/
addIdentifierToLinariaPreval.ts
91 lines (82 loc) · 2.45 KB
/
addIdentifierToLinariaPreval.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
import type { NodePath, Scope } from '@babel/traverse';
import type {
ExportNamedDeclaration,
ExpressionStatement,
Identifier,
ObjectExpression,
ObjectProperty,
Program,
} from '@babel/types';
import { createId } from './createId';
import { reference } from './scopeHelpers';
export function getOrAddLinariaPreval(
scope: Scope
): NodePath<ObjectExpression> {
const rootScope = scope.getProgramParent();
const programPath = rootScope.path as NodePath<Program>;
let object = programPath.getData('__linariaPreval');
if (object) {
return object;
}
if (programPath.node.sourceType === 'script') {
// CJS exports.__linariaPreval = {};
const prevalExport: ExpressionStatement = {
expression: {
type: 'AssignmentExpression',
operator: '=',
left: {
computed: false,
object: createId('exports'),
property: createId('__linariaPreval'),
type: 'MemberExpression',
},
right: {
properties: [],
type: 'ObjectExpression',
},
},
type: 'ExpressionStatement',
};
const [inserted] = programPath.pushContainer('body', [prevalExport]);
object = inserted.get('expression.right') as NodePath<ObjectExpression>;
} else {
// ESM export const __linariaPreval = {};
const prevalExport: ExportNamedDeclaration = {
declaration: {
declarations: [
{
id: createId('__linariaPreval'),
init: {
properties: [],
type: 'ObjectExpression',
},
type: 'VariableDeclarator',
},
],
kind: 'const',
type: 'VariableDeclaration',
},
specifiers: [],
type: 'ExportNamedDeclaration',
};
const [inserted] = programPath.pushContainer('body', [prevalExport]);
object = inserted.get(
'declaration.declarations.0.init'
) as NodePath<ObjectExpression>;
}
programPath.setData('__linariaPreval', object);
return object;
}
export function addIdentifierToLinariaPreval(scope: Scope, name: string) {
const rootScope = scope.getProgramParent();
const object = getOrAddLinariaPreval(rootScope);
const newProperty: ObjectProperty = {
type: 'ObjectProperty',
key: createId(name),
value: createId(name),
computed: false,
shorthand: false,
};
const [inserted] = object.pushContainer('properties', [newProperty]);
reference(inserted.get('value') as NodePath<Identifier>);
}