@fragments-sdk/cli 0.9.0 → 0.10.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 (166) hide show
  1. package/dist/bin.d.ts +1 -0
  2. package/dist/bin.js +502 -84
  3. package/dist/bin.js.map +1 -1
  4. package/dist/{chunk-CJEGT3WD.js → chunk-566BNPQZ.js} +21 -6
  5. package/dist/chunk-566BNPQZ.js.map +1 -0
  6. package/dist/{chunk-WI6SLMSO.js → chunk-CAMXG5HJ.js} +5 -5
  7. package/dist/chunk-D2CDBRNU.js +2 -0
  8. package/dist/{chunk-YMPGYEWK.js → chunk-D5PYOXEI.js} +2 -2
  9. package/dist/{chunk-NGIMCIK2.js → chunk-OQO55NKV.js} +405 -34
  10. package/dist/chunk-OQO55NKV.js.map +1 -0
  11. package/dist/{chunk-TOIE7VXF.js → chunk-PW7QTQA6.js} +2 -2
  12. package/dist/{chunk-AWYCDRPG.js → chunk-WXSR2II7.js} +2 -2
  13. package/dist/chunk-WXSR2II7.js.map +1 -0
  14. package/dist/{chunk-2JIKCJX3.js → chunk-ZDA3PLQ6.js} +17 -14
  15. package/dist/chunk-ZDA3PLQ6.js.map +1 -0
  16. package/dist/core/index.d.ts +1 -2092
  17. package/dist/core/index.js +26 -21
  18. package/dist/{discovery-Z4RDDFVR.js → discovery-NEOY4MPN.js} +3 -3
  19. package/dist/generate-BGKTKO6E.js +459 -0
  20. package/dist/generate-BGKTKO6E.js.map +1 -0
  21. package/dist/index.d.ts +3 -5
  22. package/dist/index.js +7 -8
  23. package/dist/index.js.map +1 -1
  24. package/dist/{init-KSAAS7X3.js → init-Q53R5Q2T.js} +66 -76
  25. package/dist/init-Q53R5Q2T.js.map +1 -0
  26. package/dist/mcp-bin.js +5 -7
  27. package/dist/mcp-bin.js.map +1 -1
  28. package/dist/scan-OQU7M4GH.js +14 -0
  29. package/dist/scan-generate-T5QNUG7N.js +691 -0
  30. package/dist/scan-generate-T5QNUG7N.js.map +1 -0
  31. package/dist/{service-A5GIGGGK.js → service-TQYWY65E.js} +4 -5
  32. package/dist/{static-viewer-NSODM5VX.js → static-viewer-NUBFPKWH.js} +4 -5
  33. package/dist/static-viewer-NUBFPKWH.js.map +1 -0
  34. package/dist/{test-RPWZAYSJ.js → test-2CSOSS3B.js} +4 -5
  35. package/dist/{test-RPWZAYSJ.js.map → test-2CSOSS3B.js.map} +1 -1
  36. package/dist/{tokens-NIXSZRX7.js → tokens-DXEGYTOJ.js} +6 -7
  37. package/dist/{tokens-NIXSZRX7.js.map → tokens-DXEGYTOJ.js.map} +1 -1
  38. package/dist/{viewer-SBTJDMP7.js → viewer-DBEPYM3G.js} +245 -23
  39. package/dist/viewer-DBEPYM3G.js.map +1 -0
  40. package/package.json +2 -1
  41. package/src/bin.ts +33 -1
  42. package/src/build.ts +13 -3
  43. package/src/commands/__tests__/scan-generate.test.ts +308 -0
  44. package/src/commands/build.ts +16 -2
  45. package/src/commands/generate.ts +383 -68
  46. package/src/commands/init.ts +81 -56
  47. package/src/commands/perf.ts +1 -1
  48. package/src/commands/scan-generate.ts +1013 -0
  49. package/src/commands/setup.ts +499 -0
  50. package/src/core/auto-props.ts +1 -1
  51. package/src/core/bundle-measurer.ts +2 -2
  52. package/src/core/config.ts +16 -4
  53. package/src/core/discovery.ts +2 -2
  54. package/src/core/generators/context.ts +1 -1
  55. package/src/core/generators/registry.ts +3 -3
  56. package/src/core/generators/typescript-extractor.ts +11 -1
  57. package/src/core/graph-extractor.ts +1 -1
  58. package/src/core/index.ts +3 -190
  59. package/src/core/loader.ts +2 -2
  60. package/src/core/parser.ts +1 -1
  61. package/src/core/previewLoader.ts +1 -1
  62. package/src/index.ts +2 -2
  63. package/src/migrate/converter.ts +9 -1
  64. package/src/migrate/parser.ts +2 -0
  65. package/src/migrate/types.ts +2 -0
  66. package/src/service/snippet-validation.test.ts +1 -1
  67. package/src/service/snippet-validation.ts +2 -2
  68. package/src/setup.ts +69 -24
  69. package/src/viewer/__tests__/viewer-integration.test.ts +4 -10
  70. package/src/viewer/components/AccessibilityPanel.tsx +305 -312
  71. package/src/viewer/components/ActionsPanel.tsx +31 -29
  72. package/src/viewer/components/AllVariantsPreview.tsx +78 -0
  73. package/src/viewer/components/App.tsx +187 -740
  74. package/src/viewer/components/BottomPanel.tsx +228 -132
  75. package/src/viewer/components/CodePanel.tsx +1 -1
  76. package/src/viewer/components/CommandPalette.tsx +7 -10
  77. package/src/viewer/components/ComponentDocView.tsx +164 -0
  78. package/src/viewer/components/ComponentGraph.tsx +111 -142
  79. package/src/viewer/components/ContractPanel.tsx +6 -6
  80. package/src/viewer/components/EmptyVariantMessage.tsx +54 -0
  81. package/src/viewer/components/FigmaEmbed.tsx +20 -18
  82. package/src/viewer/components/FragmentEditor.tsx +92 -115
  83. package/src/viewer/components/HeaderSearch.tsx +24 -0
  84. package/src/viewer/components/HealthDashboard.tsx +16 -2
  85. package/src/viewer/components/Icons.tsx +9 -0
  86. package/src/viewer/components/InteractionsPanel.tsx +101 -117
  87. package/src/viewer/components/IsolatedPreviewFrame.tsx +1 -0
  88. package/src/viewer/components/LandingPage.tsx +3 -3
  89. package/src/viewer/components/LeftSidebar.tsx +141 -63
  90. package/src/viewer/components/LoadErrorMessage.tsx +102 -0
  91. package/src/viewer/components/MultiViewportPreview.tsx +61 -142
  92. package/src/viewer/components/NoVariantsMessage.tsx +59 -0
  93. package/src/viewer/components/PanelShell.tsx +161 -0
  94. package/src/viewer/components/PerformancePanel.tsx +31 -28
  95. package/src/viewer/components/PreviewArea.tsx +1 -1
  96. package/src/viewer/components/PreviewAside.tsx +168 -0
  97. package/src/viewer/components/PreviewFrameHost.tsx +3 -3
  98. package/src/viewer/components/PropsEditor.tsx +70 -156
  99. package/src/viewer/components/ResizablePanel.tsx +103 -263
  100. package/src/viewer/components/RightSidebar.tsx +3 -9
  101. package/src/viewer/components/SkeletonLoader.tsx +13 -13
  102. package/src/viewer/components/TokenStylePanel.tsx +182 -209
  103. package/src/viewer/components/TopToolbar.tsx +159 -0
  104. package/src/viewer/components/VariantMatrix.tsx +42 -86
  105. package/src/viewer/components/VariantTabs.tsx +3 -3
  106. package/src/viewer/components/ViewerHeader.tsx +69 -0
  107. package/src/viewer/components/WebMCPDevTools.tsx +17 -23
  108. package/src/viewer/components/viewer-utils.ts +16 -0
  109. package/src/viewer/entry.tsx +5 -0
  110. package/src/viewer/hooks/useAppState.ts +27 -4
  111. package/src/viewer/hooks/usePreviewBridge.ts +2 -2
  112. package/src/viewer/preview-frame.html +6 -12
  113. package/src/viewer/server.ts +169 -2
  114. package/src/viewer/vendor/shared/src/ComponentDocContent.module.scss +10 -0
  115. package/src/viewer/vendor/shared/src/ComponentDocContent.module.scss.d.ts +2 -0
  116. package/src/viewer/vendor/shared/src/ComponentDocContent.tsx +274 -0
  117. package/src/viewer/vendor/shared/src/DocsHeaderBar.tsx +6 -18
  118. package/src/viewer/vendor/shared/src/DocsPageShell.tsx +5 -0
  119. package/src/viewer/vendor/shared/src/DocsSidebarNav.tsx +5 -16
  120. package/src/viewer/vendor/shared/src/PropsTable.module.scss +68 -0
  121. package/src/viewer/vendor/shared/src/PropsTable.module.scss.d.ts +2 -0
  122. package/src/viewer/vendor/shared/src/PropsTable.tsx +76 -0
  123. package/src/viewer/vendor/shared/src/VariantPreviewCard.module.scss +114 -0
  124. package/src/viewer/vendor/shared/src/VariantPreviewCard.module.scss.d.ts +2 -0
  125. package/src/viewer/vendor/shared/src/VariantPreviewCard.tsx +134 -0
  126. package/src/viewer/vendor/shared/src/index.ts +8 -0
  127. package/src/viewer/vendor/shared/src/types.ts +12 -0
  128. package/src/viewer/vite-plugin.ts +109 -4
  129. package/dist/chunk-2JIKCJX3.js.map +0 -1
  130. package/dist/chunk-AWYCDRPG.js.map +0 -1
  131. package/dist/chunk-CJEGT3WD.js.map +0 -1
  132. package/dist/chunk-EKLMXTWU.js +0 -80
  133. package/dist/chunk-EKLMXTWU.js.map +0 -1
  134. package/dist/chunk-GOVI6COW.js +0 -195
  135. package/dist/chunk-GOVI6COW.js.map +0 -1
  136. package/dist/chunk-NGIMCIK2.js.map +0 -1
  137. package/dist/defineFragment-D0UTve-I.d.ts +0 -665
  138. package/dist/generate-35OIMW4Y.js +0 -252
  139. package/dist/generate-35OIMW4Y.js.map +0 -1
  140. package/dist/init-KSAAS7X3.js.map +0 -1
  141. package/dist/scan-65RH3QMM.js +0 -15
  142. package/dist/viewer-SBTJDMP7.js.map +0 -1
  143. package/src/core/__tests__/preview-runtime.test.tsx +0 -111
  144. package/src/core/composition.test.ts +0 -262
  145. package/src/core/composition.ts +0 -318
  146. package/src/core/constants.ts +0 -114
  147. package/src/core/context.ts +0 -2
  148. package/src/core/defineFragment.ts +0 -141
  149. package/src/core/figma.ts +0 -263
  150. package/src/core/fragment-types.ts +0 -214
  151. package/src/core/performance-presets.ts +0 -142
  152. package/src/core/preview-runtime.tsx +0 -144
  153. package/src/core/schema.ts +0 -221
  154. package/src/core/storyAdapter.test.ts +0 -571
  155. package/src/core/storyAdapter.ts +0 -761
  156. package/src/core/storybook-csf.ts +0 -11
  157. package/src/core/token-parser.ts +0 -321
  158. package/src/core/token-types.ts +0 -287
  159. package/src/core/types.ts +0 -762
  160. /package/dist/{chunk-WI6SLMSO.js.map → chunk-CAMXG5HJ.js.map} +0 -0
  161. /package/dist/{discovery-Z4RDDFVR.js.map → chunk-D2CDBRNU.js.map} +0 -0
  162. /package/dist/{chunk-YMPGYEWK.js.map → chunk-D5PYOXEI.js.map} +0 -0
  163. /package/dist/{chunk-TOIE7VXF.js.map → chunk-PW7QTQA6.js.map} +0 -0
  164. /package/dist/{scan-65RH3QMM.js.map → discovery-NEOY4MPN.js.map} +0 -0
  165. /package/dist/{service-A5GIGGGK.js.map → scan-OQU7M4GH.js.map} +0 -0
  166. /package/dist/{static-viewer-NSODM5VX.js.map → service-TQYWY65E.js.map} +0 -0
