@builder.io/mitosis 0.8.0 → 0.9.0

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 (69) hide show
  1. package/dist/src/generators/angular/{blocks.d.ts → classic/blocks.d.ts} +3 -3
  2. package/dist/src/generators/angular/{blocks.js → classic/blocks.js} +14 -14
  3. package/dist/src/generators/angular/classic/component.d.ts +3 -0
  4. package/dist/src/generators/angular/classic/component.js +356 -0
  5. package/dist/src/generators/angular/classic/plugins/get-class-properties-plugin.d.ts +2 -0
  6. package/dist/src/generators/angular/classic/plugins/get-class-properties-plugin.js +138 -0
  7. package/dist/src/generators/angular/classic/plugins/get-code-processor-plugins.d.ts +8 -0
  8. package/dist/src/generators/angular/classic/plugins/get-code-processor-plugins.js +60 -0
  9. package/dist/src/generators/angular/component.d.ts +3 -0
  10. package/dist/src/generators/angular/component.js +27 -0
  11. package/dist/src/generators/angular/helpers/format.d.ts +1 -0
  12. package/dist/src/generators/angular/helpers/format.js +24 -0
  13. package/dist/src/generators/angular/helpers/get-inputs.d.ts +7 -0
  14. package/dist/src/generators/angular/helpers/get-inputs.js +18 -0
  15. package/dist/src/generators/angular/helpers/get-outputs.d.ts +7 -0
  16. package/dist/src/generators/angular/helpers/get-outputs.js +23 -0
  17. package/dist/src/generators/angular/helpers/get-refs.d.ts +8 -0
  18. package/dist/src/generators/angular/helpers/get-refs.js +40 -0
  19. package/dist/src/generators/angular/helpers/get-styles.d.ts +6 -0
  20. package/dist/src/generators/angular/helpers/get-styles.js +17 -0
  21. package/dist/src/generators/angular/helpers/index.d.ts +15 -0
  22. package/dist/src/generators/angular/helpers/index.js +126 -2
  23. package/dist/src/generators/angular/{parse-selector.d.ts → helpers/parse-selector.d.ts} +1 -1
  24. package/dist/src/generators/angular/{parse-selector.js → helpers/parse-selector.js} +3 -3
  25. package/dist/src/generators/angular/index.d.ts +1 -3
  26. package/dist/src/generators/angular/index.js +1 -692
  27. package/dist/src/generators/angular/signals/blocks.d.ts +10 -0
  28. package/dist/src/generators/angular/signals/blocks.js +242 -0
  29. package/dist/src/generators/angular/signals/component.d.ts +3 -0
  30. package/dist/src/generators/angular/signals/component.js +279 -0
  31. package/dist/src/generators/angular/signals/helpers/get-inputs.d.ts +7 -0
  32. package/dist/src/generators/angular/signals/helpers/get-inputs.js +15 -0
  33. package/dist/src/generators/angular/signals/helpers/index.d.ts +9 -0
  34. package/dist/src/generators/angular/signals/helpers/index.js +22 -0
  35. package/dist/src/generators/angular/signals/plugins/get-code-processor-plugins.d.ts +4 -0
  36. package/dist/src/generators/angular/signals/plugins/get-code-processor-plugins.js +194 -0
  37. package/dist/src/generators/angular/types.d.ts +23 -2
  38. package/dist/src/generators/angular/types.js +1 -0
  39. package/dist/src/generators/mitosis/generator.js +11 -27
  40. package/dist/src/generators/qwik/component-generator.js +1 -0
  41. package/dist/src/generators/solid/index.js +1 -0
  42. package/dist/src/generators/stencil/blocks.js +2 -1
  43. package/dist/src/generators/stencil/component.js +3 -2
  44. package/dist/src/generators/stencil/helpers/index.d.ts +0 -5
  45. package/dist/src/generators/stencil/helpers/index.js +2 -33
  46. package/dist/src/generators/stencil/plugins/get-code-processor-plugins.d.ts +1 -1
  47. package/dist/src/generators/stencil/plugins/get-code-processor-plugins.js +3 -2
  48. package/dist/src/generators/svelte/svelte.js +2 -0
  49. package/dist/src/generators/vue/vue.js +2 -0
  50. package/dist/src/helpers/babel-transform.js +1 -1
  51. package/dist/src/helpers/class-components.d.ts +13 -0
  52. package/dist/src/helpers/class-components.js +51 -0
  53. package/dist/src/helpers/get-state-object-string.d.ts +4 -0
  54. package/dist/src/helpers/get-state-object-string.js +22 -5
  55. package/dist/src/helpers/is-children.js +1 -1
  56. package/dist/src/helpers/map-refs.d.ts +7 -1
  57. package/dist/src/helpers/map-refs.js +21 -21
  58. package/dist/src/helpers/plugins/process-code/index.d.ts +1 -1
  59. package/dist/src/helpers/plugins/process-code/index.js +16 -2
  60. package/dist/src/helpers/plugins/process-code/types.d.ts +3 -2
  61. package/dist/src/helpers/render-imports.d.ts +5 -0
  62. package/dist/src/helpers/replace-identifiers.js +1 -4
  63. package/dist/src/helpers/traverse-nodes.d.ts +1 -1
  64. package/dist/src/parsers/jsx/function-parser.js +15 -0
  65. package/dist/src/parsers/svelte/html/text.d.ts +18 -0
  66. package/dist/src/types/mitosis-component.d.ts +2 -0
  67. package/dist/src/types/mitosis-node.d.ts +7 -2
  68. package/dist/src/types/mitosis-node.js +8 -3
  69. package/package.json +1 -1
