@komaci/esm-generator 240.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/build/__tests__/compile-generated-module-fixtures.spec.d.ts +2 -0
  2. package/build/__tests__/compile-generated-module-fixtures.spec.js +45 -0
  3. package/build/__tests__/fixtures-combined-files/exclude-comps-unused-import-prop/actual.d.ts +5 -0
  4. package/build/__tests__/fixtures-combined-files/exclude-comps-unused-import-prop/actual.js +28 -0
  5. package/build/__tests__/fixtures-combined-files/exclude-partial-classProps-indirect-importRef-getter/actual.d.ts +28 -0
  6. package/build/__tests__/fixtures-combined-files/exclude-partial-classProps-indirect-importRef-getter/actual.js +144 -0
  7. package/build/__tests__/fixtures-combined-files/exclude-total-unused-import-getter-from-one/actual.d.ts +8 -0
  8. package/build/__tests__/fixtures-combined-files/exclude-total-unused-import-getter-from-one/actual.js +35 -0
  9. package/build/__tests__/fixtures-combined-files/exclude-total-unused-import-getter-from-two/actual.d.ts +9 -0
  10. package/build/__tests__/fixtures-combined-files/exclude-total-unused-import-getter-from-two/actual.js +39 -0
  11. package/build/__tests__/fixtures-combined-files/exclude-wire-unused-import-prop/actual.d.ts +6 -0
  12. package/build/__tests__/fixtures-combined-files/exclude-wire-unused-import-prop/actual.js +34 -0
  13. package/build/__tests__/fixtures-combined-files/image-type/actual.d.ts +12 -0
  14. package/build/__tests__/fixtures-combined-files/image-type/actual.js +41 -0
  15. package/build/__tests__/fixtures-combined-files/include-all-indirect-importRef-getter-complex/actual.d.ts +13 -0
  16. package/build/__tests__/fixtures-combined-files/include-all-indirect-importRef-getter-complex/actual.js +75 -0
  17. package/build/__tests__/fixtures-combined-files/include-class-prop-indirect-importRef-getter/actual.d.ts +17 -0
  18. package/build/__tests__/fixtures-combined-files/include-class-prop-indirect-importRef-getter/actual.js +99 -0
  19. package/build/__tests__/fixtures-combined-files/include-comps-used-import-prop/actual.d.ts +5 -0
  20. package/build/__tests__/fixtures-combined-files/include-comps-used-import-prop/actual.js +28 -0
  21. package/build/__tests__/fixtures-combined-files/include-template-strings/actual.d.ts +9 -0
  22. package/build/__tests__/fixtures-combined-files/include-template-strings/actual.js +41 -0
  23. package/build/__tests__/fixtures-combined-files/include-used-import-getter/actual.d.ts +8 -0
  24. package/build/__tests__/fixtures-combined-files/include-used-import-getter/actual.js +38 -0
  25. package/build/__tests__/fixtures-combined-files/include-wire-used-import-prop/actual.d.ts +6 -0
  26. package/build/__tests__/fixtures-combined-files/include-wire-used-import-prop/actual.js +34 -0
  27. package/build/__tests__/fixtures-combined-files/unsupported-wire-from-supported-namespace/actual.d.ts +5 -0
  28. package/build/__tests__/fixtures-combined-files/unsupported-wire-from-supported-namespace/actual.js +19 -0
  29. package/build/__tests__/fixtures-script-files/class-extends-multiple-with-separate-imports/actual.d.ts +8 -0
  30. package/build/__tests__/fixtures-script-files/class-extends-multiple-with-separate-imports/actual.js +17 -0
  31. package/build/__tests__/fixtures-script-files/class-extends-separate-imports/actual.d.ts +4 -0
  32. package/build/__tests__/fixtures-script-files/class-extends-separate-imports/actual.js +13 -0
  33. package/build/__tests__/fixtures-script-files/class-extends-separate-imports-alias/actual.d.ts +4 -0
  34. package/build/__tests__/fixtures-script-files/class-extends-separate-imports-alias/actual.js +10 -0
  35. package/build/__tests__/fixtures-script-files/class-props/actual.d.ts +25 -0
  36. package/build/__tests__/fixtures-script-files/class-props/actual.js +92 -0
  37. package/build/__tests__/fixtures-script-files/empty-class/actual.d.ts +3 -0
  38. package/build/__tests__/fixtures-script-files/empty-class/actual.js +7 -0
  39. package/build/__tests__/fixtures-script-files/empty-doc/actual.d.ts +1 -0
  40. package/build/__tests__/fixtures-script-files/empty-doc/actual.js +2 -0
  41. package/build/__tests__/fixtures-script-files/empty-wire/actual.d.ts +4 -0
  42. package/build/__tests__/fixtures-script-files/empty-wire/actual.js +16 -0
  43. package/build/__tests__/fixtures-script-files/exclude-wire-unused-import-prop/actual.d.ts +6 -0
  44. package/build/__tests__/fixtures-script-files/exclude-wire-unused-import-prop/actual.js +34 -0
  45. package/build/__tests__/fixtures-script-files/exports/actual.d.ts +21 -0
  46. package/build/__tests__/fixtures-script-files/exports/actual.js +63 -0
  47. package/build/__tests__/fixtures-script-files/imports/actual.d.ts +10 -0
  48. package/build/__tests__/fixtures-script-files/imports/actual.js +76 -0
  49. package/build/__tests__/fixtures-script-files/imports-namespaced/actual.d.ts +9 -0
  50. package/build/__tests__/fixtures-script-files/imports-namespaced/actual.js +59 -0
  51. package/build/__tests__/fixtures-script-files/include-wire-unused-import-prop/actual.d.ts +6 -0
  52. package/build/__tests__/fixtures-script-files/include-wire-unused-import-prop/actual.js +34 -0
  53. package/build/__tests__/fixtures-script-files/inheritance-imports-default/actual.d.ts +3 -0
  54. package/build/__tests__/fixtures-script-files/inheritance-imports-default/actual.js +10 -0
  55. package/build/__tests__/fixtures-script-files/inheritance-imports-local/actual.d.ts +8 -0
  56. package/build/__tests__/fixtures-script-files/inheritance-imports-local/actual.js +24 -0
  57. package/build/__tests__/fixtures-script-files/inheritance-imports-named/actual.d.ts +4 -0
  58. package/build/__tests__/fixtures-script-files/inheritance-imports-named/actual.js +17 -0
  59. package/build/__tests__/fixtures-script-files/inheritance-parent-unresolved/actual.d.ts +4 -0
  60. package/build/__tests__/fixtures-script-files/inheritance-parent-unresolved/actual.js +17 -0
  61. package/build/__tests__/fixtures-script-files/unsupported-wire-from-supported-namespace/actual.d.ts +5 -0
  62. package/build/__tests__/fixtures-script-files/unsupported-wire-from-supported-namespace/actual.js +19 -0
  63. package/build/__tests__/fixtures-script-files/wire-basic/actual.d.ts +7 -0
  64. package/build/__tests__/fixtures-script-files/wire-basic/actual.js +30 -0
  65. package/build/__tests__/fixtures-script-files/wire-functions/actual.d.ts +12 -0
  66. package/build/__tests__/fixtures-script-files/wire-functions/actual.js +46 -0
  67. package/build/__tests__/fixtures-script-files/wire-imports/actual.d.ts +10 -0
  68. package/build/__tests__/fixtures-script-files/wire-imports/actual.js +59 -0
  69. package/build/__tests__/fixtures-source-code/badImportRef.d.ts +4 -0
  70. package/build/__tests__/fixtures-source-code/badImportRef.js +21 -0
  71. package/build/__tests__/fixtures-source-code/generalMockSourceCode.d.ts +5 -0
  72. package/build/__tests__/fixtures-source-code/generalMockSourceCode.js +93 -0
  73. package/build/__tests__/general-komaci-docs/assorted-template-strings/source.d.ts +9 -0
  74. package/build/__tests__/general-komaci-docs/assorted-template-strings/source.js +41 -0
  75. package/build/__tests__/general-komaci-docs/getters-and-compositions-collisions/source.d.ts +6 -0
  76. package/build/__tests__/general-komaci-docs/getters-and-compositions-collisions/source.js +31 -0
  77. package/build/__tests__/general-komaci-docs/import-types/source.d.ts +18 -0
  78. package/build/__tests__/general-komaci-docs/import-types/source.js +104 -0
  79. package/build/__tests__/general-komaci-docs/import-types/validationStuff.d.ts +18 -0
  80. package/build/__tests__/general-komaci-docs/import-types/validationStuff.js +63 -0
  81. package/build/__tests__/general-komaci-docs/template-component/source.d.ts +8 -0
  82. package/build/__tests__/general-komaci-docs/template-component/source.js +34 -0
  83. package/build/__tests__/index.spec.d.ts +2 -0
  84. package/build/__tests__/index.spec.js +124 -0
  85. package/build/__tests__/komaci-ast-unit.spec.d.ts +2 -0
  86. package/build/__tests__/komaci-ast-unit.spec.js +628 -0
  87. package/build/__tests__/komaci-bundle-module.fixtures.spec.d.ts +2 -0
  88. package/build/__tests__/komaci-bundle-module.fixtures.spec.js +75 -0
  89. package/build/__tests__/komaci-script-module.fixtures.spec.d.ts +2 -0
  90. package/build/__tests__/komaci-script-module.fixtures.spec.js +66 -0
  91. package/build/__tests__/komaci-template-module.fixtures.spec.d.ts +2 -0
  92. package/build/__tests__/komaci-template-module.fixtures.spec.js +56 -0
  93. package/build/__tests__/modGenScript.spec.d.ts +2 -0
  94. package/build/__tests__/modGenScript.spec.js +110 -0
  95. package/build/__tests__/modGenTemplate.spec.d.ts +2 -0
  96. package/build/__tests__/modGenTemplate.spec.js +196 -0
  97. package/build/__tests__/shared.spec.d.ts +2 -0
  98. package/build/__tests__/shared.spec.js +62 -0
  99. package/build/__tests__/templateStrings.spec.d.ts +2 -0
  100. package/build/__tests__/templateStrings.spec.js +130 -0
  101. package/build/index.d.ts +4 -0
  102. package/build/index.js +130 -0
  103. package/build/modGenScript.d.ts +38 -0
  104. package/build/modGenScript.js +1027 -0
  105. package/build/modGenTemplate.d.ts +37 -0
  106. package/build/modGenTemplate.js +402 -0
  107. package/build/shared.d.ts +170 -0
  108. package/build/shared.js +588 -0
  109. package/build/types.d.ts +132 -0
  110. package/build/types.js +14 -0
  111. package/package.json +40 -0
