@developer_tribe/react-builder 0.1.0 → 0.1.2

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 (107) hide show
  1. package/package.json +4 -2
  2. package/scripts/build-components.js +550 -0
  3. package/scripts/prebuild.js +11 -0
  4. package/src/AttributesEditor.tsx +107 -0
  5. package/src/RenderMainNode.tsx +37 -0
  6. package/src/RenderPage.tsx +61 -0
  7. package/src/assets/devices.json +730 -0
  8. package/src/assets/samples/carousel-sample.json +108 -0
  9. package/src/assets/samples/getSamples.ts +28 -0
  10. package/src/assets/samples/simple-1.json +46 -0
  11. package/src/assets/samples/simple-2.json +233 -0
  12. package/src/assets/samples/vpn-onboard-1.json +799 -0
  13. package/src/assets/samples/vpn-onboard-2.json +790 -0
  14. package/src/assets/samples/vpn-onboard-3.json +803 -0
  15. package/src/assets/samples/vpn-onboard-4.json +804 -0
  16. package/src/build-components/Button/Button.tsx +13 -0
  17. package/src/build-components/Button/ButtonProps.generated.ts +21 -0
  18. package/src/build-components/Button/ButtonProps.ts +3 -0
  19. package/src/build-components/Button/pattern.json +25 -0
  20. package/src/build-components/Carousel/Carousel.tsx +27 -0
  21. package/src/build-components/Carousel/CarouselProps.generated.ts +6 -0
  22. package/src/build-components/Carousel/CarouselProps.ts +3 -0
  23. package/src/build-components/Carousel/pattern.json +9 -0
  24. package/src/build-components/CarouselButtons/CarouselButtons.tsx +47 -0
  25. package/src/build-components/CarouselButtons/CarouselButtonsProps.generated.ts +9 -0
  26. package/src/build-components/CarouselButtons/CarouselButtonsProps.ts +3 -0
  27. package/src/build-components/CarouselButtons/pattern.json +12 -0
  28. package/src/build-components/CarouselDots/CarouselDots.tsx +40 -0
  29. package/src/build-components/CarouselDots/CarouselDotsProps.generated.ts +14 -0
  30. package/src/build-components/CarouselDots/CarouselDotsProps.ts +3 -0
  31. package/src/build-components/CarouselDots/pattern.json +18 -0
  32. package/src/build-components/CarouselItem/CarouselItem.tsx +18 -0
  33. package/src/build-components/CarouselItem/CarouselItemProps.generated.ts +6 -0
  34. package/src/build-components/CarouselItem/CarouselItemProps.ts +3 -0
  35. package/src/build-components/CarouselItem/pattern.json +9 -0
  36. package/src/build-components/CarouselProvider/CarouselProvider.tsx +26 -0
  37. package/src/build-components/CarouselProvider/CarouselProviderProps.generated.ts +6 -0
  38. package/src/build-components/CarouselProvider/CarouselProviderProps.ts +3 -0
  39. package/src/build-components/CarouselProvider/pattern.json +9 -0
  40. package/src/build-components/Image/Image.tsx +35 -0
  41. package/src/build-components/Image/ImageProps.generated.ts +12 -0
  42. package/src/build-components/Image/ImageProps.ts +3 -0
  43. package/src/build-components/Image/pattern.json +15 -0
  44. package/src/build-components/Onboard/Onboard.tsx +14 -0
  45. package/src/build-components/Onboard/OnboardProps.generated.ts +6 -0
  46. package/src/build-components/Onboard/OnboardProps.ts +3 -0
  47. package/src/build-components/Onboard/pattern.json +9 -0
  48. package/src/build-components/OnboardBoardTitle/OnboardBoardTitle.tsx +28 -0
  49. package/src/build-components/OnboardBoardTitle/OnboardBoardTitleProps.generated.ts +21 -0
  50. package/src/build-components/OnboardBoardTitle/OnboardBoardTitleProps.ts +4 -0
  51. package/src/build-components/OnboardBoardTitle/pattern.json +25 -0
  52. package/src/build-components/OnboardButton/OnboardButton.tsx +59 -0
  53. package/src/build-components/OnboardButton/OnboardButtonProps.generated.ts +13 -0
  54. package/src/build-components/OnboardButton/OnboardButtonProps.ts +3 -0
  55. package/src/build-components/OnboardButton/pattern.json +16 -0
  56. package/src/build-components/OnboardButtons/OnboardButtons.tsx +76 -0
  57. package/src/build-components/OnboardButtons/OnboardButtonsProps.generated.ts +12 -0
  58. package/src/build-components/OnboardButtons/OnboardButtonsProps.ts +3 -0
  59. package/src/build-components/OnboardButtons/pattern.json +15 -0
  60. package/src/build-components/OnboardExpandingDot/OnboardExpandingDot.tsx +14 -0
  61. package/src/build-components/OnboardExpandingDot/OnboardExpandingDotProps.generated.ts +14 -0
  62. package/src/build-components/OnboardExpandingDot/OnboardExpandingDotProps.ts +4 -0
  63. package/src/build-components/OnboardExpandingDot/pattern.json +18 -0
  64. package/src/build-components/OnboardFooter/OnboardFooter.tsx +13 -0
  65. package/src/build-components/OnboardFooter/OnboardFooterProps.generated.ts +24 -0
  66. package/src/build-components/OnboardFooter/OnboardFooterProps.ts +3 -0
  67. package/src/build-components/OnboardFooter/pattern.json +28 -0
  68. package/src/build-components/OnboardImage/OnboardImage.tsx +14 -0
  69. package/src/build-components/OnboardImage/OnboardImageProps.generated.ts +12 -0
  70. package/src/build-components/OnboardImage/OnboardImageProps.ts +3 -0
  71. package/src/build-components/OnboardImage/pattern.json +15 -0
  72. package/src/build-components/OnboardItem/OnboardItem.tsx +29 -0
  73. package/src/build-components/OnboardItem/OnboardItemProps.generated.ts +6 -0
  74. package/src/build-components/OnboardItem/OnboardItemProps.ts +3 -0
  75. package/src/build-components/OnboardItem/pattern.json +9 -0
  76. package/src/build-components/OnboardProvider/OnboardProvider.tsx +65 -0
  77. package/src/build-components/OnboardProvider/OnboardProviderProps.generated.ts +6 -0
  78. package/src/build-components/OnboardProvider/OnboardProviderProps.ts +3 -0
  79. package/src/build-components/OnboardProvider/pattern.json +9 -0
  80. package/src/build-components/OnboardSubtitle/OnboardSubtitle.tsx +28 -0
  81. package/src/build-components/OnboardSubtitle/OnboardSubtitleProps.generated.ts +21 -0
  82. package/src/build-components/OnboardSubtitle/OnboardSubtitleProps.ts +3 -0
  83. package/src/build-components/OnboardSubtitle/pattern.json +25 -0
  84. package/src/build-components/RenderNode.generated.tsx +97 -0
  85. package/src/build-components/Text/Text.tsx +23 -0
  86. package/src/build-components/Text/TextProps.generated.ts +21 -0
  87. package/src/build-components/Text/TextProps.ts +3 -0
  88. package/src/build-components/Text/pattern.json +26 -0
  89. package/src/build-components/View/View.tsx +62 -0
  90. package/src/build-components/View/ViewProps.generated.ts +24 -0
  91. package/src/build-components/View/ViewProps.ts +3 -0
  92. package/src/build-components/View/pattern.json +28 -0
  93. package/src/build-components/other.ts +6 -0
  94. package/src/index.ts +24 -0
  95. package/src/styles/index.scss +114 -0
  96. package/src/types/Device.ts +12 -0
  97. package/src/types/Node.ts +19 -0
  98. package/src/types/PreviewConfig.ts +19 -0
  99. package/src/types/Project.ts +11 -0
  100. package/src/types/TargetedScreenSize.ts +4 -0
  101. package/src/utils/analyseNode.ts +77 -0
  102. package/src/utils/generateRandomKeyForNode.ts +3 -0
  103. package/src/utils/getDevices.ts +6 -0
  104. package/src/utils/isCarousel.ts +36 -0
  105. package/src/utils/isOnboard.ts +54 -0
  106. package/src/utils/novaToJson.ts +254 -0
  107. package/src/utils/patterns.ts +63 -0