@@ -0,0 +1,691 @@
1
+ import { createRequire as __banner_createRequire } from 'module'; const require = __banner_createRequire(import.meta.url);
2
+ import "./chunk-566BNPQZ.js";
3
+ import {
4
+ discoverAllComponents
5
+ } from "./chunk-WXSR2II7.js";
6
+ import {
7
+ extractPropsFromFile
8
+ } from "./chunk-D5PYOXEI.js";
9
+ import "./chunk-D2CDBRNU.js";
10
+ import {
11
+ BRAND
12
+ } from "./chunk-OQO55NKV.js";
13
+ import "./chunk-Z7EY4VHE.js";
14
+
15
+ // src/commands/scan-generate.ts
16
+ import { readFile, writeFile, access, mkdir } from "fs/promises";
17
+ import { resolve, basename, dirname, relative, join } from "path";
18
+ import * as ts from "typescript";
19
+ import pc from "picocolors";
20
+ async function scanGenerate(options) {
21
+ const scanPath = resolve(options.scanPath);
22
+ const generated = [];
23
+ const skipped = [];
24
+ const errors = [];
25
+ console.log(pc.cyan(`
26
+ ${BRAND.name} Scan \u2192 Generate
27
+ `));
28
+ console.log(pc.dim(`Scanning: ${scanPath}
29
+ `));
30
+ console.log(pc.dim("Phase 1: Discovering components..."));
31
+ const defaultScanPatterns = [
32
+ "**/*.tsx",
33
+ "**/*.ts"
34
+ ];
35
+ const components = await discoverAllComponents(scanPath, {
36
+ patterns: options.patterns || defaultScanPatterns,
37
+ exclude: [
38
+ "**/*.test.*",
39
+ "**/*.spec.*",
40
+ "**/*.stories.*",
41
+ "**/*.fragment.*",
42
+ "**/*.d.ts",
43
+ "**/__tests__/**",
44
+ "**/__mocks__/**",
45
+ "**/node_modules/**",
46
+ "**/dist/**"
47
+ ]
48
+ });
49
+ if (components.length === 0) {
50
+ console.log(
51
+ pc.yellow("No components found. Check the path or file patterns.")
52
+ );
53
+ return {
54
+ success: false,
55
+ generated: [],
56
+ skipped: [],
57
+ errors: [{ name: "*", error: "No components found" }],
58
+ averageConfidence: 0
59
+ };
60
+ }
61
+ console.log(pc.green(` Found ${components.length} components`));
62
+ console.log(pc.dim("\nPhase 2: Extracting component metadata..."));
63
+ const componentDataList = [];
64
+ for (const comp of components) {
65
+ let propsResult = null;
66
+ try {
67
+ propsResult = await extractPropsFromFile(comp.sourcePath, {
68
+ propsTypeName: `${comp.name}Props`
69
+ });
70
+ } catch {
71
+ }
72
+ let jsDoc = null;
73
+ try {
74
+ jsDoc = await extractComponentJSDoc(comp.sourcePath, comp.name);
75
+ } catch {
76
+ }
77
+ let compoundChildren = [];
78
+ try {
79
+ compoundChildren = await detectCompoundComponents(comp.sourcePath);
80
+ } catch {
81
+ }
82
+ let storyVariants = [];
83
+ if (!options.skipStorybook && comp.storyPath) {
84
+ try {
85
+ storyVariants = await extractStoryVariantsFromFile(comp.storyPath);
86
+ } catch {
87
+ }
88
+ }
89
+ componentDataList.push({
90
+ component: comp,
91
+ props: propsResult,
92
+ jsDoc,
93
+ compoundChildren,
94
+ storyVariants
95
+ });
96
+ }
97
+ const propsExtracted = componentDataList.filter(
98
+ (d) => d.props?.success && d.props.props.length > 0
99
+ ).length;
100
+ console.log(pc.green(` Extracted props for ${propsExtracted} components`));
101
+ console.log(pc.dim("\nPhase 3: Generating fragment files..."));
102
+ for (const data of componentDataList) {
103
+ const comp = data.component;
104
+ const componentDir = dirname(comp.sourcePath);
105
+ const componentBaseName = basename(comp.sourcePath, ".tsx");
106
+ let fragmentDir;
107
+ if (options.outputDir) {
108
+ fragmentDir = resolve(options.outputDir, comp.name);
109
+ await mkdir(fragmentDir, { recursive: true });
110
+ } else {
111
+ fragmentDir = componentDir;
112
+ }
113
+ const fragmentPath = join(
114
+ fragmentDir,
115
+ `${componentBaseName}${BRAND.fileExtension}`
116
+ );
117
+ let fragmentExists = false;
118
+ try {
119
+ await access(fragmentPath);
120
+ fragmentExists = true;
121
+ } catch {
122
+ }
123
+ if (fragmentExists && !options.force) {
124
+ skipped.push({ name: comp.name, reason: "Fragment already exists" });
125
+ if (options.verbose) {
126
+ console.log(pc.dim(` Skipping ${comp.name} (fragment exists)`));
127
+ }
128
+ continue;
129
+ }
130
+ try {
131
+ const confidence = calculateFieldConfidence(data);
132
+ const importPath = computeImportPath(
133
+ fragmentDir,
134
+ comp.sourcePath,
135
+ componentBaseName
136
+ );
137
+ const content = generateFragmentWithTodos(
138
+ comp.name,
139
+ importPath,
140
+ data,
141
+ confidence
142
+ );
143
+ await writeFile(fragmentPath, content, "utf-8");
144
+ const relPath = relative(process.cwd(), fragmentPath);
145
+ generated.push({
146
+ name: comp.name,
147
+ path: relPath,
148
+ confidence: confidence.score,
149
+ todoCount: confidence.todoFields.length
150
+ });
151
+ const confColor = confidence.score >= 70 ? pc.green : confidence.score >= 40 ? pc.yellow : pc.red;
152
+ console.log(
153
+ pc.green(` \u2713 ${comp.name}`) + pc.dim(` (confidence: `) + confColor(`${confidence.score}`) + pc.dim(`, TODOs: ${confidence.todoFields.length})`)
154
+ );
155
+ } catch (e) {
156
+ errors.push({
157
+ name: comp.name,
158
+ error: e instanceof Error ? e.message : String(e)
159
+ });
160
+ console.log(pc.red(` \u2717 ${comp.name}: ${e instanceof Error ? e.message : String(e)}`));
161
+ }
162
+ }
163
+ const avgConfidence = generated.length > 0 ? Math.round(
164
+ generated.reduce((sum, g) => sum + g.confidence, 0) / generated.length
165
+ ) : 0;
166
+ console.log(pc.dim("\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));
167
+ console.log(pc.green(`
168
+ \u2713 Generated ${generated.length} fragment file(s)`));
169
+ if (skipped.length > 0) {
170
+ console.log(
171
+ pc.dim(` Skipped ${skipped.length} (use --force to overwrite)`)
172
+ );
173
+ }
174
+ if (errors.length > 0) {
175
+ console.log(pc.yellow(` ${errors.length} error(s)`));
176
+ }
177
+ console.log(pc.dim(` Average confidence: ${avgConfidence}/100`));
178
+ const totalTodos = generated.reduce((sum, g) => sum + g.todoCount, 0);
179
+ if (totalTodos > 0) {
180
+ console.log(
181
+ pc.dim(` Total TODOs: ${totalTodos}`) + pc.dim(` \u2014 search for "TODO:" in generated files`)
182
+ );
183
+ }
184
+ console.log();
185
+ return {
186
+ success: errors.length === 0,
187
+ generated,
188
+ skipped,
189
+ errors,
190
+ averageConfidence: avgConfidence
191
+ };
192
+ }
193
+ async function extractComponentJSDoc(filePath, componentName) {
194
+ const content = await readFile(filePath, "utf-8");
195
+ return extractComponentJSDocFromSource(content, filePath, componentName);
196
+ }
197
+ function extractComponentJSDocFromSource(source, filePath, componentName) {
198
+ const sourceFile = ts.createSourceFile(
199
+ filePath,
200
+ source,
201
+ ts.ScriptTarget.ESNext,
202
+ true,
203
+ filePath.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS
204
+ );
205
+ const targetName = componentName || basename(filePath).replace(/\.(tsx?|jsx?)$/, "");
206
+ let componentDoc = null;
207
+ let propsInterfaceDoc = null;
208
+ for (const statement of sourceFile.statements) {
209
+ if (ts.isFunctionDeclaration(statement) && statement.name?.text === targetName && hasExportModifier(statement)) {
210
+ const doc = getLeadingJSDoc(statement, sourceFile);
211
+ if (doc) componentDoc = doc;
212
+ }
213
+ if (ts.isVariableStatement(statement) && hasExportModifier(statement)) {
214
+ for (const decl of statement.declarationList.declarations) {
215
+ if (ts.isIdentifier(decl.name) && decl.name.text === targetName) {
216
+ const doc = getLeadingJSDoc(statement, sourceFile);
217
+ if (doc) componentDoc = doc;
218
+ }
219
+ }
220
+ }
221
+ if (ts.isFunctionDeclaration(statement) && hasDefaultExportModifier(statement)) {
222
+ const doc = getLeadingJSDoc(statement, sourceFile);
223
+ if (doc) componentDoc = doc;
224
+ }
225
+ if (ts.isInterfaceDeclaration(statement) && (statement.name.text === `${targetName}Props` || statement.name.text === `${targetName}Properties`)) {
226
+ const doc = getLeadingJSDoc(statement, sourceFile);
227
+ if (doc) propsInterfaceDoc = doc;
228
+ }
229
+ }
230
+ return componentDoc || propsInterfaceDoc;
231
+ }
232
+ function hasExportModifier(node) {
233
+ const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : void 0;
234
+ return modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ?? false;
235
+ }
236
+ function hasDefaultExportModifier(node) {
237
+ const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : void 0;
238
+ if (!modifiers) return false;
239
+ return modifiers.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) && modifiers.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword);
240
+ }
241
+ function getLeadingJSDoc(node, sourceFile) {
242
+ const fullText = sourceFile.getFullText();
243
+ const nodeStart = node.getFullStart();
244
+ const nodePos = node.getStart(sourceFile);
245
+ const leadingText = fullText.slice(nodeStart, nodePos);
246
+ const jsDocMatch = leadingText.match(/\/\*\*([\s\S]*?)\*\//);
247
+ if (!jsDocMatch) return null;
248
+ const lines = jsDocMatch[1].split("\n");
249
+ const descriptionLines = [];
250
+ for (const line of lines) {
251
+ const trimmed = line.replace(/^\s*\*?\s?/, "").trim();
252
+ if (trimmed.startsWith("@")) break;
253
+ if (trimmed) descriptionLines.push(trimmed);
254
+ }
255
+ return descriptionLines.length > 0 ? descriptionLines.join(" ") : null;
256
+ }
257
+ async function detectCompoundComponents(filePath) {
258
+ const content = await readFile(filePath, "utf-8");
259
+ return detectCompoundComponentsFromSource(content, filePath);
260
+ }
261
+ function detectCompoundComponentsFromSource(source, filePath) {
262
+ const sourceFile = ts.createSourceFile(
263
+ filePath,
264
+ source,
265
+ ts.ScriptTarget.ESNext,
266
+ true,
267
+ filePath.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS
268
+ );
269
+ const subComponents = [];
270
+ function visit(node) {
271
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === "Object" && node.expression.name.text === "assign" && node.arguments.length >= 2) {
272
+ const secondArg = node.arguments[1];
273
+ if (ts.isObjectLiteralExpression(secondArg)) {
274
+ for (const prop of secondArg.properties) {
275
+ if (ts.isShorthandPropertyAssignment(prop)) {
276
+ subComponents.push(prop.name.text);
277
+ } else if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
278
+ subComponents.push(prop.name.text);
279
+ }
280
+ }
281
+ }
282
+ }
283
+ ts.forEachChild(node, visit);
284
+ }
285
+ ts.forEachChild(sourceFile, visit);
286
+ return subComponents;
287
+ }
288
+ async function extractStoryVariantsFromFile(storyPath) {
289
+ const content = await readFile(storyPath, "utf-8");
290
+ const variants = [];
291
+ const exportMatches = content.matchAll(
292
+ /export\s+const\s+([A-Z][a-zA-Z0-9]*)\s*[=:]/g
293
+ );
294
+ for (const match of exportMatches) {
295
+ const name = match[1];
296
+ if (name === "default" || name.endsWith("Args") || name.endsWith("Meta")) {
297
+ continue;
298
+ }
299
+ const args = extractStoryArgs(content, name);
300
+ variants.push({ name, args });
301
+ }
302
+ return variants;
303
+ }
304
+ function extractStoryArgs(content, storyName) {
305
+ const storyPattern = new RegExp(
306
+ `export\\s+const\\s+${storyName}[^=]*=\\s*\\{([\\s\\S]*?)\\n\\};`
307
+ );
308
+ const storyMatch = content.match(storyPattern);
309
+ if (!storyMatch) return {};
310
+ const storyBody = storyMatch[1];
311
+ const argsStart = storyBody.indexOf("args:");
312
+ if (argsStart === -1) return {};
313
+ const braceStart = storyBody.indexOf("{", argsStart);
314
+ if (braceStart === -1) return {};
315
+ let depth = 0;
316
+ let braceEnd = -1;
317
+ for (let i = braceStart; i < storyBody.length; i++) {
318
+ if (storyBody[i] === "{") depth++;
319
+ else if (storyBody[i] === "}") {
320
+ depth--;
321
+ if (depth === 0) {
322
+ braceEnd = i;
323
+ break;
324
+ }
325
+ }
326
+ }
327
+ if (braceEnd === -1) return {};
328
+ const argsBlock = storyBody.slice(braceStart + 1, braceEnd).trim();
329
+ return parseArgsBlock(argsBlock);
330
+ }
331
+ function parseArgsBlock(argsBlock) {
332
+ const args = {};
333
+ const pairPattern = /(\w+)\s*:\s*(?:['"]([^'"]*?)['"]|(true|false)|(\d+(?:\.\d+)?))/g;
334
+ let pairMatch;
335
+ while ((pairMatch = pairPattern.exec(argsBlock)) !== null) {
336
+ const key = pairMatch[1];
337
+ if (pairMatch[2] !== void 0) {
338
+ args[key] = pairMatch[2];
339
+ } else if (pairMatch[3] !== void 0) {
340
+ args[key] = pairMatch[3] === "true";
341
+ } else if (pairMatch[4] !== void 0) {
342
+ args[key] = Number(pairMatch[4]);
343
+ }
344
+ }
345
+ return args;
346
+ }
347
+ function calculateFieldConfidence(data) {
348
+ let score = 0;
349
+ const todoFields = [];
350
+ const hasProps = data.props?.success && data.props.props.length > 0;
351
+ if (hasProps) {
352
+ score += 30;
353
+ }
354
+ if (data.jsDoc) {
355
+ score += 15;
356
+ } else {
357
+ todoFields.push("meta.description");
358
+ }
359
+ const category = inferCategory(
360
+ data.component.name,
361
+ data.props?.success ? data.props.props : []
362
+ );
363
+ if (category !== "Components") {
364
+ score += 10;
365
+ } else {
366
+ todoFields.push("meta.category");
367
+ }
368
+ if (data.storyVariants.length > 0) {
369
+ score += 25;
370
+ }
371
+ if (hasProps) {
372
+ const allResolved = data.props.props.every(
373
+ (p) => p.propType.type !== "custom"
374
+ );
375
+ if (allResolved) {
376
+ score += 10;
377
+ }
378
+ }
379
+ if (data.compoundChildren.length > 0) {
380
+ score += 5;
381
+ }
382
+ if (hasProps) {
383
+ const hasDefaults = data.props.props.some(
384
+ (p) => p.defaultValue !== void 0
385
+ );
386
+ if (hasDefaults) {
387
+ score += 5;
388
+ }
389
+ }
390
+ todoFields.push("usage.when");
391
+ todoFields.push("usage.whenNot");
392
+ return { score: Math.min(score, 100), todoFields };
393
+ }
394
+ var CATEGORY_PATTERNS = {
395
+ Actions: ["button", "action", "cta", "fab", "floatingaction"],
396
+ Forms: [
397
+ "form",
398
+ "input",
399
+ "select",
400
+ "checkbox",
401
+ "radio",
402
+ "textarea",
403
+ "field",
404
+ "textfield",
405
+ "datepicker",
406
+ "switch",
407
+ "slider",
408
+ "segmented"
409
+ ],
410
+ Layout: [
411
+ "layout",
412
+ "container",
413
+ "grid",
414
+ "flex",
415
+ "stack",
416
+ "box",
417
+ "divider",
418
+ "spacer",
419
+ "sidebar"
420
+ ],
421
+ Navigation: [
422
+ "nav",
423
+ "menu",
424
+ "breadcrumb",
425
+ "tab",
426
+ "link",
427
+ "pagination",
428
+ "stepper",
429
+ "topbar"
430
+ ],
431
+ Feedback: [
432
+ "alert",
433
+ "toast",
434
+ "notification",
435
+ "message",
436
+ "badge",
437
+ "indicator",
438
+ "progress",
439
+ "spinner",
440
+ "loading",
441
+ "loader",
442
+ "lozenge",
443
+ "chip"
444
+ ],
445
+ "Data Display": [
446
+ "table",
447
+ "list",
448
+ "card",
449
+ "avatar",
450
+ "stat",
451
+ "timeline",
452
+ "tree",
453
+ "datalist",
454
+ "datacard"
455
+ ],
456
+ Overlays: [
457
+ "modal",
458
+ "dialog",
459
+ "drawer",
460
+ "popover",
461
+ "tooltip",
462
+ "dropdown",
463
+ "slidepanel"
464
+ ],
465
+ Typography: ["text", "heading", "title", "label", "paragraph"],
466
+ Media: ["image", "video", "icon", "carousel"]
467
+ };
468
+ function inferCategory(componentName, props) {
469
+ const lower = componentName.toLowerCase();
470
+ for (const [category, patterns] of Object.entries(CATEGORY_PATTERNS)) {
471
+ for (const pattern of patterns) {
472
+ if (lower.includes(pattern)) {
473
+ return category;
474
+ }
475
+ }
476
+ }
477
+ const propNames = new Set(props.map((p) => p.name));
478
+ if (propNames.has("onClick") || propNames.has("onPress")) return "Actions";
479
+ if (propNames.has("value") || propNames.has("defaultValue")) return "Forms";
480
+ if (propNames.has("children")) return "Layout";
481
+ return "Components";
482
+ }
483
+ function inferStatus(filePath) {
484
+ const lowerPath = filePath.toLowerCase();
485
+ if (lowerPath.includes("/experimental/") || lowerPath.includes("/labs/"))
486
+ return "experimental";
487
+ if (lowerPath.includes("/beta/")) return "beta";
488
+ if (lowerPath.includes("/deprecated/") || lowerPath.includes("/legacy/"))
489
+ return "deprecated";
490
+ if (lowerPath.includes("/draft/") || lowerPath.includes("/wip/"))
491
+ return "draft";
492
+ return "stable";
493
+ }
494
+ function inferDescription(componentName, props) {
495
+ const words = componentName.replace(/([A-Z])/g, " $1").trim().toLowerCase();
496
+ const propNames = new Set(props.map((p) => p.name));
497
+ const hasOnClick = propNames.has("onClick") || propNames.has("onPress");
498
+ const hasValue = propNames.has("value") || propNames.has("defaultValue");
499
+ const hasChildren = propNames.has("children");
500
+ if (hasOnClick && !hasValue)
501
+ return `Interactive ${words} element for triggering actions`;
502
+ if (hasValue) return `Form ${words} for user input`;
503
+ if (hasChildren) return `Container ${words} for grouping content`;
504
+ return `${words.charAt(0).toUpperCase() + words.slice(1)} component`;
505
+ }
506
+ function inferAccessibility(props) {
507
+ const propNames = new Set(props.map((p) => p.name));
508
+ const accessibility = {};
509
+ const hasOnClick = propNames.has("onClick") || propNames.has("onPress");
510
+ const hasAriaLabel = propNames.has("ariaLabel") || propNames.has("aria-label");
511
+ const hasDisabled = propNames.has("disabled");
512
+ const hasHref = propNames.has("href");
513
+ if (hasOnClick && !hasHref) accessibility.role = "button";
514
+ else if (hasHref) accessibility.role = "link";
515
+ const requirements = [];
516
+ if (hasOnClick && !hasAriaLabel)
517
+ requirements.push("Should have visible text or aria-label");
518
+ if (hasDisabled)
519
+ requirements.push(
520
+ "Disabled state should be conveyed to assistive technology"
521
+ );
522
+ if (requirements.length > 0) accessibility.requirements = requirements;
523
+ return accessibility;
524
+ }
525
+ function computeImportPath(fragmentDir, sourcePath, componentBaseName) {
526
+ const sourceDir = dirname(sourcePath);
527
+ if (fragmentDir === sourceDir) {
528
+ if (componentBaseName === "index") {
529
+ return ".";
530
+ }
531
+ return `./${componentBaseName}`;
532
+ }
533
+ let rel = relative(fragmentDir, sourceDir);
534
+ if (!rel.startsWith(".")) rel = `./${rel}`;
535
+ if (componentBaseName !== "index") {
536
+ rel = `${rel}/${componentBaseName}`;
537
+ }
538
+ return rel;
539
+ }
540
+ function escapeQuotes(str) {
541
+ return str.replace(/'/g, "\\'");
542
+ }
543
+ function generateFragmentWithTodos(componentName, importPath, data, confidence) {
544
+ const props = data.props?.success ? data.props.props : [];
545
+ const isDefaultExport = data.props?.success ? !data.props.propsTypeName : false;
546
+ const description = data.jsDoc || inferDescription(componentName, props);
547
+ const descriptionTodo = data.jsDoc ? "" : " // TODO: Review description";
548
+ const category = inferCategory(componentName, props);
549
+ const categoryTodo = category === "Components" ? " // TODO: Set correct category" : "";
550
+ const status = inferStatus(data.component.sourcePath);
551
+ const accessibility = inferAccessibility(props);
552
+ const propsBlock = buildPropsBlock(props);
553
+ const accessibilityBlock = buildAccessibilityBlock(accessibility);
554
+ const variantsBlock = buildVariantsBlock(
555
+ componentName,
556
+ data.storyVariants
557
+ );
558
+ const compoundComment = data.compoundChildren.length > 0 ? `
559
+ // Compound sub-components detected: ${data.compoundChildren.join(", ")}` : "";
560
+ return `// Auto-generated by fragments init --scan | Confidence: ${confidence.score}/100
561
+ // ${confidence.todoFields.length} TODO(s) \u2014 search for "TODO:" and fill in human knowledge
562
+ import React from 'react';
563
+ import { defineFragment } from '@fragments-sdk/core';
564
+ import { ${componentName} } from '${importPath}';
565
+
566
+ export default defineFragment({
567
+ component: ${componentName},
568
+ ${compoundComment}
569
+ meta: {
570
+ name: '${escapeQuotes(componentName)}',
571
+ description: '${escapeQuotes(description)}',${descriptionTodo}
572
+ category: '${escapeQuotes(category)}',${categoryTodo}
573
+ status: '${status}',
574
+ },
575
+
576
+ usage: {
577
+ when: [
578
+ // TODO: Describe when to use ${componentName}
579
+ ],
580
+ whenNot: [
581
+ // TODO: Describe when NOT to use ${componentName}
582
+ ],
583
+ },
584
+
585
+ props: ${propsBlock},${accessibilityBlock}
586
+
587
+ variants: [
588
+ ${variantsBlock}
589
+ ],
590
+ });
591
+ `;
592
+ }
593
+ function buildPropsBlock(props) {
594
+ if (props.length === 0) return "{}";
595
+ const lines = props.map((prop) => {
596
+ const type = prop.propType.type;
597
+ const parts = [` type: '${type}'`];
598
+ if (prop.description) {
599
+ parts.push(
600
+ ` description: '${escapeQuotes(prop.description.replace(/\n/g, " "))}'`
601
+ );
602
+ }
603
+ parts.push(` required: ${prop.required}`);
604
+ if (prop.defaultValue !== void 0) {
605
+ parts.push(` default: ${JSON.stringify(prop.defaultValue)}`);
606
+ }
607
+ if (prop.enumValues && prop.enumValues.length > 0) {
608
+ parts.push(` values: ${JSON.stringify(prop.enumValues)}`);
609
+ }
610
+ const todoComment = type === "custom" ? " // TODO: Review type" : "";
611
+ return ` ${prop.name}: {
612
+ ${parts.join(",\n")},
613
+ },${todoComment}`;
614
+ });
615
+ return `{
616
+ ${lines.join("\n")}
617
+ }`;
618
+ }
619
+ function buildAccessibilityBlock(accessibility) {
620
+ if (!accessibility.role && (!accessibility.requirements || accessibility.requirements.length === 0)) {
621
+ return "";
622
+ }
623
+ const parts = [];
624
+ if (accessibility.role) {
625
+ parts.push(` role: '${accessibility.role}'`);
626
+ }
627
+ if (accessibility.requirements && accessibility.requirements.length > 0) {
628
+ const reqs = accessibility.requirements.map((r) => `'${escapeQuotes(r)}'`).join(", ");
629
+ parts.push(` requirements: [${reqs}]`);
630
+ }
631
+ return `
632
+
633
+ accessibility: {
634
+ ${parts.join(",\n")},
635
+ },`;
636
+ }
637
+ function buildVariantsBlock(componentName, storyVariants) {
638
+ const entries = [];
639
+ const hasDefault = storyVariants.some((v) => v.name === "Default");
640
+ if (!hasDefault) {
641
+ entries.push(formatVariantEntry(componentName, "Default", `Default ${componentName}`, {}));
642
+ }
643
+ for (const variant of storyVariants) {
644
+ const description = variant.name.replace(/([A-Z])/g, " $1").trim();
645
+ entries.push(
646
+ formatVariantEntry(
647
+ componentName,
648
+ variant.name,
649
+ `${description} ${componentName}`,
650
+ variant.args
651
+ )
652
+ );
653
+ }
654
+ return entries.join("\n");
655
+ }
656
+ function formatVariantEntry(componentName, name, description, args) {
657
+ const jsxCode = buildJsxString(componentName, args);
658
+ return ` {
659
+ name: '${escapeQuotes(name)}',
660
+ description: '${escapeQuotes(description)}',
661
+ code: \`${jsxCode}\`,
662
+ render: () => ${jsxCode},
663
+ },`;
664
+ }
665
+ function buildJsxString(componentName, args) {
666
+ const { children, ...restArgs } = args;
667
+ const propParts = [];
668
+ for (const [key, value] of Object.entries(restArgs)) {
669
+ if (typeof value === "string") {
670
+ propParts.push(`${key}="${escapeQuotes(value)}"`);
671
+ } else if (typeof value === "boolean") {
672
+ propParts.push(value ? key : `${key}={false}`);
673
+ } else if (typeof value === "number") {
674
+ propParts.push(`${key}={${value}}`);
675
+ }
676
+ }
677
+ const propsStr = propParts.length > 0 ? " " + propParts.join(" ") : "";
678
+ if (typeof children === "string") {
679
+ return `<${componentName}${propsStr}>${children}</${componentName}>`;
680
+ }
681
+ return `<${componentName}${propsStr} />`;
682
+ }
683
+ export {
684
+ calculateFieldConfidence,
685
+ detectCompoundComponents,
686
+ detectCompoundComponentsFromSource,
687
+ extractComponentJSDoc,
688
+ extractComponentJSDocFromSource,
689
+ scanGenerate
690
+ };
691
+ //# sourceMappingURL=scan-generate-T5QNUG7N.js.map