@@ -0,0 +1,588 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.addPropertyFunction = exports.updateKomaciDocumentWithValidTemplatedStrings = exports.sanitizeFunction = exports.mapRealNameToGenerated = exports.hoistTemplateStrings = exports.processTemplateStrings = exports.updateKomaciDocumentWithValidGetters = exports.transformGetters = exports.processGetters = exports.getComponentSrcJs = exports.valueToExpression = exports.bindingRootToExpression = exports.bindingToExpression = exports.primitiveToExpression = exports.getFactoryFuncDeclaration = exports.retrieveImportInfo = exports.updateImportInfoState = exports.ID = exports.PRIMING_FUNCTION = exports.ERROR_FUNCTION = exports.TEMPLATED_STRING_FUNCTION = exports.GETTER_FUNCTION = exports.WIRE_FUNCTION = exports.USER_VARIABLE_PREFIX = exports.UNRESOLVED = exports.ADG_IMPORT_SUFFIX = exports.PROPS = exports.CONTEXT = exports.ERROR_PREFIX = void 0;
23
+ const t = __importStar(require("@babel/types"));
24
+ const types_1 = require("./types");
25
+ const static_analyzer_1 = require("@komaci/static-analyzer");
26
+ const common_shared_1 = require("@komaci/common-shared");
27
+ exports.ERROR_PREFIX = '[komaci esm-generator] ';
28
+ exports.CONTEXT = 'ctx';
29
+ exports.PROPS = 'props';
30
+ exports.ADG_IMPORT_SUFFIX = 'getAdgDefinition';
31
+ exports.UNRESOLVED = 'unresolved';
32
+ exports.USER_VARIABLE_PREFIX = 'user_var_';
33
+ exports.WIRE_FUNCTION = 'WireFunction';
34
+ exports.GETTER_FUNCTION = 'GetterFunction';
35
+ exports.TEMPLATED_STRING_FUNCTION = 'TemplatedStringFunction';
36
+ exports.ERROR_FUNCTION = 'ErrorFunction';
37
+ exports.PRIMING_FUNCTION = 'PrimingFunction';
38
+ exports.ID = {
39
+ CONTEXT: t.identifier(exports.CONTEXT),
40
+ PROPS: t.identifier(exports.PROPS),
41
+ FACTORY: t.identifier('fct'),
42
+ COMPOSED_GRAPH_FUNC: t.identifier('cg'),
43
+ ITERATION_FUNC: t.identifier('i'),
44
+ UNRESOLVED_FUNC: t.identifier('u'),
45
+ SLOT_FUNC: t.identifier('s'),
46
+ ELEMENT_FUNC: t.identifier('e'),
47
+ ADG_FUNC: t.identifier('adg'),
48
+ SLOT: t.identifier('slot'),
49
+ COMPONENT_ID: t.identifier('componentId'),
50
+ UNDEFINED: t.identifier('undefined'),
51
+ PROP_API: t.identifier('a'),
52
+ PROP_INIT: t.identifier('i'),
53
+ PROP_FUNC: t.identifier('f'),
54
+ PROP_GETTER: t.identifier('g'),
55
+ DEFAULT_COMP: t.identifier('comp1'),
56
+ FUNC_ID: t.identifier('f'),
57
+ FUNC_NAME: t.identifier('fN'),
58
+ FUNC_TYPE: t.identifier('t'),
59
+ FUNC_CONFIG: t.identifier('c'),
60
+ FUNC_INPUT: t.identifier('in'),
61
+ WIRE_TYPE: t.identifier('wt'),
62
+ UNRESOLVED_VALUE: t.identifier('unresolved'),
63
+ BATCH_FUNC_ID: t.identifier('b'),
64
+ BATCH_FUNC_NAME: t.identifier('bN'),
65
+ REDUCER_FUNC_ID: t.identifier('r'),
66
+ IMG_SRC: t.identifier('src'),
67
+ IMG_FUNC: t.identifier('img'),
68
+ };
69
+ /**
70
+ * Retrieve info about an import given its reference value (e.g. 0/names/0), while initializing/updating its usageState, as well
71
+ * as updating required factory functions (if we are returning an ImportInfo for an unsupported namespace).
72
+ * @param generatorState the GeneratorState
73
+ * @param importRefValue import reference value, as a string. ex: "0/names/0"
74
+ * @param isScriptFile boolean indicating whether we are calling the method while processing a Script (JS file)[true], or a template (HTML file)[false]
75
+ * @param usageState ImportUsageState enum that represents the way the import will be used. Some example values are: composedadg, wireadapter,
76
+ * getter, initialvalue, wireconfig, parentadg
77
+ * @returns ImportInfo object, updated with latest usageState
78
+ */
79
+ function updateImportInfoState(generatorState, importRefValue, isScriptFile, usageState) {
80
+ const importInfo = isScriptFile
81
+ ? generatorState.scriptGenState.importRefsMap[importRefValue]
82
+ : generatorState.templateGenState.importRefsMap[importRefValue];
83
+ if (!importInfo) {
84
+ throw new Error(exports.ERROR_PREFIX + 'komaciDoc contains invalid import reference');
85
+ }
86
+ if (isScriptFile) {
87
+ importInfo.importUsages.add(usageState);
88
+ if (usageState === types_1.ImportUsageState.wireadapter) {
89
+ generatorState.scriptGenState.importInfosForWireAdapter.add(importInfo);
90
+ }
91
+ if (!(0, static_analyzer_1.isSupportedNamespace)(importInfo.resourceName)) {
92
+ generatorState.scriptGenState.requiredFactoryFunctions.add(exports.ID.UNRESOLVED_VALUE);
93
+ }
94
+ }
95
+ return importInfo;
96
+ }
97
+ exports.updateImportInfoState = updateImportInfoState;
98
+ /**
99
+ * Retrieve info about an import given its reference value (e.g. 0/names/0), without updating its state.
100
+ * To update ImportInfo state, see method updateImportInfoState.
101
+ * @param generatorState the current GeneratorState for this module generation
102
+ * @param importRefValue the import reference value to use in looking up the ImportInfo. ex: "0/names/0"
103
+ * @param isScriptFile boolean determining whether we are processing a script (JS) or template (HTML)
104
+ * @returns ImportInfo corresponding to the importRefValue in the generatorState
105
+ */
106
+ function retrieveImportInfo(generatorState, importRefValue, isScriptFile) {
107
+ return isScriptFile
108
+ ? generatorState.scriptGenState.importRefsMap[importRefValue]
109
+ : generatorState.templateGenState.importRefsMap[importRefValue];
110
+ }
111
+ exports.retrieveImportInfo = retrieveImportInfo;
112
+ // Return the variable declaration done via destructuring the factory object
113
+ // (e.g. const { i, cg } = fct;) or undefined if no fct functions are used.
114
+ function getFactoryFuncDeclaration(generatorState, isScriptFile) {
115
+ const fctFunctions = [];
116
+ const requiredFactoryFunctionsSet = isScriptFile
117
+ ? generatorState.scriptGenState.requiredFactoryFunctions
118
+ : generatorState.templateGenState.requiredFactoryFunctions;
119
+ // Only functions which are used within the module are actually assigned.
120
+ requiredFactoryFunctionsSet.forEach((funcId) => {
121
+ fctFunctions.push(t.objectProperty(funcId, funcId, false, true));
122
+ });
123
+ if (fctFunctions.length) {
124
+ const declarator = t.variableDeclarator(t.objectPattern(fctFunctions), exports.ID.FACTORY);
125
+ return t.variableDeclaration('const', [declarator]);
126
+ }
127
+ }
128
+ exports.getFactoryFuncDeclaration = getFactoryFuncDeclaration;
129
+ // Convert a Komaci primitive value to babel expression.
130
+ function primitiveToExpression(generatorState, primitive) {
131
+ switch (typeof primitive.value) {
132
+ case 'number':
133
+ return t.numericLiteral(primitive.value);
134
+ case 'string':
135
+ return t.stringLiteral(primitive.value);
136
+ case 'boolean':
137
+ return t.booleanLiteral(primitive.value);
138
+ case 'undefined':
139
+ return exports.ID.UNDEFINED;
140
+ default:
141
+ return t.nullLiteral();
142
+ }
143
+ }
144
+ exports.primitiveToExpression = primitiveToExpression;
145
+ // Convert binding (or PropertyReference) to a babel expr (e.g. record.value?.Id).
146
+ function bindingToExpression(generatorState, binding, isScriptFile) {
147
+ if (!binding.value.length) {
148
+ if (binding.type === 'Binding') {
149
+ throw new Error(exports.ERROR_PREFIX + 'encountered empty binding');
150
+ }
151
+ throw new Error(exports.ERROR_PREFIX + 'encountered empty property reference');
152
+ }
153
+ const segments = binding.value.split('/'); // segments[0] === propertyName
154
+ let chainingStartIdx;
155
+ let iteratorBinding = false;
156
+ // Am I in the context of an iteration?
157
+ if (generatorState.iterationContext.includes(segments[0])) {
158
+ // Referencing property of an iteration
159
+ iteratorBinding = true; // flag to distinguish whether we are in the context of an iteration
160
+ chainingStartIdx = 1;
161
+ }
162
+ else {
163
+ // Not referencing property of an iteration
164
+ // Are we referencing a property in the adg of the associated composition? Add to Set of reference properties on reaching this else
165
+ if (!isScriptFile) {
166
+ // put property into the Set of strings, and later convert into an array of stringLiterals later for arg 4
167
+ generatorState.templateGenState.refProps.add(segments[0]);
168
+ }
169
+ chainingStartIdx = 2;
170
+ segments.unshift(exports.CONTEXT, exports.PROPS); // Referencing property in context, so prepend ctx.props
171
+ }
172
+ // Build member expression w/ optional chaining to prevent runtime TypeError.
173
+ // If we are in the context of an iterator binding, we must prepend the user variable prefix
174
+ let expr = iteratorBinding
175
+ ? t.identifier(exports.USER_VARIABLE_PREFIX + segments[0])
176
+ : t.identifier(segments[0]);
177
+ for (let i = 1; i < segments.length; ++i) {
178
+ expr = t.optionalMemberExpression(expr, t.identifier(segments[i]), false, i > chainingStartIdx);
179
+ }
180
+ return expr;
181
+ }
182
+ exports.bindingToExpression = bindingToExpression;
183
+ // Convert binding root (or PropertyReference) to a babel expr (e.g. ctx.prop.record).
184
+ function bindingRootToExpression(generatorState, binding) {
185
+ if (!binding.value.length) {
186
+ if (binding.type === 'Binding') {
187
+ throw new Error(exports.ERROR_PREFIX + 'encountered empty binding');
188
+ }
189
+ throw new Error(exports.ERROR_PREFIX + 'encountered empty property reference');
190
+ }
191
+ const segments = binding.value.split('/').slice(0, 1);
192
+ let iterationBinding = false;
193
+ // not referencing property of an iteration.
194
+ if (!generatorState.iterationContext.includes(segments[0])) {
195
+ // Referencing property in context, so prepend ctx.props
196
+ segments.unshift(exports.CONTEXT, exports.PROPS);
197
+ }
198
+ else {
199
+ iterationBinding = true; // we are referencing a property of an iteration
200
+ }
201
+ // Build member expression w/ optional chaining to prevent runtime TypeError.
202
+ // if we are in the context of an iteration, prepend the user variable prefix
203
+ let expr = iterationBinding
204
+ ? t.identifier(exports.USER_VARIABLE_PREFIX + segments[0])
205
+ : t.identifier(segments[0]);
206
+ for (let i = 1; i < segments.length; ++i) {
207
+ expr = t.memberExpression(expr, t.identifier(segments[i]), false);
208
+ }
209
+ return expr;
210
+ }
211
+ exports.bindingRootToExpression = bindingRootToExpression;
212
+ // Convert any possible value within a Komaci ADG to a babel expression.
213
+ function valueToExpression(generatorState, komaciValue, isScriptFile, usageState) {
214
+ let newExpression;
215
+ switch (komaciValue.type) {
216
+ case 'PrimitiveValue':
217
+ newExpression = primitiveToExpression(generatorState, komaciValue);
218
+ break;
219
+ case 'ImportReference': {
220
+ const importInfo = updateImportInfoState(
221
+ // called from a lot of different places. Add a way to indicate where getImportInfo is being used.
222
+ generatorState, komaciValue.value, isScriptFile, usageState);
223
+ newExpression = importInfo.localName;
224
+ if (newExpression?.name !== exports.UNRESOLVED && komaciValue.namespacedMember) {
225
+ newExpression = t.memberExpression(newExpression, t.identifier(komaciValue.namespacedMember));
226
+ }
227
+ break;
228
+ }
229
+ case 'PropertyReference': {
230
+ return bindingToExpression(generatorState, komaciValue, isScriptFile);
231
+ }
232
+ case 'Binding': {
233
+ const objProps = [];
234
+ objProps.push(t.objectProperty(t.stringLiteral('url'), bindingToExpression(generatorState, komaciValue, isScriptFile)));
235
+ return t.objectExpression(objProps);
236
+ }
237
+ case 'Unresolved':
238
+ isScriptFile
239
+ ? generatorState.scriptGenState.requiredFactoryFunctions.add(exports.ID.UNRESOLVED_VALUE)
240
+ : generatorState.templateGenState.requiredFactoryFunctions.add(exports.ID.UNRESOLVED_VALUE);
241
+ newExpression = exports.ID.UNRESOLVED_VALUE;
242
+ break;
243
+ case 'ArrayValue': {
244
+ const elements = [];
245
+ komaciValue.value.forEach((element) => {
246
+ elements.push(valueToExpression(generatorState, element, isScriptFile, usageState));
247
+ });
248
+ newExpression = t.arrayExpression(elements);
249
+ break;
250
+ }
251
+ case 'ObjectValue': {
252
+ const objProps = [];
253
+ for (const [propName, propValue] of Object.entries(komaciValue.value)) {
254
+ objProps.push(t.objectProperty(t.stringLiteral(propName), valueToExpression(generatorState, propValue, isScriptFile, usageState)));
255
+ }
256
+ newExpression = t.objectExpression(objProps);
257
+ break;
258
+ }
259
+ }
260
+ if (!newExpression) {
261
+ throw new Error(`${exports.ERROR_PREFIX}: Unrecognized value type`);
262
+ }
263
+ return newExpression;
264
+ }
265
+ exports.valueToExpression = valueToExpression;
266
+ /**
267
+ * Retrieve the file path for the js of a component
268
+ * @param generatorState GeneratorState containg the GeneratorInput, which in turn contains the JS raw source file
269
+ * @returns Returns raw source code as string for the js of a component if it exists in the srcFileMap
270
+ * Returns undefined if no JS source file (whose filename also matches the LWC module name) was included in the
271
+ * GeneratorState.GeneratorInput by lwc-platform, other calling code.
272
+ */
273
+ function getComponentSrcJs(generatorState) {
274
+ let sourceCode;
275
+ const moduleName = generatorState.input.moduleInfo.name;
276
+ if (generatorState.input.srcFileMap) {
277
+ const filename = Object.keys(generatorState.input.srcFileMap).find((filename) => filename.endsWith('.js') && filename.startsWith(moduleName));
278
+ if (filename) {
279
+ sourceCode = generatorState.input.srcFileMap[filename];
280
+ }
281
+ }
282
+ return sourceCode;
283
+ }
284
+ exports.getComponentSrcJs = getComponentSrcJs;
285
+ /**
286
+ * AST is traversed to see if they contain getter functions that are not valid. For each getter that is valid, we will
287
+ * update contextual information about the class and pass back info about the valid getters.
288
+ *
289
+ * @param {ClassPropertyContexts} properties the Map of properties metadata, which tells whether a property is used by a wire functions
290
+ * @param {ModuleContext} moduleContext Contextual info about the module itself
291
+ * @param {ModuleLevelConsumption} moduleLevelConsumption Details about how things are consuming module level entities. NOTE: This is updated in here for import usage
292
+ * @param {t.File} ast The ast for the module
293
+ * @returns Information about valid getters to be added to the resolvable Module.
294
+ */
295
+ function processGetters(properties, moduleContext, moduleLevelConsumption, getterMethodPaths) {
296
+ return (getterMethodPaths
297
+ // filter removes invalid getters from the array
298
+ .filter((getter) => (0, static_analyzer_1.validateGetter)(getter, moduleContext, false))
299
+ // map changes the item at each index to be an instance of ValidGetterContext
300
+ .map((getter, index) => {
301
+ const { identifiers } = (0, common_shared_1.implicitConsumptionMetadata)(getter, moduleContext.astContext.classProperties, // info on all class properties
302
+ moduleContext.astContext.importDeclarations, // import metadata info
303
+ moduleLevelConsumption);
304
+ if (identifiers.length > 0) {
305
+ identifiers.forEach((identifier) => {
306
+ properties.get(identifier);
307
+ });
308
+ }
309
+ return {
310
+ getter,
311
+ generatedName: `g${index}`,
312
+ memberUsage: identifiers,
313
+ };
314
+ })
315
+ .map((getter) => {
316
+ (0, common_shared_1.updatePropertyUsage)((0, common_shared_1.getClassMethodName)(getter.getter), getter.memberUsage, properties, common_shared_1.PropertyTypes.GETTER);
317
+ return getter;
318
+ }));
319
+ }
320
+ exports.processGetters = processGetters;
321
+ /**
322
+ * This method takes in the generatedCombinedModule AST, the original source AST, the import references map from the
323
+ * GeneratorState, and the valid getter contexts (which contain the babel NodePaths to the getters) and transforms the generated
324
+ * combined module AST by hoisting any passed-in valid getters into top-level getter methods, adding `props` as input paramater to the
325
+ * same getter methods, replacing this.<var> references in the getter method to props.<var>, as well as replacing references of
326
+ * valid imports references in the getter with corresponding Komaci module unique identifiers (i1, i2, i3,...).
327
+ *
328
+ * @param genCombinedModuleAST the AST of the generated combined module
329
+ * @param importReferencesMap Map of importReferences (ex: "0/names/0") to ImportInfo, which comes from GeneratorState's scriptGenState.importRefsMap
330
+ * @param getterImportUsage All the imports decalred in the ast
331
+ * @param validGetterContexts Array of ValidGetterContext object which contain the NodePath representing the getter, as well as an Array<string> of
332
+ * memberUsages within the same getter.
333
+ */
334
+ function transformGetters(genCombinedModuleAST, importReferencesMap, getterImportUsage, validGetterContexts) {
335
+ const trueToGeneratedImport = mapRealNameToGenerated(importReferencesMap);
336
+ let body = [];
337
+ const hoistedGetters = [];
338
+ for (const getterCtx of validGetterContexts) {
339
+ sanitizeFunction(getterCtx.getter, getterImportUsage, trueToGeneratedImport);
340
+ // hoist getters to module-level
341
+ // use direct-access here since it is possible for this portion
342
+ const program = genCombinedModuleAST.program;
343
+ body = program.body;
344
+ const propsId = t.identifier(exports.PROPS);
345
+ const hoistedGetter = t.functionDeclaration(t.identifier(getterCtx.generatedName), [propsId], // make 'props' an input parameter to the hoisted getter
346
+ getterCtx.getter.node.body);
347
+ hoistedGetters.push(hoistedGetter);
348
+ }
349
+ // add hoisted getter functions in the array of Statements for the program body, in the first spot after
350
+ // all of the ImportDeclarations
351
+ const insertBeforeIndex = body.findIndex((statement) => statement.type !== 'ImportDeclaration');
352
+ body.splice(insertBeforeIndex, 0, ...hoistedGetters);
353
+ }
354
+ exports.transformGetters = transformGetters;
355
+ /**
356
+ * Function to update the Komaci Document with validated getter information. This function will update the functions array in the
357
+ * export default adg along with the property references in the property array.
358
+ * @param komaciScriptDoc the komaci document
359
+ * @param validGetterContext a collection
360
+ */
361
+ function updateKomaciDocumentWithValidGetters(komaciScriptDoc, validGetterContext) {
362
+ if (komaciScriptDoc.exports) {
363
+ //get the exort mapping for the export default
364
+ const defaultExportMapping = komaciScriptDoc.exports['default'];
365
+ if (defaultExportMapping && defaultExportMapping.type === 'AdgReference') {
366
+ const defaultExportAdg = komaciScriptDoc.adgs?.[defaultExportMapping.value];
367
+ //foreach getter in the context.
368
+ validGetterContext.forEach((getter) => {
369
+ //Get the name of the getter.
370
+ const getterName = getter.getter.node.key.name;
371
+ const inputArr = {
372
+ type: 'ArrayValue',
373
+ value: [],
374
+ };
375
+ getter.memberUsage.forEach((member) => {
376
+ const primVal = {
377
+ type: 'PrimitiveValue',
378
+ value: member,
379
+ };
380
+ inputArr.value.push(primVal);
381
+ });
382
+ //create a new functionType obj with getter information.
383
+ const validGetterFunction = {
384
+ type: exports.GETTER_FUNCTION,
385
+ reference: { type: 'InternalReference', value: getter.generatedName },
386
+ input: [inputArr],
387
+ location: undefined,
388
+ };
389
+ //if we have an adg make changes to it.
390
+ if (defaultExportAdg) {
391
+ getter.f_index = addPropertyFunction(defaultExportAdg, getterName, validGetterFunction);
392
+ }
393
+ });
394
+ }
395
+ }
396
+ }
397
+ exports.updateKomaciDocumentWithValidGetters = updateKomaciDocumentWithValidGetters;
398
+ /**
399
+ * Validate what templates are good and then uplift the metadata about how they interact with other portions of the modules.
400
+ * i.e. import, property references, used in priming
401
+ * @param {ClassPropertyContexts} properties the Map of properties metadata, which tells whether a property is used by a wire functions
402
+ * @param {ModuleContext} moduleContext Contextual info about the module itself
403
+ * @param {ModuleLevelConsumption} moduleLevelConsumption Details about how things are consuming module level entities. NOTE: This is updated in here for import usage
404
+ * @param {Array<NodePath<t.ClassProperty>>} templateStrings The templates to validate
405
+ * @returns Information about valid templates to be added to the resolvable Module.
406
+ */
407
+ function processTemplateStrings(properties, moduleContext, moduleLevelConsumption, templateStrings) {
408
+ return templateStrings
409
+ .filter((template) => (0, static_analyzer_1.validateTemplateString)(template, moduleContext, false))
410
+ .map((template, index) => {
411
+ const { identifiers } = (0, common_shared_1.implicitConsumptionMetadata)(template, moduleContext.astContext.classProperties, // info on all class properties
412
+ moduleContext.astContext.importDeclarations, // import metadata info
413
+ moduleLevelConsumption);
414
+ return {
415
+ template,
416
+ generatedName: `t${index}`,
417
+ memberUsage: identifiers,
418
+ };
419
+ })
420
+ .map((template) => {
421
+ (0, common_shared_1.updatePropertyUsage)((0, common_shared_1.getFromIdentifierOrStringLiteral)(template.template.node.key), template.memberUsage, properties, common_shared_1.PropertyTypes.TEMPLATE_STRING);
422
+ return template;
423
+ });
424
+ }
425
+ exports.processTemplateStrings = processTemplateStrings;
426
+ /**
427
+ * Converts templates into single line functions, hoisted to the top level of the resolvable module.
428
+ * Part of this hoisting is going through and updating references to properties or imports. similar to what we do for getters.
429
+ *
430
+ * @param genCombinedModuleAST the AST of the generated combined module
431
+ * @param importReferencesMap Map of importReferences (ex: "0/names/0") to ImportInfo, which comes from GeneratorState's scriptGenState.importRefsMap
432
+ * @param definedImports All the imports decalred in the ast
433
+ * @param validGetterContexts Array of valid templates
434
+ */
435
+ function hoistTemplateStrings(genCombinedModuleAST, importReferencesMap, definedImports, templateStrings) {
436
+ const trueToGeneratedImport = mapRealNameToGenerated(importReferencesMap);
437
+ let body = [];
438
+ const hoistedTemplateStrings = [];
439
+ for (const templateString of templateStrings) {
440
+ sanitizeFunction(templateString.template, definedImports, trueToGeneratedImport);
441
+ const program = genCombinedModuleAST.program;
442
+ body = program.body;
443
+ const propsId = t.identifier(exports.PROPS);
444
+ const hoistedGetter = t.functionDeclaration(t.identifier(templateString.generatedName), [propsId], t.blockStatement([t.returnStatement(templateString.template.node.value)]));
445
+ hoistedTemplateStrings.push(hoistedGetter);
446
+ }
447
+ const insertBeforeIndex = body.findIndex((statement) => statement.type !== 'ImportDeclaration');
448
+ body.splice(insertBeforeIndex, 0, ...hoistedTemplateStrings);
449
+ }
450
+ exports.hoistTemplateStrings = hoistTemplateStrings;
451
+ /**
452
+ * Create a mapping from the original name of an import to the generated one made by komaci
453
+ * @param importReferencesMap The inverse mapping of generated name to info
454
+ * @returns A map of original import name to generated name
455
+ */
456
+ function mapRealNameToGenerated(importReferencesMap) {
457
+ const trueToGeneratedImport = new Map();
458
+ for (const ref of Object.values(importReferencesMap)) {
459
+ if (ref.importSpecifier.type === 'ImportDefaultSpecifier' ||
460
+ ref.importSpecifier.type === 'ImportNamespaceSpecifier') {
461
+ trueToGeneratedImport.set(ref.resourceName, ref.localName.name);
462
+ }
463
+ else {
464
+ trueToGeneratedImport.set((0, common_shared_1.getFromIdentifierOrStringLiteral)(ref.importSpecifier.imported), ref.localName.name);
465
+ }
466
+ }
467
+ return trueToGeneratedImport;
468
+ }
469
+ exports.mapRealNameToGenerated = mapRealNameToGenerated;
470
+ /**
471
+ * Take a function defined on a class and sanitize it's interactions in preparation to be hoisted into resolvable module/
472
+ *
473
+ * Two main things happen during sanitization:
474
+ * - references to imports are updated to their generated name (i.e. i2)
475
+ * - references to `this` are replaced with references to `props`
476
+ *
477
+ * @param nodePath The node to sanitize
478
+ * @param definedImports Metadata about all the imports we know about
479
+ * @param trueToGeneratedImport Mapping of real import name to generated name
480
+ */
481
+ function sanitizeFunction(nodePath, definedImports, trueToGeneratedImport) {
482
+ const Visitors = {
483
+ Identifier(path) {
484
+ if ((path.parent.type === 'MemberExpression' &&
485
+ path.parent.property === path.node) ||
486
+ path.parent.type === 'Decorator') {
487
+ //when a property shares a same name with an import,
488
+ //it will be identified as an import
489
+ //this check skips the scenario
490
+ return;
491
+ }
492
+ const info = definedImports.get(path.node.name);
493
+ let localName;
494
+ if (info && (info.isDefault || info.isNamespaceSpecifier)) {
495
+ localName = trueToGeneratedImport.get(info.namespace);
496
+ }
497
+ else if (info && info.trueName) {
498
+ localName = trueToGeneratedImport.get(info.trueName);
499
+ }
500
+ else if (info) {
501
+ localName = trueToGeneratedImport.get(info.identifierName);
502
+ }
503
+ if (localName && localName !== exports.UNRESOLVED) {
504
+ path.replaceWith(t.identifier(localName)); // replace usage of import specifier in getter
505
+ }
506
+ else if (localName === exports.UNRESOLVED) {
507
+ // legit this should never happen but if we somehow missed an edge case somewhere this will prevent a malformed module from going out
508
+ throw new Error(`${exports.ERROR_PREFIX}: '${path.node.name}' does not map to valid import`);
509
+ }
510
+ },
511
+ MemberExpression(path) {
512
+ if (path.node.object.type === 'ThisExpression') {
513
+ path.replaceWith(t.memberExpression(t.identifier(exports.PROPS), path.node.property)); // replace this.<var> with props.<var>
514
+ }
515
+ },
516
+ };
517
+ nodePath.traverse(Visitors);
518
+ }
519
+ exports.sanitizeFunction = sanitizeFunction;
520
+ /**
521
+ * Function to update the Komaci Document with validated template information. This function will update the functions array in the
522
+ * export default adg along with the property references in the property array.
523
+ * @param komaciScriptDoc the komaci document
524
+ * @param ValidTemplateContext details about the templates we've deemed to be valid
525
+ */
526
+ function updateKomaciDocumentWithValidTemplatedStrings(komaciScriptDoc, templateStrings) {
527
+ if (komaciScriptDoc.exports?.default?.type === 'AdgReference') {
528
+ const adg = komaciScriptDoc.adgs?.[komaciScriptDoc.exports.default.value];
529
+ if (adg) {
530
+ templateStrings.forEach((template) => {
531
+ const propertyName = template.template.node.key.name;
532
+ const inputArr = {
533
+ type: 'ArrayValue',
534
+ value: [],
535
+ };
536
+ template.memberUsage.forEach((member) => {
537
+ const primVal = {
538
+ type: 'PrimitiveValue',
539
+ value: member,
540
+ };
541
+ inputArr.value.push(primVal);
542
+ });
543
+ const validTemplateStringFunction = {
544
+ type: exports.TEMPLATED_STRING_FUNCTION,
545
+ reference: {
546
+ type: 'InternalReference',
547
+ value: template.generatedName,
548
+ },
549
+ input: [inputArr],
550
+ location: undefined,
551
+ };
552
+ //if we have an adg make changes to it.
553
+ if (adg) {
554
+ template.f_index = addPropertyFunction(adg, propertyName, validTemplateStringFunction);
555
+ }
556
+ });
557
+ }
558
+ }
559
+ }
560
+ exports.updateKomaciDocumentWithValidTemplatedStrings = updateKomaciDocumentWithValidTemplatedStrings;
561
+ /**
562
+ * Update the functions array with the newly formed function reference and point the property to it
563
+ * @param adg The adg to update
564
+ * @param propertyName name of the property to update
565
+ */
566
+ function addPropertyFunction(adg, propertyName, func) {
567
+ if (!adg.functions) {
568
+ adg.functions = [];
569
+ }
570
+ if (!adg.properties) {
571
+ adg.properties = {};
572
+ }
573
+ //push getter onto array get the length.
574
+ const fIndex = adg.functions.push(func);
575
+ const refIndex = fIndex - 1;
576
+ //create new property to reference function array.
577
+ const property = {
578
+ isPublic: adg.properties[propertyName]?.isPublic || false,
579
+ input: {
580
+ type: 'FunctionReference',
581
+ value: refIndex,
582
+ },
583
+ };
584
+ adg.properties[propertyName] = property;
585
+ return refIndex;
586
+ }
587
+ exports.addPropertyFunction = addPropertyFunction;
588
+ //# sourceMappingURL=shared.js.map