package/package.json CHANGED
@@ -1,13 +1,15 @@
1
1
  {
2
2
  "name": "@developer_tribe/react-builder",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs.js",
7
7
  "module": "dist/index.esm.js",
8
8
  "types": "dist/index.d.ts",
9
9
  "files": [
10
- "dist"
10
+ "dist",
11
+ "src",
12
+ "scripts"
11
13
  ],
12
14
  "scripts": {
13
15
  "prebuild": "node ./scripts/prebuild.js",
@@ -0,0 +1,550 @@
1
+ #!/usr/bin/env node
2
+ // Pre-build component generator for files under `src/build-components`
3
+ // Order of operations follows the user's checklist, implemented as sequential functions.
4
+ //TODO: memo needs optimization
5
+ import { promises as fs } from 'fs';
6
+ import path from 'path';
7
+ import url from 'url';
8
+ import prettier from 'prettier';
9
+ import { ESLint } from 'eslint';
10
+
11
+ const __filename = url.fileURLToPath(import.meta.url);
12
+ const __dirname = path.dirname(__filename);
13
+
14
+ const PROJECT_ROOT = path.resolve(__dirname, '..');
15
+ const SRC_ROOT = path.join(PROJECT_ROOT, 'src');
16
+ const COMPONENTS_ROOT = path.join(SRC_ROOT, 'build-components');
17
+ const PATTERNS_ROOT = path.join(SRC_ROOT, 'patterns');
18
+
19
+ /**
20
+ * Utility: read JSON with helpful error messages
21
+ */
22
+ async function readJson(filePath) {
23
+ try {
24
+ const content = await fs.readFile(filePath, 'utf8');
25
+ return JSON.parse(content);
26
+ } catch (error) {
27
+ const reason =
28
+ error instanceof SyntaxError
29
+ ? 'Invalid JSON'
30
+ : error.code || error.message;
31
+ return fail(`Failed to read JSON at ${filePath}: ${reason}`);
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Utility: ensure directory exists
37
+ */
38
+ async function ensureDir(dirPath) {
39
+ await fs.mkdir(dirPath, { recursive: true });
40
+ }
41
+
42
+ /**
43
+ * Helper: log the error for readability and then throw
44
+ */
45
+ function fail(message) {
46
+ console.error(message);
47
+ const err = new Error(message);
48
+ // eslint-disable-next-line no-underscore-dangle
49
+ err._alreadyLogged = true;
50
+ throw err;
51
+ }
52
+
53
+ /**
54
+ * Prettier helper
55
+ */
56
+ async function formatWithPrettier(tempFileText) {
57
+ return prettier.format(tempFileText, {
58
+ parser: 'typescript',
59
+ semi: true,
60
+ singleQuote: true,
61
+ tabWidth: 2,
62
+ });
63
+ }
64
+
65
+ /**
66
+ * ESLint validation for non-generated files under src
67
+ * Fails if any non-generated TS/TSX file has errors
68
+ */
69
+ async function lintNonGeneratedOrThrow() {
70
+ const eslint = new ESLint({ cwd: PROJECT_ROOT });
71
+ const results = await eslint.lintFiles(['src/**/*.ts', 'src/**/*.tsx']);
72
+
73
+ const isGenerated = filePath =>
74
+ filePath.endsWith('.generated.ts') ||
75
+ filePath.endsWith('RenderNode.generated.tsx');
76
+
77
+ const errorResults = results.filter(
78
+ r => !isGenerated(r.filePath) && r.errorCount > 0
79
+ );
80
+
81
+ if (errorResults.length > 0) {
82
+ const summary = errorResults
83
+ .map(
84
+ r =>
85
+ `${path.relative(PROJECT_ROOT, r.filePath)}: ${r.errorCount} error(s)`
86
+ ) // keep concise
87
+ .join('\n');
88
+ return fail(`ESLint failed on non-generated files:\n${summary}`);
89
+ }
90
+ }
91
+
92
+ // ===== Ensuring & Validation =====
93
+
94
+ /**
95
+ * 1) Get all files in the component root
96
+ */
97
+ async function getAllEntriesInComponentsRoot() {
98
+ const exists = await fs
99
+ .stat(COMPONENTS_ROOT)
100
+ .then(() => true)
101
+ .catch(() => false);
102
+ if (!exists) {
103
+ return fail(`Components root not found at ${COMPONENTS_ROOT}`);
104
+ }
105
+ return await fs
106
+ .readdir(COMPONENTS_ROOT, { withFileTypes: true })
107
+ .then(dirents => {
108
+ return dirents.filter(d => d.name !== 'RenderNode.generated.tsx');
109
+ });
110
+ }
111
+
112
+ /**
113
+ * 2) Make sure all entries are folders (throw error with reason)
114
+ */
115
+ function ensureAllEntriesAreFolders(dirents) {
116
+ const notDirs = dirents.filter(d => !d.isDirectory()).map(d => d.name);
117
+ if (notDirs.length > 0) {
118
+ return fail(
119
+ `All entries in ${COMPONENTS_ROOT} must be directories. Non-directories found: ${notDirs.join(', ')}`
120
+ );
121
+ }
122
+ }
123
+
124
+ /**
125
+ * 3) Validate pattern.json has correct props
126
+ * Required structure:
127
+ * - schemaVersion: number
128
+ * - allowUnknownAttributes: boolean
129
+ * - pattern: {
130
+ * type: string
131
+ * children: string
132
+ * attributes: Record<string, 'string' | 'number' | string[]>
133
+ * }
134
+ */
135
+ async function validatePatternJson(componentDir, componentName) {
136
+ const patternPath = path.join(componentDir, 'pattern.json');
137
+ const exists = await fs
138
+ .stat(patternPath)
139
+ .then(() => true)
140
+ .catch(() => false);
141
+ if (!exists) {
142
+ return fail(
143
+ `Missing pattern.json for component ${componentName} at ${patternPath}`
144
+ );
145
+ }
146
+ const data = await readJson(patternPath);
147
+
148
+ if (typeof data.schemaVersion !== 'number') {
149
+ return fail(
150
+ `[${componentName}] pattern.json -> 'schemaVersion' must be a number`
151
+ );
152
+ }
153
+ if (typeof data.allowUnknownAttributes !== 'boolean') {
154
+ return fail(
155
+ `[${componentName}] pattern.json -> 'allowUnknownAttributes' must be a boolean`
156
+ );
157
+ }
158
+ if (typeof data.pattern !== 'object' || data.pattern == null) {
159
+ return fail(
160
+ `[${componentName}] pattern.json -> 'pattern' must be an object`
161
+ );
162
+ }
163
+ const { pattern } = data;
164
+ if (typeof pattern.type !== 'string') {
165
+ return fail(
166
+ `[${componentName}] pattern.json -> 'pattern.type' must be a string`
167
+ );
168
+ }
169
+ if (
170
+ typeof pattern.children !== 'string' &&
171
+ !Array.isArray(pattern.children)
172
+ ) {
173
+ return fail(
174
+ `[${componentName}] pattern.json -> 'pattern.children' must be a string or an array`
175
+ );
176
+ }
177
+ if (typeof pattern.attributes !== 'object' || pattern.attributes == null) {
178
+ return fail(
179
+ `[${componentName}] pattern.json -> 'pattern.attributes' must be an object`
180
+ );
181
+ }
182
+
183
+ for (const [attrName, attrType] of Object.entries(pattern.attributes)) {
184
+ const isValidType =
185
+ typeof attrType === 'string' &&
186
+ (attrType === 'string' || attrType === 'number' || attrType === 'boolean')
187
+ ? true
188
+ : Array.isArray(attrType) && attrType.every(v => typeof v === 'string');
189
+ if (!isValidType) {
190
+ return fail(
191
+ `[${componentName}] pattern.json -> 'pattern.attributes.${attrName}' must be 'string' | 'number' | 'boolean' | string[]`
192
+ );
193
+ }
194
+ }
195
+
196
+ return data;
197
+ }
198
+
199
+ /**
200
+ * Helper to derive TS type from attribute type specifier
201
+ */
202
+ // (Moved to Actions section) tsTypeFromAttributeType
203
+
204
+ /**
205
+ * 4) Create <Name>Props.generated.ts (child, attributes) inside the component folder
206
+ */
207
+ // (Moved to Actions section) createGeneratedProps
208
+
209
+ /**
210
+ * 5) Create <Name>Props.ts if it doesn't exist inside the component folder. Must export interface extending Generated.
211
+ */
212
+ // (Moved to Actions section) ensurePropsTs
213
+
214
+ /**
215
+ * 6) Check <Name>Props.ts is valid if it already exists (in the component folder)
216
+ */
217
+ async function validateExistingPropsTs(componentDir, componentName) {
218
+ const filePath = path.join(componentDir, `${componentName}Props.ts`);
219
+ const exists = await fs
220
+ .stat(filePath)
221
+ .then(() => true)
222
+ .catch(() => false);
223
+ if (!exists) return; // Created in step 5 if missing
224
+
225
+ const content = await fs.readFile(filePath, 'utf8');
226
+ const hasExportedInterface = new RegExp(
227
+ `export\\s+interface\\s+${componentName}Props\\s+extends\\s+${componentName}PropsGenerated`
228
+ ).test(content);
229
+ if (!hasExportedInterface) {
230
+ throw new Error(
231
+ `${filePath} must export interface '${componentName}Props' extending '${componentName}PropsGenerated'`
232
+ );
233
+ }
234
+ }
235
+
236
+ /**
237
+ * 7) Create <Name>.tsx inside its component folder
238
+ * Should return "hello world" and default export React.memo(Name)
239
+ */
240
+ // (Moved to Actions section) createComponentTsx
241
+
242
+ /**
243
+ * 8) If component file exists, check name, memo exists, export default memo
244
+ */
245
+ async function validateExistingComponentTsx(componentDir, componentName) {
246
+ const filePath = path.join(componentDir, `${componentName}.tsx`);
247
+ const exists = await fs
248
+ .stat(filePath)
249
+ .then(() => true)
250
+ .catch(() => false);
251
+ if (!exists) return; // Created in step 7 if missing
252
+
253
+ const content = await fs.readFile(filePath, 'utf8');
254
+ const hasConstDeclaration = new RegExp(`const\\s+${componentName}\\s*:`).test(
255
+ content
256
+ );
257
+ const hasFunctionDeclaration = new RegExp(
258
+ `function\\s+${componentName}\\s*\\(`
259
+ ).test(content);
260
+ const hasDeclaration = hasConstDeclaration || hasFunctionDeclaration;
261
+ const usesMemo = /React\.memo\(/.test(content);
262
+ const defaultExportMemo = new RegExp(
263
+ `export\\s+default\\s+React\\.memo\\(\\s*${componentName}\\s*\\)\\s*;?`
264
+ ).test(content);
265
+
266
+ if (!hasDeclaration) {
267
+ return fail(
268
+ `${filePath} must declare component as 'const ${componentName}: React.FC = (...)' or 'function ${componentName}()'`
269
+ );
270
+ }
271
+ if (!usesMemo) {
272
+ return fail(`${filePath} must use React.memo`);
273
+ }
274
+ if (!defaultExportMemo) {
275
+ return fail(`${filePath} must default export React.memo(${componentName})`);
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Validation aggregator per component: run all validations without creating files
281
+ * Returns the patternJson to be reused by actions
282
+ */
283
+ async function validateComponent(componentDir, componentName) {
284
+ const patternJson = await validatePatternJson(componentDir, componentName);
285
+ await validateExistingPropsTs(componentDir, componentName);
286
+ await validateExistingComponentTsx(componentDir, componentName);
287
+ return { componentDir, componentName, patternJson };
288
+ }
289
+
290
+ /**
291
+ * Validate all components first; if any fails, throw and skip all actions
292
+ */
293
+ async function validateAllComponentsOrThrow() {
294
+ const dirents = await getAllEntriesInComponentsRoot();
295
+ ensureAllEntriesAreFolders(dirents);
296
+
297
+ const validated = [];
298
+ for (const dirent of dirents) {
299
+ const componentName = dirent.name;
300
+ const componentDir = path.join(COMPONENTS_ROOT, componentName);
301
+ const result = await validateComponent(componentDir, componentName);
302
+ validated.push(result);
303
+ }
304
+ // Ensure fallback renderer exists for unknown component types
305
+ await ensureOtherTsExists();
306
+ return validated;
307
+ }
308
+
309
+ /**
310
+ * Ensure src/build-components/other.ts exists. Create with default implementation if missing.
311
+ */
312
+ async function ensureOtherTsExists() {
313
+ const otherPath = path.join(COMPONENTS_ROOT, 'other.ts');
314
+ const exists = await fs
315
+ .stat(otherPath)
316
+ .then(() => true)
317
+ .catch(() => false);
318
+ if (exists) return;
319
+
320
+ const content =
321
+ `import React from 'react';\n` +
322
+ `import type { Node } from '../types/Node';\n\n` +
323
+ `export function other(type: string, node: Node): React.ReactNode {\n` +
324
+ ` return null;\n` +
325
+ `}\n`;
326
+ const formatted = await formatWithPrettier(content);
327
+ await fs.writeFile(otherPath, formatted, 'utf8');
328
+ }
329
+
330
+ // ===== Actions & Generators =====
331
+
332
+ /** Helper to derive TS type from attribute type specifier */
333
+ function tsTypeFromAttributeType(attrType) {
334
+ if (attrType === 'string') return 'string';
335
+ if (attrType === 'number') return 'number';
336
+ if (attrType === 'boolean') return 'boolean';
337
+ if (Array.isArray(attrType)) {
338
+ const literals = attrType.map(v => JSON.stringify(v)).join(' | ');
339
+ return literals.length > 0 ? literals : 'string';
340
+ }
341
+ // Fallback
342
+ return 'string';
343
+ }
344
+
345
+ /** Create <Name>Props.generated.ts (child, attributes) inside the component folder */
346
+ async function createGeneratedProps(componentDir, componentName, patternJson) {
347
+ await ensureDir(componentDir);
348
+ const fileName = `${componentName}Props.generated.ts`;
349
+ const filePath = path.join(componentDir, fileName);
350
+
351
+ const { pattern, allowUnknownAttributes } = patternJson;
352
+ const attributes = pattern.attributes || {};
353
+ const attributeLines = Object.entries(attributes).map(([key, t]) => {
354
+ const tsType = tsTypeFromAttributeType(t);
355
+ return ` ${key}?: ${tsType};`;
356
+ });
357
+
358
+ const indexSignature = allowUnknownAttributes
359
+ ? ' [key: string]: string | number | boolean | undefined;\n'
360
+ : '';
361
+
362
+ const childTsType =
363
+ typeof pattern.children === 'string' ? pattern.children : 'string';
364
+ const normalizedChildTsType = ['string', 'number', 'boolean'].includes(
365
+ childTsType
366
+ )
367
+ ? childTsType
368
+ : 'string';
369
+
370
+ const fileContent =
371
+ `/* AUTO-GENERATED FILE - DO NOT EDIT */\n` +
372
+ `\n` +
373
+ `export interface ${componentName}PropsGenerated {\n` +
374
+ ` child: ${normalizedChildTsType};\n` +
375
+ ` attributes: {\n` +
376
+ (attributeLines.length ? attributeLines.join('\n') + '\n' : '') +
377
+ indexSignature +
378
+ ` };\n` +
379
+ `}\n`;
380
+
381
+ const formatted = await formatWithPrettier(fileContent);
382
+ await fs.writeFile(filePath, formatted, 'utf8');
383
+ }
384
+
385
+ /** Create <Name>Props.ts if it doesn't exist inside the component folder */
386
+ async function ensurePropsTs(componentDir, componentName) {
387
+ await ensureDir(componentDir);
388
+ const fileName = `${componentName}Props.ts`;
389
+ const filePath = path.join(componentDir, fileName);
390
+ const exists = await fs
391
+ .stat(filePath)
392
+ .then(() => true)
393
+ .catch(() => false);
394
+ if (exists) return; // Will be validated in step 6
395
+
396
+ const content =
397
+ `import type { ${componentName}PropsGenerated } from './${componentName}Props.generated';\n\n` +
398
+ `export interface ${componentName}Props extends ${componentName}PropsGenerated {\n}\n`;
399
+ const formatted = await formatWithPrettier(content);
400
+ await fs.writeFile(filePath, formatted, 'utf8');
401
+ }
402
+
403
+ /** Create <Name>.tsx inside its component folder */
404
+ async function createComponentTsx(componentDir, componentName) {
405
+ const filePath = path.join(componentDir, `${componentName}.tsx`);
406
+ const exists = await fs
407
+ .stat(filePath)
408
+ .then(() => true)
409
+ .catch(() => false);
410
+ if (exists) return; // Will be validated in step 8
411
+
412
+ const content =
413
+ `import React from 'react';\n\n` +
414
+ `function ${componentName}() {\n` +
415
+ ` return "hello world";\n` +
416
+ `}\n\n` +
417
+ `export default React.memo(${componentName});\n`;
418
+ const formatted = await formatWithPrettier(content);
419
+ await fs.writeFile(filePath, formatted, 'utf8');
420
+ }
421
+
422
+ /** Generate src/build-components/RenderNode.generated.tsx based on validated components */
423
+ async function createRenderNodeGenerated(validated) {
424
+ const targetPath = path.join(COMPONENTS_ROOT, 'RenderNode.generated.tsx');
425
+
426
+ // Build imports for all components discovered
427
+ const componentImports = validated
428
+ .map(
429
+ ({ componentName }) =>
430
+ `import ${componentName} from './${componentName}/${componentName}';`
431
+ )
432
+ .join('\n');
433
+
434
+ // Build switch cases from each component's pattern.type
435
+ const cases = validated
436
+ .map(({ componentName, patternJson }) => {
437
+ const type = patternJson?.pattern?.type;
438
+ return typeof type === 'string'
439
+ ? ` case ${JSON.stringify(type)}:\n return <${componentName} node={simpleNode} />;`
440
+ : null;
441
+ })
442
+ .filter(Boolean)
443
+ .join('\n');
444
+
445
+ const fileContent =
446
+ `/* AUTO-GENERATED FILE - DO NOT EDIT */\n` +
447
+ `import React from 'react';\n\n` +
448
+ `import {\n` +
449
+ ` Node,\n` +
450
+ ` NodeData,\n` +
451
+ ` isNodeArray,\n` +
452
+ ` isNodeNullOrUndefined,\n` +
453
+ ` isNodeString,\n` +
454
+ `} from '../index';\n\n` +
455
+ `import { other } from './other';\n\n` +
456
+ `// Builder components\n` +
457
+ componentImports +
458
+ `\n\n` +
459
+ `function RenderNode({ node }: { node: Node }) {\n` +
460
+ ` if (isNodeNullOrUndefined(node)) {\n` +
461
+ ` return null;\n` +
462
+ ` }\n` +
463
+ ` if (isNodeString(node)) {\n` +
464
+ ` return <Text node={{ children: node as string, type: 'text' }} />;\n` +
465
+ ` }\n` +
466
+ ` if (isNodeArray(node)) {\n` +
467
+ ` return (\n` +
468
+ ` <>\n` +
469
+ ` {(node as Node[]).map((item: Node, index) => (\n` +
470
+ ` <RenderNode key={index} node={item} />\n` +
471
+ ` ))}\n` +
472
+ ` </>\n` +
473
+ ` );\n` +
474
+ ` }\n\n` +
475
+ ` const simpleNode = node as NodeData;\n` +
476
+ ` switch (simpleNode?.type) {\n` +
477
+ cases +
478
+ `\n default:\n` +
479
+ ` return other(simpleNode?.type, node);\n` +
480
+ ` }\n` +
481
+ `}\n\n` +
482
+ `export default React.memo(RenderNode);\n`;
483
+
484
+ const formatted = await formatWithPrettier(fileContent);
485
+ await fs.writeFile(targetPath, formatted, 'utf8');
486
+ }
487
+
488
+ /** Format all TS/TSX files under src with Prettier */
489
+ async function formatAllSourceFiles() {
490
+ async function* walk(dir) {
491
+ const dirents = await fs.readdir(dir, { withFileTypes: true });
492
+ for (const dirent of dirents) {
493
+ const full = path.join(dir, dirent.name);
494
+ if (dirent.isDirectory()) {
495
+ // Skip common non-source directories
496
+ if (dirent.name === 'node_modules' || dirent.name === 'dist') continue;
497
+ yield* walk(full);
498
+ } else {
499
+ yield full;
500
+ }
501
+ }
502
+ }
503
+
504
+ const targets = [];
505
+ for await (const filePath of walk(SRC_ROOT)) {
506
+ if (filePath.endsWith('.ts') || filePath.endsWith('.tsx')) {
507
+ targets.push(filePath);
508
+ }
509
+ }
510
+
511
+ await Promise.all(
512
+ targets.map(async filePath => {
513
+ const original = await fs.readFile(filePath, 'utf8');
514
+ const formatted = await formatWithPrettier(original);
515
+ if (formatted !== original) {
516
+ await fs.writeFile(filePath, formatted, 'utf8');
517
+ }
518
+ })
519
+ );
520
+ }
521
+
522
+ /**
523
+ * Orchestrator
524
+ */
525
+ async function run() {
526
+ // First pass: validations only; aborts on first failure
527
+ const validated = await validateAllComponentsOrThrow();
528
+
529
+ // Lint pass: fail if non-generated files have ESLint errors
530
+ //await lintNonGeneratedOrThrow();
531
+
532
+ // Second pass: actions only if all validations passed
533
+ for (const { componentDir, componentName, patternJson } of validated) {
534
+ await createGeneratedProps(componentDir, componentName, patternJson);
535
+ await ensurePropsTs(componentDir, componentName);
536
+ await createComponentTsx(componentDir, componentName);
537
+
538
+ // Final sanity validations
539
+ await validateExistingPropsTs(componentDir, componentName);
540
+ await validateExistingComponentTsx(componentDir, componentName);
541
+ }
542
+
543
+ // Finally, generate the RenderNode for builder components
544
+ await createRenderNodeGenerated(validated);
545
+
546
+ // Format all TS/TSX files as the last step
547
+ await formatAllSourceFiles();
548
+ }
549
+
550
+ export default run;
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+
3
+ import run from './build-components.js';
4
+
5
+ console.log('Building components...');
6
+ try {
7
+ await run();
8
+ } catch (err) {
9
+ console.error(err?.stack || err?.message || err);
10
+ process.exit(1);
11
+ }
@@ -0,0 +1,107 @@
1
+ import React from 'react';
2
+ import { Node, NodeData, NodeDefaultAttribute } from './types/Node';
3
+ import { isNodeString } from './utils/analyseNode';
4
+ import { getAttributeSchema } from './utils/patterns';
5
+
6
+ type AttributesEditorProps = {
7
+ node: Node;
8
+ onChange: (next: Node) => void;
9
+ };
10
+
11
+ function Field({
12
+ name,
13
+ type,
14
+ value,
15
+ onChange,
16
+ }: {
17
+ name: string;
18
+ type: string | string[];
19
+ value: any;
20
+ onChange: (v: any) => void;
21
+ }) {
22
+ if (Array.isArray(type)) {
23
+ return (
24
+ <select
25
+ value={value ?? ''}
26
+ onChange={(e) => onChange(e.target.value)}
27
+ className="input"
28
+ >
29
+ <option value="">(none)</option>
30
+ {type.map((opt) => (
31
+ <option key={opt} value={opt}>
32
+ {opt}
33
+ </option>
34
+ ))}
35
+ </select>
36
+ );
37
+ }
38
+ if (type === 'number') {
39
+ return (
40
+ <input
41
+ type="number"
42
+ value={value ?? ''}
43
+ onChange={(e) =>
44
+ onChange(e.target.value === '' ? undefined : Number(e.target.value))
45
+ }
46
+ className="input"
47
+ />
48
+ );
49
+ }
50
+ if (type === 'boolean') {
51
+ return (
52
+ <input
53
+ type="checkbox"
54
+ checked={Boolean(value)}
55
+ onChange={(e) => onChange(e.target.checked)}
56
+ />
57
+ );
58
+ }
59
+ return (
60
+ <input
61
+ type="text"
62
+ value={value ?? ''}
63
+ onChange={(e) =>
64
+ onChange(e.target.value === '' ? undefined : e.target.value)
65
+ }
66
+ className="input"
67
+ />
68
+ );
69
+ }
70
+
71
+ export function AttributesEditor({ node, onChange }: AttributesEditorProps) {
72
+ if (!node || isNodeString(node)) return null;
73
+ const data = node as NodeData<NodeDefaultAttribute>;
74
+ const schema = getAttributeSchema(data?.type) ?? {};
75
+ const attributes = (data?.attributes ?? {}) as NodeDefaultAttribute;
76
+
77
+ const entries = Object.entries(schema);
78
+ if (entries.length === 0) {
79
+ return (
80
+ <div style={{ padding: 8, opacity: 0.7 }}>No editable attributes</div>
81
+ );
82
+ }
83
+
84
+ return (
85
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
86
+ {entries.map(([name, type]) => (
87
+ <React.Fragment key={name}>
88
+ <div style={{ alignSelf: 'center' }}>{name}</div>
89
+ <Field
90
+ name={name}
91
+ type={type}
92
+ value={attributes?.[name]}
93
+ onChange={(val) => {
94
+ const next: NodeData<NodeDefaultAttribute> = {
95
+ ...data,
96
+ attributes: { ...(attributes ?? {}), [name]: val },
97
+ };
98
+ onChange(next);
99
+ }}
100
+ />
101
+ </React.Fragment>
102
+ ))}
103
+ </div>
104
+ );
105
+ }
106
+
107
+ export default React.memo(AttributesEditor);