-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
codegen.ts
503 lines (467 loc) · 15.7 KB
/
codegen.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import type { CompileOptions } from '../@types/compiler';
import type { AstroConfig, ValidExtensionPlugins } from '../@types/astro';
import type { Ast, TemplateNode } from '../parser/interfaces';
import type { JsxItem, TransformResult } from '../@types/astro';
import eslexer from 'es-module-lexer';
import esbuild from 'esbuild';
import path from 'path';
import { walk } from 'estree-walker';
import babelParser from '@babel/parser';
import _babelGenerator from '@babel/generator';
import { ImportDeclaration, ExportNamedDeclaration, VariableDeclarator, Identifier } from '@babel/types';
const babelGenerator: typeof _babelGenerator =
// @ts-ignore
_babelGenerator.default;
const { transformSync } = esbuild;
interface Attribute {
start: number;
end: number;
type: 'Attribute';
name: string;
value: TemplateNode[] | boolean;
}
interface CodeGenOptions {
compileOptions: CompileOptions;
filename: string;
fileID: string;
}
function internalImport(internalPath: string) {
return `/_astro_internal/${internalPath}`;
}
function getAttributes(attrs: Attribute[]): Record<string, string> {
let result: Record<string, string> = {};
for (const attr of attrs) {
if (attr.value === true) {
result[attr.name] = JSON.stringify(attr.value);
continue;
}
if (attr.value === false || attr.value === undefined) {
// note: attr.value shouldn’t be `undefined`, but a bad transform would cause a compile error here, so prevent that
continue;
}
if (attr.value.length > 1) {
result[attr.name] =
'(' +
attr.value
.map((v: TemplateNode) => {
if (v.content) {
return v.content;
} else {
return JSON.stringify(getTextFromAttribute(v));
}
})
.join('+') +
')';
continue;
}
const val = attr.value[0];
if (!val) {
result[attr.name] = '(' + val + ')';
continue;
}
switch (val.type) {
case 'MustacheTag':
result[attr.name] = '(' + val.content + ')';
continue;
case 'Text':
result[attr.name] = JSON.stringify(getTextFromAttribute(val));
continue;
default:
throw new Error(`UNKNOWN: ${val.type}`);
}
}
return result;
}
function getTextFromAttribute(attr: any): string {
if (attr.raw !== undefined) {
return attr.raw;
}
if (attr.data !== undefined) {
return attr.data;
}
throw new Error('UNKNOWN attr');
}
function generateAttributes(attrs: Record<string, string>): string {
let result = '{';
for (const [key, val] of Object.entries(attrs)) {
result += JSON.stringify(key) + ':' + val + ',';
}
return result + '}';
}
interface ComponentInfo {
type: string;
url: string;
plugin: string | undefined;
}
const defaultExtensions: Readonly<Record<string, ValidExtensionPlugins>> = {
'.astro': 'astro',
'.jsx': 'react',
'.vue': 'vue',
'.svelte': 'svelte',
};
type DynamicImportMap = Map<'vue' | 'react' | 'react-dom' | 'preact', string>;
interface GetComponentWrapperOptions {
filename: string;
astroConfig: AstroConfig;
dynamicImports: DynamicImportMap;
}
function getComponentWrapper(_name: string, { type, plugin, url }: ComponentInfo, opts: GetComponentWrapperOptions) {
const { astroConfig, dynamicImports, filename } = opts;
const { astroRoot } = astroConfig;
const [name, kind] = _name.split(':');
const currFileUrl = new URL(`file:https://${filename}`);
if (!plugin) {
throw new Error(`No supported plugin found for extension ${type}`);
}
const getComponentUrl = (ext = '.js') => {
const outUrl = new URL(url, currFileUrl);
return '/_astro/' + path.posix.relative(astroRoot.pathname, outUrl.pathname).replace(/\.[^.]+$/, ext);
};
switch (plugin) {
case 'astro': {
if (kind) {
throw new Error(`Astro does not support :${kind}`);
}
return {
wrapper: name,
wrapperImport: ``,
};
}
case 'preact': {
if (['load', 'idle', 'visible'].includes(kind)) {
return {
wrapper: `__preact_${kind}(${name}, ${JSON.stringify({
componentUrl: getComponentUrl(),
componentExport: 'default',
frameworkUrls: {
preact: dynamicImports.get('preact'),
},
})})`,
wrapperImport: `import {__preact_${kind}} from '${internalImport('render/preact.js')}';`,
};
}
return {
wrapper: `__preact_static(${name})`,
wrapperImport: `import {__preact_static} from '${internalImport('render/preact.js')}';`,
};
}
case 'react': {
if (['load', 'idle', 'visible'].includes(kind)) {
return {
wrapper: `__preact_${kind}(${name}, ${JSON.stringify({
componentUrl: getComponentUrl(),
componentExport: 'default',
frameworkUrls: {
react: dynamicImports.get('react'),
'react-dom': dynamicImports.get('react-dom'),
},
})})`,
wrapperImport: `import {__preact_${kind}} from '${internalImport('render/preact.js')}';`,
};
}
return {
wrapper: `__react_static(${name})`,
wrapperImport: `import {__react_static} from '${internalImport('render/react.js')}';`,
};
}
case 'svelte': {
if (['load', 'idle', 'visible'].includes(kind)) {
return {
wrapper: `__svelte_${kind}(${name}, ${JSON.stringify({
componentUrl: getComponentUrl('.svelte.js'),
componentExport: 'default',
})})`,
wrapperImport: `import {__svelte_${kind}} from '${internalImport('render/svelte.js')}';`,
};
}
return {
wrapper: `__svelte_static(${name})`,
wrapperImport: `import {__svelte_static} from '${internalImport('render/svelte.js')}';`,
};
}
case 'vue': {
if (['load', 'idle', 'visible'].includes(kind)) {
return {
wrapper: `__vue_${kind}(${name}, ${JSON.stringify({
componentUrl: getComponentUrl('.vue.js'),
componentExport: 'default',
frameworkUrls: {
vue: dynamicImports.get('vue'),
},
})})`,
wrapperImport: `import {__vue_${kind}} from '${internalImport('render/vue.js')}';`,
};
}
return {
wrapper: `__vue_static(${name})`,
wrapperImport: `import {__vue_static} from '${internalImport('render/vue.js')}';`,
};
}
default: {
throw new Error(`Unknown component type`);
}
}
}
function compileExpressionSafe(raw: string): string {
let { code } = transformSync(raw, {
loader: 'tsx',
jsxFactory: 'h',
jsxFragment: 'Fragment',
charset: 'utf8',
});
return code;
}
async function acquireDynamicComponentImports(plugins: Set<ValidExtensionPlugins>, resolve: (s: string) => Promise<string>): Promise<DynamicImportMap> {
const importMap: DynamicImportMap = new Map();
for (let plugin of plugins) {
switch (plugin) {
case 'vue': {
importMap.set('vue', await resolve('vue'));
break;
}
case 'react': {
importMap.set('react', await resolve('react'));
importMap.set('react-dom', await resolve('react-dom'));
break;
}
case 'preact': {
importMap.set('preact', await resolve('preact'));
break;
}
}
}
return importMap;
}
export async function codegen(ast: Ast, { compileOptions, filename, fileID }: CodeGenOptions): Promise<TransformResult> {
const { extensions = defaultExtensions, astroConfig } = compileOptions;
await eslexer.init;
const componentImports: ImportDeclaration[] = [];
const componentProps: VariableDeclarator[] = [];
const componentExports: ExportNamedDeclaration[] = [];
let script = '';
let propsStatement = '';
const importExportStatements: Set<string> = new Set();
const components: Record<string, { type: string; url: string; plugin: string | undefined }> = {};
const componentPlugins = new Set<ValidExtensionPlugins>();
if (ast.module) {
const program = babelParser.parse(ast.module.content, {
sourceType: 'module',
plugins: ['jsx', 'typescript', 'topLevelAwait'],
}).program;
const { body } = program;
let i = body.length;
while (--i >= 0) {
const node = body[i];
if (node.type === 'ImportDeclaration') {
componentImports.push(node);
body.splice(i, 1);
}
if (/^Export/.test(node.type)) {
if (node.type === 'ExportNamedDeclaration' && node.declaration?.type === 'VariableDeclaration') {
const declaration = node.declaration.declarations[0];
if ((declaration.id as Identifier).name === '__layout' || (declaration.id as Identifier).name === '__content') {
componentExports.push(node);
} else {
componentProps.push(declaration);
}
body.splice(i, 1);
}
// const replacement = extract_exports(node);
}
}
for (const componentImport of componentImports) {
const importUrl = componentImport.source.value;
const componentType = path.posix.extname(importUrl);
const componentName = path.posix.basename(importUrl, componentType);
const plugin = extensions[componentType] || defaultExtensions[componentType];
components[componentName] = {
type: componentType,
plugin,
url: importUrl,
};
if (plugin) {
componentPlugins.add(plugin);
}
importExportStatements.add(ast.module.content.slice(componentImport.start!, componentImport.end!));
}
for (const componentImport of componentExports) {
importExportStatements.add(ast.module.content.slice(componentImport.start!, componentImport.end!));
}
if (componentProps.length > 0) {
propsStatement = 'let {';
for (const componentExport of componentProps) {
propsStatement += `${(componentExport.id as Identifier).name}`;
if (componentExport.init) {
propsStatement += `= ${babelGenerator(componentExport.init!).code}`;
}
propsStatement += `,`;
}
propsStatement += `} = props;`;
}
script = propsStatement + babelGenerator(program).code;
}
const dynamicImports = await acquireDynamicComponentImports(componentPlugins, compileOptions.resolve);
let items: JsxItem[] = [];
let collectionItem: JsxItem | undefined;
let currentItemName: string | undefined;
let currentDepth = 0;
let css: string[] = [];
walk(ast.css, {
enter(node: TemplateNode) {
if (node.type === 'Style') {
css.push(node.content.styles); // if multiple <style> tags, combine together
this.skip();
}
},
leave(node: TemplateNode) {
if (node.type === 'Style') {
this.remove(); // this will be optimized in a global CSS file; remove so it‘s not accidentally inlined
}
},
});
walk(ast.html, {
enter(node: TemplateNode) {
switch (node.type) {
case 'MustacheTag':
let code = compileExpressionSafe(node.content);
let matches: RegExpExecArray[] = [];
let match: RegExpExecArray | null | undefined;
const H_COMPONENT_SCANNER = /h\(['"]?([A-Z].*?)['"]?,/gs;
const regex = new RegExp(H_COMPONENT_SCANNER);
while ((match = regex.exec(code))) {
matches.push(match);
}
for (const match of matches.reverse()) {
const name = match[1];
const [componentName, componentKind] = name.split(':');
if (!components[componentName]) {
throw new Error(`Unknown Component: ${componentName}`);
}
const { wrapper, wrapperImport } = getComponentWrapper(name, components[componentName], { astroConfig, dynamicImports, filename });
if (wrapperImport) {
importExportStatements.add(wrapperImport);
}
if (wrapper !== name) {
code = code.slice(0, match.index + 2) + wrapper + code.slice(match.index + match[0].length - 1);
}
}
collectionItem!.jsx += `,(${code.trim().replace(/\;$/, '')})`;
this.skip();
return;
case 'Comment':
return;
case 'Fragment':
// Ignore if its the top level fragment
// This should be cleaned up, but right now this is how the old thing worked
if (!collectionItem) {
return;
}
break;
case 'Slot':
case 'Head':
case 'InlineComponent':
case 'Title':
case 'Element': {
const name: string = node.name;
if (!name) {
throw new Error('AHHHH');
}
const attributes = getAttributes(node.attributes);
currentDepth++;
currentItemName = name;
if (!collectionItem) {
collectionItem = { name, jsx: '' };
items.push(collectionItem);
}
collectionItem.jsx += collectionItem.jsx === '' ? '' : ',';
if (node.type === 'Slot') {
collectionItem.jsx += `(children`;
return;
}
const COMPONENT_NAME_SCANNER = /^[A-Z]/;
if (!COMPONENT_NAME_SCANNER.test(name)) {
collectionItem.jsx += `h("${name}", ${attributes ? generateAttributes(attributes) : 'null'}`;
return;
}
const [componentName, componentKind] = name.split(':');
const componentImportData = components[componentName];
if (!componentImportData) {
throw new Error(`Unknown Component: ${componentName}`);
}
const { wrapper, wrapperImport } = getComponentWrapper(name, components[componentName], { astroConfig, dynamicImports, filename });
if (wrapperImport) {
importExportStatements.add(wrapperImport);
}
collectionItem.jsx += `h(${wrapper}, ${attributes ? generateAttributes(attributes) : 'null'}`;
return;
}
case 'Attribute': {
this.skip();
return;
}
case 'Style': {
css.push(node.content.styles); // if multiple <style> tags, combine together
this.skip();
return;
}
case 'Text': {
const text = getTextFromAttribute(node);
if (!text.trim()) {
return;
}
if (!collectionItem) {
throw new Error('Not possible! TEXT:' + text);
}
if (currentItemName === 'script' || currentItemName === 'code') {
collectionItem.jsx += ',' + JSON.stringify(text);
return;
}
collectionItem.jsx += ',' + JSON.stringify(text);
return;
}
default:
throw new Error('Unexpected (enter) node type: ' + node.type);
}
},
leave(node, parent, prop, index) {
switch (node.type) {
case 'Text':
case 'MustacheTag':
case 'Attribute':
case 'Comment':
return;
case 'Fragment':
if (!collectionItem) {
return;
}
case 'Slot':
case 'Head':
case 'Body':
case 'Title':
case 'Element':
case 'InlineComponent':
if (!collectionItem) {
throw new Error('Not possible! CLOSE ' + node.name);
}
collectionItem.jsx += ')';
currentDepth--;
if (currentDepth === 0) {
collectionItem = undefined;
}
return;
case 'Style': {
this.remove(); // this will be optimized in a global CSS file; remove so it‘s not accidentally inlined
return;
}
default:
throw new Error('Unexpected (leave) node type: ' + node.type);
}
},
});
return {
script: script,
imports: Array.from(importExportStatements),
items,
css: css.length ? css.join('\n\n') : undefined,
};
}