@@ -10,700 +10,9 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi
10
10
  if (k2 === undefined) k2 = k;
11
11
  o[k2] = m[k];
12
12
  }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
13
  var __exportStar = (this && this.__exportStar) || function(m, exports) {
26
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
27
15
  };
28
- var __importDefault = (this && this.__importDefault) || function (mod) {
29
- return (mod && mod.__esModule) ? mod : { "default": mod };
30
- };
31
16
  Object.defineProperty(exports, "__esModule", { value: true });
32
- exports.componentToAngular = void 0;
33
- const html_tags_1 = require("../../constants/html_tags");
34
- const bindings_1 = require("../../helpers/bindings");
35
- const dedent_1 = require("../../helpers/dedent");
36
- const fast_clone_1 = require("../../helpers/fast-clone");
37
- const get_child_components_1 = require("../../helpers/get-child-components");
38
- const get_components_used_1 = require("../../helpers/get-components-used");
39
- const get_custom_imports_1 = require("../../helpers/get-custom-imports");
40
- const get_prop_functions_1 = require("../../helpers/get-prop-functions");
41
- const get_props_1 = require("../../helpers/get-props");
42
- const get_props_ref_1 = require("../../helpers/get-props-ref");
43
- const get_refs_1 = require("../../helpers/get-refs");
44
- const get_state_object_string_1 = require("../../helpers/get-state-object-string");
45
- const get_typed_function_1 = require("../../helpers/get-typed-function");
46
- const indent_1 = require("../../helpers/indent");
47
- const is_mitosis_node_1 = require("../../helpers/is-mitosis-node");
48
- const is_upper_case_1 = require("../../helpers/is-upper-case");
49
- const map_refs_1 = require("../../helpers/map-refs");
50
- const merge_options_1 = require("../../helpers/merge-options");
51
- const process_code_1 = require("../../helpers/plugins/process-code");
52
- const render_imports_1 = require("../../helpers/render-imports");
53
- const replace_identifiers_1 = require("../../helpers/replace-identifiers");
54
- const slots_1 = require("../../helpers/slots");
55
- const strip_meta_properties_1 = require("../../helpers/strip-meta-properties");
56
- const strip_state_and_props_refs_1 = require("../../helpers/strip-state-and-props-refs");
57
- const collect_css_1 = require("../../helpers/styles/collect-css");
58
- const helpers_1 = require("../../helpers/styles/helpers");
59
- const traverse_nodes_1 = require("../../helpers/traverse-nodes");
60
- const plugins_1 = require("../../modules/plugins");
61
- const babel = __importStar(require("@babel/core"));
62
- const function_1 = require("fp-ts/lib/function");
63
- const lodash_1 = require("lodash");
64
- const legacy_1 = __importDefault(require("neotraverse/legacy"));
65
- const standalone_1 = require("prettier/standalone");
66
- const is_children_1 = __importDefault(require("../../helpers/is-children"));
67
- const on_mount_1 = require("../helpers/on-mount");
68
- const helpers_2 = require("./helpers");
69
- const types_1 = require("./types");
70
- const dash_case_1 = require("../../helpers/dash-case");
71
- const event_handlers_1 = require("../../helpers/event-handlers");
72
- const hooks_1 = require("../../generators/angular/helpers/hooks");
73
- const attribute_passing_1 = require("../../helpers/web-components/attribute-passing");
74
- const blocks_1 = require("./blocks");
75
- const { types } = babel;
76
- const preprocessCssAsJson = (json) => {
77
- (0, legacy_1.default)(json).forEach((item) => {
78
- var _a, _b;
79
- if ((0, is_mitosis_node_1.isMitosisNode)(item)) {
80
- if ((0, helpers_1.nodeHasCss)(item)) {
81
- if ((_b = (_a = item.bindings.css) === null || _a === void 0 ? void 0 : _a.code) === null || _b === void 0 ? void 0 : _b.includes('"')) {
82
- item.bindings.css.code = item.bindings.css.code.replace(/"/g, '"');
83
- }
84
- }
85
- }
86
- });
87
- };
88
- const generateNgModule = (content, name, componentsUsed, component, bootstrapMapper) => {
89
- return `import { NgModule } from "@angular/core";
90
- import { CommonModule } from "@angular/common";
91
-
92
- ${content}
93
-
94
- @NgModule({
95
- declarations: [${name}],
96
- imports: [CommonModule${componentsUsed.length ? ', ' + componentsUsed.map((comp) => `${comp}Module`).join(', ') : ''}],
97
- exports: [${name}],
98
- ${bootstrapMapper ? bootstrapMapper(name, componentsUsed, component) : ''}
99
- })
100
- export class ${name}Module {}`;
101
- };
102
- const traverseToGetAllDynamicComponents = (json, options, blockOptions) => {
103
- const components = new Set();
104
- let dynamicTemplate = '';
105
- (0, legacy_1.default)(json).forEach((item) => {
106
- if ((0, is_mitosis_node_1.isMitosisNode)(item) && item.name.includes('.') && item.name.split('.').length === 2) {
107
- const children = item.children
108
- .map((child) => (0, blocks_1.blockToAngular)({ root: json, json: child, options, blockOptions }))
109
- .join('\n');
110
- dynamicTemplate = `<ng-template #${item.name.split('.')[1].toLowerCase() + 'Template'}>${children}</ng-template>`;
111
- components.add(item.name);
112
- }
113
- });
114
- return {
115
- components,
116
- dynamicTemplate,
117
- };
118
- };
119
- const traverseAndCheckIfInnerHTMLIsUsed = (json) => {
120
- let innerHTMLIsUsed = false;
121
- (0, legacy_1.default)(json).forEach((item) => {
122
- if ((0, is_mitosis_node_1.isMitosisNode)(item)) {
123
- Object.keys(item.bindings).forEach((key) => {
124
- if (key === 'innerHTML') {
125
- innerHTMLIsUsed = true;
126
- return;
127
- }
128
- });
129
- }
130
- });
131
- return innerHTMLIsUsed;
132
- };
133
- /**
134
- * Prefixes state identifiers with this.
135
- * e.g. state.foo --> this.foo
136
- */
137
- const prefixState = (code) => {
138
- return (0, replace_identifiers_1.replaceNodes)({
139
- code,
140
- nodeMaps: [
141
- {
142
- from: types.identifier('state'),
143
- to: types.thisExpression(),
144
- },
145
- ],
146
- }).trim();
147
- };
148
- const processAngularCode = ({ contextVars, outputVars, domRefs, replaceWith, }) => (code) => (0, function_1.pipe)((0, strip_state_and_props_refs_1.DO_NOT_USE_VARS_TRANSFORMS)(code, {
149
- contextVars,
150
- domRefs,
151
- outputVars,
152
- }),
153
- /**
154
- * Only prefix state that is in the Angular class component.
155
- * Do not prefix state referenced in the template
156
- */
157
- replaceWith === 'this' ? prefixState : (x) => x, (newCode) => (0, strip_state_and_props_refs_1.stripStateAndPropsRefs)(newCode, { replaceWith }));
158
- const isASimpleProperty = (code) => {
159
- const expressions = ['==', '===', '!=', '!==', '<', '>', '<=', '>='];
160
- const invalidChars = ['{', '}', '(', ')', 'typeof'];
161
- return !invalidChars.some((char) => code.includes(char)) && !expressions.includes(code);
162
- };
163
- const generateNewBindingName = (index, name) => `node_${index}_${name.replaceAll('.', '_').replaceAll('-', '_')}`;
164
- const handleBindings = (json, item, index, forName, indexName) => {
165
- var _a, _b, _c, _d, _e, _f;
166
- for (const key in item.bindings) {
167
- if (key.startsWith('"') ||
168
- key.startsWith('$') ||
169
- key === 'css' ||
170
- key === 'ref' ||
171
- isASimpleProperty(item.bindings[key].code)) {
172
- continue;
173
- }
174
- const newBindingName = generateNewBindingName(index, item.name);
175
- if (forName) {
176
- if (item.name === 'For')
177
- continue;
178
- if (key === 'key')
179
- continue;
180
- if ((0, event_handlers_1.checkIsEvent)(key)) {
181
- const { arguments: cusArgs = ['event'] } = item.bindings[key];
182
- const eventBindingName = `${generateNewBindingName(index, item.name)}_event`;
183
- if (((_a = item.bindings[key]) === null || _a === void 0 ? void 0 : _a.code.trim().startsWith('{')) &&
184
- ((_b = item.bindings[key]) === null || _b === void 0 ? void 0 : _b.code.trim().endsWith('}'))) {
185
- const forAndIndex = `${forName ? `, ${forName}` : ''}${indexName ? `, ${indexName}` : ''}`;
186
- const eventArgs = `${cusArgs.join(', ')}${forAndIndex}`;
187
- json.state[eventBindingName] = {
188
- code: `(${eventArgs}) => ${item.bindings[key].code}`,
189
- type: 'function',
190
- };
191
- item.bindings[key].code = `state.${eventBindingName}(${eventArgs})`;
192
- json.state[newBindingName] = {
193
- code: `(${eventArgs}) => (${item.bindings[key].code})`,
194
- type: 'function',
195
- };
196
- item.bindings[key].code = `state.${newBindingName}($${eventArgs})`;
197
- }
198
- }
199
- else {
200
- json.state[newBindingName] = {
201
- code: `(${forName}${indexName ? `, ${indexName}` : ''}) => (${item.bindings[key].code})`,
202
- type: 'function',
203
- };
204
- item.bindings[key].code = `state.${newBindingName}(${forName}${indexName ? `, ${indexName}` : ''})`;
205
- }
206
- }
207
- else if ((_c = item.bindings[key]) === null || _c === void 0 ? void 0 : _c.code) {
208
- if (((_d = item.bindings[key]) === null || _d === void 0 ? void 0 : _d.type) !== 'spread' && !(0, event_handlers_1.checkIsEvent)(key)) {
209
- json.state[newBindingName] = { code: 'null', type: 'property' };
210
- (0, hooks_1.makeReactiveState)(json, newBindingName, `this.${newBindingName} = ${item.bindings[key].code}`);
211
- item.bindings[key].code = `state.${newBindingName}`;
212
- }
213
- else if ((0, event_handlers_1.checkIsEvent)(key)) {
214
- const { arguments: cusArgs = ['event'] } = item.bindings[key];
215
- if (((_e = item.bindings[key]) === null || _e === void 0 ? void 0 : _e.code.trim().startsWith('{')) &&
216
- ((_f = item.bindings[key]) === null || _f === void 0 ? void 0 : _f.code.trim().endsWith('}'))) {
217
- json.state[newBindingName] = {
218
- code: `(${cusArgs.join(', ')}) => ${item.bindings[key].code}`,
219
- type: 'function',
220
- };
221
- item.bindings[key].code = `state.${newBindingName}(${cusArgs.join(', ')})`;
222
- }
223
- }
224
- else {
225
- (0, hooks_1.makeReactiveState)(json, newBindingName, `state.${newBindingName} = {...(${item.bindings[key].code})}`);
226
- item.bindings[newBindingName] = item.bindings[key];
227
- item.bindings[key].code = `state.${newBindingName}`;
228
- delete item.bindings[key];
229
- }
230
- }
231
- index++;
232
- }
233
- return index;
234
- };
235
- const handleProperties = (json, item, index) => {
236
- for (const key in item.properties) {
237
- if (key.startsWith('$') || isASimpleProperty(item.properties[key])) {
238
- continue;
239
- }
240
- const newBindingName = generateNewBindingName(index, item.name);
241
- json.state[newBindingName] = { code: '`' + `${item.properties[key]}` + '`', type: 'property' };
242
- item.bindings[key] = (0, bindings_1.createSingleBinding)({ code: `state.${newBindingName}` });
243
- delete item.properties[key];
244
- index++;
245
- }
246
- return index;
247
- };
248
- const handleAngularBindings = (json, item, index, { forName, indexName } = {}) => {
249
- if ((0, is_children_1.default)({ node: item }))
250
- return index;
251
- index = handleBindings(json, item, index, forName, indexName);
252
- index = handleProperties(json, item, index);
253
- return index;
254
- };
255
- const classPropertiesPlugin = () => ({
256
- json: {
257
- pre: (json) => {
258
- let lastId = 0;
259
- (0, traverse_nodes_1.traverseNodes)(json, (item) => {
260
- if ((0, is_mitosis_node_1.isMitosisNode)(item)) {
261
- if (item.name === 'For') {
262
- const forName = item.scope.forName;
263
- const indexName = item.scope.indexName;
264
- (0, traverse_nodes_1.traverseNodes)(item, (child) => {
265
- if ((0, is_mitosis_node_1.isMitosisNode)(child)) {
266
- child._traversed = true;
267
- lastId = handleAngularBindings(json, child, lastId, {
268
- forName,
269
- indexName,
270
- });
271
- }
272
- });
273
- }
274
- else if (!item._traversed) {
275
- lastId = handleAngularBindings(json, item, lastId);
276
- }
277
- }
278
- });
279
- return json;
280
- },
281
- },
282
- });
283
- const componentToAngular = (userOptions = {}) => ({ component: _component }) => {
284
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
285
- // Make a copy we can safely mutate, similar to babel's toolchain
286
- let json = (0, fast_clone_1.fastClone)(_component);
287
- const useMetadata = (_a = json.meta) === null || _a === void 0 ? void 0 : _a.useMetadata;
288
- const contextVars = Object.keys(((_b = json === null || json === void 0 ? void 0 : json.context) === null || _b === void 0 ? void 0 : _b.get) || {});
289
- // TODO: Why is 'outputs' used here and shouldn't it be typed in packages/core/src/types/metadata.ts
290
- const metaOutputVars = (useMetadata === null || useMetadata === void 0 ? void 0 : useMetadata.outputs) || [];
291
- const outputVars = (0, lodash_1.uniq)([...metaOutputVars, ...(0, get_prop_functions_1.getPropFunctions)(json)]);
292
- const options = (0, merge_options_1.initializeOptions)({
293
- target: 'angular',
294
- component: _component,
295
- defaults: types_1.DEFAULT_ANGULAR_OPTIONS,
296
- userOptions: userOptions,
297
- });
298
- options.plugins = [
299
- ...(options.plugins || []),
300
- (0, process_code_1.CODE_PROCESSOR_PLUGIN)((codeType, _, node) => {
301
- switch (codeType) {
302
- case 'hooks':
303
- return (0, function_1.flow)(processAngularCode({
304
- replaceWith: 'this',
305
- contextVars,
306
- outputVars,
307
- domRefs: Array.from((0, get_refs_1.getRefs)(json)),
308
- }), (code) => {
309
- const allMethodNames = Object.entries(json.state)
310
- .filter(([_, value]) => (value === null || value === void 0 ? void 0 : value.type) === 'function' || (value === null || value === void 0 ? void 0 : value.type) === 'method')
311
- .map(([key]) => key);
312
- return (0, replace_identifiers_1.replaceIdentifiers)({
313
- code,
314
- from: allMethodNames,
315
- to: (name) => `this.${name}`,
316
- });
317
- });
318
- case 'bindings':
319
- return (code, key) => {
320
- var _a;
321
- // we create a separate state property for spread binding and use ref to attach the attributes
322
- // so we need to use `this.` inside the class to access state and props
323
- const isSpreadAttributeBinding = ((_a = node === null || node === void 0 ? void 0 : node.bindings[key]) === null || _a === void 0 ? void 0 : _a.type) === 'spread' &&
324
- html_tags_1.VALID_HTML_TAGS.includes(node.name.trim());
325
- // If we have a For loop with "key" it will be transformed to
326
- // trackOfXXX, we need to use "this" for state properties
327
- const isKey = key === 'key';
328
- const newLocal = processAngularCode({
329
- contextVars: [],
330
- outputVars,
331
- domRefs: [], // the template doesn't need the this keyword.
332
- replaceWith: isKey || isSpreadAttributeBinding ? 'this' : undefined,
333
- })(code);
334
- return newLocal.replace(/"/g, '&quot;');
335
- };
336
- case 'hooks-deps':
337
- case 'state':
338
- case 'context-set':
339
- case 'properties':
340
- case 'dynamic-jsx-elements':
341
- case 'types':
342
- return (x) => x;
343
- }
344
- }),
345
- ];
346
- if (options.state === 'class-properties') {
347
- options.plugins.push(classPropertiesPlugin);
348
- }
349
- if (options.plugins) {
350
- json = (0, plugins_1.runPreJsonPlugins)({ json, plugins: options.plugins });
351
- }
352
- const [forwardProp, hasPropRef] = (0, get_props_ref_1.getPropsRef)(json, true);
353
- const propsTypeRef = json.propsTypeRef !== 'any' ? json.propsTypeRef : undefined;
354
- const childComponents = (0, get_child_components_1.getChildComponents)(json);
355
- const customImports = (0, get_custom_imports_1.getCustomImports)(json);
356
- const { exports: localExports = {} } = json;
357
- const localExportVars = Object.keys(localExports)
358
- .filter((key) => localExports[key].usedInLocal)
359
- .map((key) => `${key} = ${key};`);
360
- const injectables = contextVars.map((variableName) => {
361
- var _a, _b, _c, _d;
362
- const variableType = (_a = json === null || json === void 0 ? void 0 : json.context) === null || _a === void 0 ? void 0 : _a.get[variableName].name;
363
- if ((_b = options === null || options === void 0 ? void 0 : options.experimental) === null || _b === void 0 ? void 0 : _b.injectables) {
364
- return (_c = options === null || options === void 0 ? void 0 : options.experimental) === null || _c === void 0 ? void 0 : _c.injectables(variableName, variableType);
365
- }
366
- if ((_d = options === null || options === void 0 ? void 0 : options.experimental) === null || _d === void 0 ? void 0 : _d.inject) {
367
- return `@Inject(forwardRef(() => ${variableType})) public ${variableName}: ${variableType}`;
368
- }
369
- return `public ${variableName} : ${variableType}`;
370
- });
371
- const props = (0, get_props_1.getProps)(json);
372
- // prevent jsx props from showing up as @Input
373
- if (hasPropRef) {
374
- props.delete(forwardProp);
375
- }
376
- props.delete('children');
377
- // remove props for outputs
378
- outputVars.forEach((variableName) => {
379
- props.delete(variableName);
380
- });
381
- const outputs = outputVars.map((variableName) => {
382
- var _a, _b;
383
- if ((_a = options === null || options === void 0 ? void 0 : options.experimental) === null || _a === void 0 ? void 0 : _a.outputs) {
384
- return (_b = options === null || options === void 0 ? void 0 : options.experimental) === null || _b === void 0 ? void 0 : _b.outputs(json, variableName);
385
- }
386
- return `@Output() ${variableName} = new EventEmitter()`;
387
- });
388
- const domRefs = (0, get_refs_1.getRefs)(json);
389
- const jsRefs = Object.keys(json.refs).filter((ref) => !domRefs.has(ref));
390
- const withAttributePassing = (0, attribute_passing_1.shouldAddAttributePassing)(json, options);
391
- const rootRef = (0, attribute_passing_1.getAddAttributePassingRef)(json, options);
392
- if (withAttributePassing) {
393
- if (!domRefs.has(rootRef)) {
394
- domRefs.add(rootRef);
395
- }
396
- (0, hooks_1.addCodeNgAfterViewInit)(json, `
397
- const element: HTMLElement | null = this.${rootRef}?.nativeElement;
398
- this.enableAttributePassing(element, "${(0, dash_case_1.dashCase)(json.name)}");
399
- `);
400
- }
401
- const componentsUsed = Array.from((0, get_components_used_1.getComponentsUsed)(json)).filter((item) => {
402
- return item.length && (0, is_upper_case_1.isUpperCase)(item[0]) && !types_1.BUILT_IN_COMPONENTS.has(item);
403
- });
404
- (0, map_refs_1.mapRefs)(json, (refName) => {
405
- const isDomRef = domRefs.has(refName);
406
- return `this.${isDomRef ? '' : '_'}${refName}${isDomRef ? '.nativeElement' : ''}`;
407
- });
408
- if (options.plugins) {
409
- json = (0, plugins_1.runPostJsonPlugins)({ json, plugins: options.plugins });
410
- }
411
- preprocessCssAsJson(json);
412
- let css = (0, collect_css_1.collectCss)(json);
413
- if (options.prettier !== false) {
414
- css = tryFormat(css, 'css');
415
- }
416
- const helperFunctions = new Set();
417
- const shouldUseSanitizer = !((_c = useMetadata === null || useMetadata === void 0 ? void 0 : useMetadata.angular) === null || _c === void 0 ? void 0 : _c.sanitizeInnerHTML) && traverseAndCheckIfInnerHTMLIsUsed(json);
418
- const changeDetectionStrategy = (_d = useMetadata === null || useMetadata === void 0 ? void 0 : useMetadata.angular) === null || _d === void 0 ? void 0 : _d.changeDetection;
419
- let template = json.children
420
- .map((item) => {
421
- var _a, _b, _c, _d;
422
- const tmpl = (0, blocks_1.blockToAngular)({
423
- root: json,
424
- json: item,
425
- options,
426
- rootRef: withAttributePassing && rootRef === attribute_passing_1.ROOT_REF ? rootRef : undefined, // only pass rootRef if it's not the default
427
- blockOptions: {
428
- childComponents,
429
- nativeAttributes: (_b = (_a = useMetadata === null || useMetadata === void 0 ? void 0 : useMetadata.angular) === null || _a === void 0 ? void 0 : _a.nativeAttributes) !== null && _b !== void 0 ? _b : [],
430
- nativeEvents: (_d = (_c = useMetadata === null || useMetadata === void 0 ? void 0 : useMetadata.angular) === null || _c === void 0 ? void 0 : _c.nativeEvents) !== null && _d !== void 0 ? _d : [],
431
- sanitizeInnerHTML: !shouldUseSanitizer,
432
- },
433
- });
434
- if (options.state === 'inline-with-wrappers') {
435
- (0, helpers_2.getAppropriateTemplateFunctionKeys)(tmpl).forEach((key) => helperFunctions.add((0, helpers_2.HELPER_FUNCTIONS)(options.typescript)[key]));
436
- }
437
- return tmpl;
438
- })
439
- .join('\n');
440
- if (options.prettier !== false) {
441
- template = tryFormat(template, 'html');
442
- }
443
- (0, strip_meta_properties_1.stripMetaProperties)(json);
444
- const { components: dynamicComponents, dynamicTemplate } = traverseToGetAllDynamicComponents(json, options, {
445
- childComponents,
446
- nativeAttributes: (_f = (_e = useMetadata === null || useMetadata === void 0 ? void 0 : useMetadata.angular) === null || _e === void 0 ? void 0 : _e.nativeAttributes) !== null && _f !== void 0 ? _f : [],
447
- nativeEvents: (_h = (_g = useMetadata === null || useMetadata === void 0 ? void 0 : useMetadata.angular) === null || _g === void 0 ? void 0 : _g.nativeEvents) !== null && _h !== void 0 ? _h : [],
448
- });
449
- (0, helpers_2.transformState)(json);
450
- const dataString = (0, get_state_object_string_1.getStateObjectStringFromComponent)(json, {
451
- format: 'class',
452
- withType: options.typescript,
453
- valueMapper: (code, type, typeParameter) => {
454
- let value = code;
455
- if (type !== 'data') {
456
- value = (0, get_typed_function_1.getTypedFunction)(code, options.typescript, typeParameter);
457
- }
458
- return processAngularCode({
459
- replaceWith: 'this',
460
- contextVars,
461
- outputVars,
462
- domRefs: Array.from(domRefs),
463
- })(value);
464
- },
465
- });
466
- const refsForObjSpread = (0, get_refs_1.getRefs)(json, 'spreadRef');
467
- const hostDisplayCss = options.visuallyIgnoreHostElement ? ':host { display: contents; }' : '';
468
- const styles = css.length ? [hostDisplayCss, css].join('\n') : hostDisplayCss;
469
- // Preparing built in component metadata parameters
470
- const componentMetadata = {
471
- selector: ((_j = useMetadata === null || useMetadata === void 0 ? void 0 : useMetadata.angular) === null || _j === void 0 ? void 0 : _j.selector)
472
- ? `'${(_k = useMetadata === null || useMetadata === void 0 ? void 0 : useMetadata.angular) === null || _k === void 0 ? void 0 : _k.selector}'`
473
- : `'${(0, lodash_1.kebabCase)(json.name || 'my-component')}'`,
474
- template: `\`
475
- ${(0, indent_1.indent)(dynamicTemplate, 8).replace(/`/g, '\\`').replace(/\$\{/g, '\\${')}
476
- ${(0, indent_1.indent)(template, 8).replace(/`/g, '\\`').replace(/\$\{/g, '\\${')}
477
- \``,
478
- ...(changeDetectionStrategy === 'OnPush'
479
- ? {
480
- changeDetection: 'ChangeDetectionStrategy.OnPush',
481
- }
482
- : {}),
483
- ...(styles
484
- ? {
485
- styles: `[\`${(0, indent_1.indent)(styles, 8)}\`]`,
486
- }
487
- : {}),
488
- ...(options.standalone
489
- ? // TODO: also add child component imports here as well
490
- {
491
- standalone: 'true',
492
- imports: `[${['CommonModule', ...componentsUsed].join(', ')}]`,
493
- }
494
- : {}),
495
- };
496
- // Taking into consideration what user has passed in options and allowing them to override the default generated metadata
497
- Object.entries(json.meta.angularConfig || {}).forEach(([key, value]) => {
498
- componentMetadata[key] = value;
499
- });
500
- const hasConstructor = Boolean(injectables.length) ||
501
- dynamicComponents.size ||
502
- refsForObjSpread.size ||
503
- shouldUseSanitizer;
504
- const angularCoreImports = [
505
- ...(outputs.length ? ['Output', 'EventEmitter'] : []),
506
- ...(((_l = options === null || options === void 0 ? void 0 : options.experimental) === null || _l === void 0 ? void 0 : _l.inject) ? ['Inject', 'forwardRef'] : []),
507
- 'Component',
508
- ...(domRefs.size || dynamicComponents.size || refsForObjSpread.size
509
- ? ['ViewChild', 'ElementRef']
510
- : []),
511
- ...(refsForObjSpread.size ? ['Renderer2'] : []),
512
- ...(props.size ? ['Input'] : []),
513
- ...(dynamicComponents.size ? ['ViewContainerRef', 'TemplateRef'] : []),
514
- ...(((_m = json.hooks.onUpdate) === null || _m === void 0 ? void 0 : _m.length) && options.typescript ? ['SimpleChanges'] : []),
515
- ...(changeDetectionStrategy === 'OnPush' ? ['ChangeDetectionStrategy'] : []),
516
- ].join(', ');
517
- const constructorInjectables = [
518
- ...injectables,
519
- ...(dynamicComponents.size
520
- ? [`private vcRef${options.typescript ? ': ViewContainerRef' : ''}`]
521
- : []),
522
- ...(refsForObjSpread.size
523
- ? [`private renderer${options.typescript ? ': Renderer2' : ''}`]
524
- : []),
525
- ...(shouldUseSanitizer
526
- ? [`protected sanitizer${options.typescript ? ': DomSanitizer' : ''}`]
527
- : []),
528
- ].join(',\n');
529
- let str = (0, dedent_1.dedent) `
530
- import { ${angularCoreImports} } from '@angular/core';
531
- ${shouldUseSanitizer ? `import { DomSanitizer } from '@angular/platform-browser';` : ''}
532
- ${options.standalone ? `import { CommonModule } from '@angular/common';` : ''}
533
-
534
- ${json.types ? json.types.join('\n') : ''}
535
- ${(0, helpers_2.getDefaultProps)(json)}
536
- ${(0, render_imports_1.renderPreComponent)({
537
- explicitImportFileExtension: options.explicitImportFileExtension,
538
- component: json,
539
- target: 'angular',
540
- excludeMitosisComponents: !options.standalone && !options.preserveImports,
541
- preserveFileExtensions: options.preserveFileExtensions,
542
- componentsUsed,
543
- importMapper: options === null || options === void 0 ? void 0 : options.importMapper,
544
- })}
545
-
546
- @Component({
547
- ${Object.entries(componentMetadata)
548
- .map(([k, v]) => `${k}: ${v}`)
549
- .join(',')}
550
- })
551
- export default class ${json.name} {
552
- ${localExportVars.join('\n')}
553
- ${customImports.map((name) => `${name} = ${name}`).join('\n')}
554
-
555
- ${Array.from(props)
556
- .filter((item) => !(0, slots_1.isSlotProperty)(item) && item !== 'children')
557
- .map((item) => {
558
- const hasDefaultProp = json.defaultProps && json.defaultProps.hasOwnProperty(item);
559
- const propType = propsTypeRef ? `${propsTypeRef}["${item}"]` : 'any';
560
- let propDeclaration = `@Input() ${item}${options.typescript ? `${hasDefaultProp ? '' : '!'}: ${propType}` : ''}`;
561
- if (hasDefaultProp) {
562
- propDeclaration += ` = defaultProps["${item}"]`;
563
- }
564
- return propDeclaration;
565
- })
566
- .join('\n')}
567
-
568
- ${outputs.join('\n')}
569
-
570
- ${Array.from(domRefs)
571
- .map((refName) => `@ViewChild('${refName}') ${refName}${options.typescript ? '!: ElementRef' : ''}`)
572
- .join('\n')}
573
-
574
- ${Array.from(refsForObjSpread)
575
- .map((refName) => `@ViewChild('${refName}') ${refName}${options.typescript ? '!: ElementRef' : ''}`)
576
- .join('\n')}
577
-
578
- ${Array.from(dynamicComponents)
579
- .map((component) => `@ViewChild('${component
580
- .split('.')[1]
581
- .toLowerCase()}Template', { static: true }) ${component
582
- .split('.')[1]
583
- .toLowerCase()}TemplateRef${options.typescript ? '!: TemplateRef<any>' : ''}`)
584
- .join('\n')}
585
-
586
- ${dynamicComponents.size ? `myContent${options.typescript ? '?: any[][];' : ''}` : ''}
587
- ${refsForObjSpread.size
588
- ? `_listenerFns = new Map${options.typescript ? '<string, () => void>' : ''}()`
589
- : ''}
590
-
591
- ${dataString}
592
-
593
- ${helperFunctions.size ? Array.from(helperFunctions).join('\n') : ''}
594
-
595
- ${jsRefs
596
- .map((ref) => {
597
- const argument = json.refs[ref].argument;
598
- const typeParameter = json.refs[ref].typeParameter;
599
- return `private _${ref}${typeParameter ? `: ${typeParameter}` : ''}${argument
600
- ? ` = ${processAngularCode({
601
- replaceWith: 'this.',
602
- contextVars,
603
- outputVars,
604
- domRefs: Array.from(domRefs),
605
- })(argument)}`
606
- : ''};`;
607
- })
608
- .join('\n')}
609
-
610
- ${!hasConstructor ? '' : `constructor(\n${constructorInjectables}) {}`}
611
-
612
- ${withAttributePassing ? (0, attribute_passing_1.getAttributePassingString)(options.typescript) : ''}
613
-
614
- ${!json.hooks.onMount.length && !dynamicComponents.size && !((_o = json.hooks.onInit) === null || _o === void 0 ? void 0 : _o.code)
615
- ? ''
616
- : `ngOnInit() {
617
- ${!((_p = json.hooks) === null || _p === void 0 ? void 0 : _p.onInit)
618
- ? ''
619
- : `
620
- ${(_q = json.hooks.onInit) === null || _q === void 0 ? void 0 : _q.code}
621
- `}
622
- ${json.hooks.onMount.length > 0
623
- ? `
624
- if (typeof window !== 'undefined') {
625
- ${(0, on_mount_1.stringifySingleScopeOnMount)(json)}
626
- }
627
- `
628
- : ''}
629
- ${dynamicComponents.size
630
- ? `
631
- this.myContent = [${Array.from(dynamicComponents)
632
- .map((component) => `this.vcRef.createEmbeddedView(this.${component
633
- .split('.')[1]
634
- .toLowerCase()}TemplateRef).rootNodes`)
635
- .join(', ')}];
636
- `
637
- : ''}
638
- }`}
639
-
640
- ${
641
- // hooks specific to Angular
642
- ((_s = (_r = json.compileContext) === null || _r === void 0 ? void 0 : _r.angular) === null || _s === void 0 ? void 0 : _s.hooks)
643
- ? Object.entries((_u = (_t = json.compileContext) === null || _t === void 0 ? void 0 : _t.angular) === null || _u === void 0 ? void 0 : _u.hooks)
644
- .map(([key, value]) => {
645
- return `${key}() {
646
- ${value.code}
647
- }`;
648
- })
649
- .join('\n')
650
- : ''}
651
-
652
- ${!((_v = json.hooks.onUpdate) === null || _v === void 0 ? void 0 : _v.length)
653
- ? ''
654
- : `ngOnChanges(changes${options.typescript ? ': SimpleChanges' : ''}) {
655
- if (typeof window !== 'undefined') {
656
- ${(_w = json.hooks.onUpdate) === null || _w === void 0 ? void 0 : _w.reduce((code, hook) => {
657
- code += hook.code;
658
- return code + '\n';
659
- }, '')}
660
- }
661
- }
662
- `}
663
-
664
- ${!json.hooks.onUnMount && !refsForObjSpread.size
665
- ? ''
666
- : `ngOnDestroy() {
667
- ${((_x = json.hooks.onUnMount) === null || _x === void 0 ? void 0 : _x.code) || ''}
668
- ${refsForObjSpread.size
669
- ? `for (const fn of this._listenerFns.values()) { fn(); }`
670
- : ''}
671
- }`}
672
-
673
- }
674
- `;
675
- if (options.standalone !== true) {
676
- str = generateNgModule(str, json.name, componentsUsed, json, options.bootstrapMapper);
677
- }
678
- if (options.plugins) {
679
- str = (0, plugins_1.runPreCodePlugins)({ json, code: str, plugins: options.plugins });
680
- }
681
- if (options.prettier !== false) {
682
- str = tryFormat(str, 'typescript');
683
- }
684
- if (options.plugins) {
685
- str = (0, plugins_1.runPostCodePlugins)({ json, code: str, plugins: options.plugins });
686
- }
687
- return str;
688
- };
689
- exports.componentToAngular = componentToAngular;
690
- const tryFormat = (str, parser) => {
691
- try {
692
- return (0, standalone_1.format)(str, {
693
- parser,
694
- plugins: [
695
- // To support running in browsers
696
- require('prettier/parser-typescript'),
697
- require('prettier/parser-postcss'),
698
- require('prettier/parser-html'),
699
- require('prettier/parser-babel'),
700
- ],
701
- htmlWhitespaceSensitivity: 'ignore',
702
- });
703
- }
704
- catch (err) {
705
- console.warn('Could not prettify', { string: str }, err);
706
- }
707
- return str;
708
- };
17
+ __exportStar(require("./component"), exports);
709
18
  __exportStar(require("./types"), exports);