@mui/internal-docs-infra 0.3.1-canary.3 → 0.3.1-canary.4

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 (102) hide show
  1. package/esm/CodeControllerContext/CodeControllerContext.js +2 -2
  2. package/esm/CodeExternalsContext/CodeExternalsContext.js +1 -1
  3. package/esm/CodeHighlighter/CodeHighlighter.js +247 -329
  4. package/esm/CodeHighlighter/CodeHighlighterClient.js +447 -653
  5. package/esm/CodeHighlighter/CodeHighlighterContext.js +2 -2
  6. package/esm/CodeHighlighter/CodeHighlighterFallbackContext.js +2 -2
  7. package/esm/CodeHighlighter/codeToFallbackProps.js +21 -37
  8. package/esm/CodeHighlighter/errors.js +248 -400
  9. package/esm/CodeHighlighter/parseControlledCode.js +12 -20
  10. package/esm/CodeProvider/CodeContext.js +3 -3
  11. package/esm/CodeProvider/CodeProvider.js +31 -40
  12. package/esm/abstractCreateDemo/abstractCreateDemo.js +13 -17
  13. package/esm/abstractCreateDemoClient/abstractCreateDemoClient.js +12 -12
  14. package/esm/cli/index.js +1 -1
  15. package/esm/cli/runValidate.js +160 -264
  16. package/esm/createDemoData/createDemoData.js +11 -12
  17. package/esm/createSitemap/createSitemap.js +2 -2
  18. package/esm/pipeline/getFileConventions/fileConventions.js +1 -1
  19. package/esm/pipeline/getFileConventions/getFileConventions.js +2 -15
  20. package/esm/pipeline/hastUtils/hastUtils.js +16 -17
  21. package/esm/pipeline/loadCodeVariant/addCodeVariantPaths.js +24 -24
  22. package/esm/pipeline/loadCodeVariant/applyCodeTransform.js +12 -22
  23. package/esm/pipeline/loadCodeVariant/calculateMainFilePath.js +30 -37
  24. package/esm/pipeline/loadCodeVariant/computeHastDeltas.js +107 -185
  25. package/esm/pipeline/loadCodeVariant/diffHast.js +18 -53
  26. package/esm/pipeline/loadCodeVariant/examineCodeVariant.js +24 -27
  27. package/esm/pipeline/loadCodeVariant/flattenCodeVariant.js +9 -10
  28. package/esm/pipeline/loadCodeVariant/hasAllCodeVariants.js +5 -5
  29. package/esm/pipeline/loadCodeVariant/loadCodeFallback.js +516 -731
  30. package/esm/pipeline/loadCodeVariant/loadCodeVariant.js +679 -1079
  31. package/esm/pipeline/loadCodeVariant/maybeCodeInitialData.js +14 -20
  32. package/esm/pipeline/loadCodeVariant/mergeCodeMetadata.js +53 -63
  33. package/esm/pipeline/loadCodeVariant/parseCode.js +40 -48
  34. package/esm/pipeline/loadCodeVariant/pathUtils.js +43 -64
  35. package/esm/pipeline/loadCodeVariant/transformSource.js +55 -125
  36. package/esm/pipeline/loadPrecomputedCodeHighlighter/loadPrecomputedCodeHighlighter.js +160 -221
  37. package/esm/pipeline/loadPrecomputedCodeHighlighter/parseCreateFactoryCall.js +377 -479
  38. package/esm/pipeline/loadPrecomputedCodeHighlighter/parseFunctionArguments.js +171 -173
  39. package/esm/pipeline/loadPrecomputedCodeHighlighter/performanceLogger.js +14 -30
  40. package/esm/pipeline/loadPrecomputedCodeHighlighter/replacePrecomputeValue.js +19 -21
  41. package/esm/pipeline/loadPrecomputedCodeHighlighter/serializeFunctionArguments.js +37 -71
  42. package/esm/pipeline/loadPrecomputedCodeHighlighterClient/filterRuntimeExternals.js +3 -9
  43. package/esm/pipeline/loadPrecomputedCodeHighlighterClient/generateImportStatements.js +54 -80
  44. package/esm/pipeline/loadPrecomputedCodeHighlighterClient/generateResolvedExternals.js +71 -98
  45. package/esm/pipeline/loadPrecomputedCodeHighlighterClient/injectImportsIntoSource.js +5 -5
  46. package/esm/pipeline/loadPrecomputedCodeHighlighterClient/loadPrecomputedCodeHighlighterClient.js +161 -211
  47. package/esm/pipeline/loadPrecomputedSitemap/loadPrecomputedSitemap.js +159 -207
  48. package/esm/pipeline/loadServerCodeMeta/loadServerCodeMeta.js +42 -64
  49. package/esm/pipeline/loadServerCodeMeta/resolveModulePathWithFs.js +20 -96
  50. package/esm/pipeline/loadServerPageIndex/loadServerPageIndex.js +66 -85
  51. package/esm/pipeline/loadServerSitemap/loadServerSitemap.js +71 -118
  52. package/esm/pipeline/loadServerSource/loadServerSource.js +121 -148
  53. package/esm/pipeline/loaderUtils/externalsToPackages.js +7 -7
  54. package/esm/pipeline/loaderUtils/extractNameAndSlugFromUrl.js +8 -12
  55. package/esm/pipeline/loaderUtils/fileUrlToPortablePath.js +5 -5
  56. package/esm/pipeline/loaderUtils/getFileNameFromUrl.js +19 -29
  57. package/esm/pipeline/loaderUtils/getLanguageFromExtension.js +3 -4
  58. package/esm/pipeline/loaderUtils/mergeExternals.js +15 -35
  59. package/esm/pipeline/loaderUtils/parseImportsAndComments.js +413 -433
  60. package/esm/pipeline/loaderUtils/processRelativeImports.js +153 -239
  61. package/esm/pipeline/loaderUtils/resolveModulePath.js +544 -1303
  62. package/esm/pipeline/loaderUtils/rewriteImports.js +73 -111
  63. package/esm/pipeline/parseSource/addLineGutters.js +33 -45
  64. package/esm/pipeline/parseSource/grammars.js +3 -3
  65. package/esm/pipeline/parseSource/parseSource.js +13 -31
  66. package/esm/pipeline/syncPageIndex/createMarkdownNodes.js +32 -55
  67. package/esm/pipeline/syncPageIndex/mergeMetadataMarkdown.js +107 -160
  68. package/esm/pipeline/syncPageIndex/metadataToMarkdown.js +846 -1033
  69. package/esm/pipeline/syncPageIndex/syncPageIndex.js +291 -438
  70. package/esm/pipeline/transformHtmlCodePrecomputed/transformHtmlCodePrecomputed.js +213 -311
  71. package/esm/pipeline/transformMarkdownBlockquoteCallouts/transformMarkdownBlockquoteCallouts.js +10 -10
  72. package/esm/pipeline/transformMarkdownCode/transformMarkdownCode.js +133 -193
  73. package/esm/pipeline/transformMarkdownDemoLinks/transformMarkdownDemoLinks.js +25 -27
  74. package/esm/pipeline/transformMarkdownMetadata/transformMarkdownMetadata.js +572 -717
  75. package/esm/pipeline/transformMarkdownRelativePaths/transformMarkdownRelativePaths.js +8 -8
  76. package/esm/pipeline/transformTypescriptToJavascript/removeTypes.js +84 -113
  77. package/esm/pipeline/transformTypescriptToJavascript/transformTypescriptToJavascript.js +10 -26
  78. package/esm/useCode/Pre.js +58 -62
  79. package/esm/useCode/useCode.js +59 -61
  80. package/esm/useCode/useCodeUtils.js +54 -63
  81. package/esm/useCode/useCopyFunctionality.js +10 -9
  82. package/esm/useCode/useFileNavigation.js +150 -212
  83. package/esm/useCode/useSourceEditing.js +17 -14
  84. package/esm/useCode/useTransformManagement.js +23 -26
  85. package/esm/useCode/useUIState.js +12 -20
  86. package/esm/useCode/useVariantSelection.js +62 -79
  87. package/esm/useCopier/index.js +29 -56
  88. package/esm/useDemo/createCodeSandbox.js +12 -15
  89. package/esm/useDemo/createStackBlitz.js +14 -20
  90. package/esm/useDemo/exportVariant.js +200 -180
  91. package/esm/useDemo/exportVariantAsCra.js +22 -25
  92. package/esm/useDemo/useDemo.js +80 -84
  93. package/esm/useErrors/ErrorsContext.js +1 -1
  94. package/esm/useErrors/useErrors.js +3 -3
  95. package/esm/useLocalStorageState/useLocalStorageState.js +23 -39
  96. package/esm/usePreference/PreferencesProvider.js +1 -1
  97. package/esm/usePreference/usePreference.js +9 -11
  98. package/esm/useSearch/useSearch.js +290 -387
  99. package/esm/useUrlHashState/useUrlHashState.js +11 -14
  100. package/esm/withDocsInfra/withDeploymentConfig.js +26 -21
  101. package/esm/withDocsInfra/withDocsInfra.js +99 -101
  102. package/package.json +7 -4
@@ -1,5 +1,3 @@
1
- import _createForOfIteratorHelper from "@babel/runtime/helpers/esm/createForOfIteratorHelper";
2
- import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
3
1
  /**
4
2
  * Generates a unique import name based on module path and original name
5
3
  */
@@ -14,30 +12,30 @@ function generateUniqueImportName(originalName, modulePath, type, usedNames) {
14
12
  // - Named imports from simple test cases (lib1, lib2, etc.): use numbered suffixes
15
13
  // - Other cases: try module-based names first
16
14
 
17
- var wantsNumberedSuffix = type === 'namespace' || modulePath.startsWith('lib') && /^lib\d+$/.test(modulePath);
15
+ const wantsNumberedSuffix = type === 'namespace' || modulePath.startsWith('lib') && /^lib\d+$/.test(modulePath);
18
16
  if (wantsNumberedSuffix) {
19
17
  // Use numbered suffixes
20
- var attempt = 1;
21
- var _uniqueName = "".concat(originalName).concat(attempt);
22
- while (usedNames.has(_uniqueName)) {
18
+ let attempt = 1;
19
+ let uniqueName = `${originalName}${attempt}`;
20
+ while (usedNames.has(uniqueName)) {
23
21
  attempt += 1;
24
- _uniqueName = "".concat(originalName).concat(attempt);
22
+ uniqueName = `${originalName}${attempt}`;
25
23
  }
26
- return _uniqueName;
24
+ return uniqueName;
27
25
  }
28
26
 
29
27
  // For real modules, try module-based names first
30
- var moduleKey = modulePath.replace(/[@/.-]/g, '') // Remove special characters
28
+ const moduleKey = modulePath.replace(/[@/.-]/g, '') // Remove special characters
31
29
  .toLowerCase().slice(0, 20); // Limit length
32
30
 
33
- var uniqueName = "".concat(originalName).concat(moduleKey);
31
+ let uniqueName = `${originalName}${moduleKey}`;
34
32
 
35
33
  // If that's still taken, try numbered suffixes
36
34
  if (usedNames.has(uniqueName)) {
37
- var _attempt = 1;
35
+ let attempt = 1;
38
36
  do {
39
- uniqueName = "".concat(originalName).concat(_attempt);
40
- _attempt += 1;
37
+ uniqueName = `${originalName}${attempt}`;
38
+ attempt += 1;
41
39
  } while (usedNames.has(uniqueName));
42
40
  }
43
41
  return uniqueName;
@@ -56,131 +54,106 @@ function isValidIdentifier(str) {
56
54
  * Returns the import statements and the externals as a JavaScript object
57
55
  */
58
56
  export function generateResolvedExternals(externals) {
59
- var moduleImports = {};
60
- var usedNames = new Set();
61
- var seenImports = new Set();
57
+ const moduleImports = {};
58
+ const usedNames = new Set();
59
+ const seenImports = new Set();
62
60
 
63
61
  // First pass: collect all imports and resolve naming conflicts
64
- for (var _i = 0, _Object$entries = Object.entries(externals); _i < _Object$entries.length; _i++) {
65
- var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
66
- modulePath = _Object$entries$_i[0],
67
- importItems = _Object$entries$_i[1];
62
+ for (const [modulePath, importItems] of Object.entries(externals)) {
68
63
  if (!moduleImports[modulePath]) {
69
64
  moduleImports[modulePath] = {
70
65
  named: [],
71
66
  namespace: []
72
67
  };
73
68
  }
74
- var _iterator = _createForOfIteratorHelper(importItems),
75
- _step;
76
- try {
77
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
78
- var _step$value = _step.value,
79
- originalName = _step$value.name,
80
- type = _step$value.type,
81
- isType = _step$value.isType;
82
- // Skip type-only imports and empty names
83
- if (isType || !originalName.trim()) {
84
- continue;
85
- }
86
- var importKey = "".concat(modulePath, ":").concat(originalName, ":").concat(type);
87
-
88
- // Skip duplicates
89
- if (seenImports.has(importKey)) {
90
- continue;
91
- }
92
- seenImports.add(importKey);
93
- var uniqueName = generateUniqueImportName(originalName, modulePath, type, usedNames);
94
- usedNames.add(uniqueName);
95
- if (type === 'default') {
96
- moduleImports[modulePath]["default"] = uniqueName;
97
- } else if (type === 'named') {
98
- moduleImports[modulePath].named.push({
99
- original: originalName,
100
- unique: uniqueName
101
- });
102
- } else if (type === 'namespace') {
103
- moduleImports[modulePath].namespace.push(uniqueName);
104
- }
69
+ for (const {
70
+ name: originalName,
71
+ type,
72
+ isType
73
+ } of importItems) {
74
+ // Skip type-only imports and empty names
75
+ if (isType || !originalName.trim()) {
76
+ continue;
77
+ }
78
+ const importKey = `${modulePath}:${originalName}:${type}`;
79
+
80
+ // Skip duplicates
81
+ if (seenImports.has(importKey)) {
82
+ continue;
83
+ }
84
+ seenImports.add(importKey);
85
+ const uniqueName = generateUniqueImportName(originalName, modulePath, type, usedNames);
86
+ usedNames.add(uniqueName);
87
+ if (type === 'default') {
88
+ moduleImports[modulePath].default = uniqueName;
89
+ } else if (type === 'named') {
90
+ moduleImports[modulePath].named.push({
91
+ original: originalName,
92
+ unique: uniqueName
93
+ });
94
+ } else if (type === 'namespace') {
95
+ moduleImports[modulePath].namespace.push(uniqueName);
105
96
  }
106
- } catch (err) {
107
- _iterator.e(err);
108
- } finally {
109
- _iterator.f();
110
97
  }
111
98
  }
112
99
 
113
100
  // Second pass: generate consolidated import statements and resolved externals
114
- var imports = [];
115
- var resolvedExternalsObject = {};
116
- for (var _i2 = 0, _Object$entries2 = Object.entries(moduleImports); _i2 < _Object$entries2.length; _i2++) {
117
- var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2),
118
- _modulePath = _Object$entries2$_i[0],
119
- moduleImport = _Object$entries2$_i[1];
120
- var hasDefault = moduleImport["default"] !== undefined;
121
- var hasNamed = moduleImport.named.length > 0;
122
- var hasNamespace = moduleImport.namespace.length > 0;
101
+ const imports = [];
102
+ const resolvedExternalsObject = {};
103
+ for (const [modulePath, moduleImport] of Object.entries(moduleImports)) {
104
+ const hasDefault = moduleImport.default !== undefined;
105
+ const hasNamed = moduleImport.named.length > 0;
106
+ const hasNamespace = moduleImport.namespace.length > 0;
123
107
 
124
108
  // Skip modules that have no valid imports
125
109
  if (!hasDefault && !hasNamed && !hasNamespace) {
126
110
  continue;
127
111
  }
128
- var importParts = [];
112
+ const importParts = [];
129
113
 
130
114
  // Add default import
131
- if (moduleImport["default"]) {
132
- importParts.push(moduleImport["default"]);
115
+ if (moduleImport.default) {
116
+ importParts.push(moduleImport.default);
133
117
  }
134
118
 
135
119
  // Add named imports (consolidated into one statement)
136
120
  if (moduleImport.named.length > 0) {
137
- var namedImports = moduleImport.named.map(function (_ref) {
138
- var original = _ref.original,
139
- unique = _ref.unique;
140
- return original === unique ? original : "".concat(original, " as ").concat(unique);
141
- }).join(', ');
142
- importParts.push("{ ".concat(namedImports, " }"));
121
+ const namedImports = moduleImport.named.map(({
122
+ original,
123
+ unique
124
+ }) => original === unique ? original : `${original} as ${unique}`).join(', ');
125
+ importParts.push(`{ ${namedImports} }`);
143
126
  }
144
127
 
145
128
  // Generate import statement
146
129
  if (importParts.length > 0) {
147
- imports.push("import ".concat(importParts.join(', '), " from '").concat(_modulePath, "';"));
130
+ imports.push(`import ${importParts.join(', ')} from '${modulePath}';`);
148
131
  }
149
132
 
150
133
  // Add namespace imports (separate statements as they can't be combined)
151
- var _iterator2 = _createForOfIteratorHelper(moduleImport.namespace),
152
- _step2;
153
- try {
154
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
155
- var namespaceName = _step2.value;
156
- imports.push("import * as ".concat(namespaceName, " from '").concat(_modulePath, "';"));
157
- }
158
-
159
- // Generate resolved externals entry for this module
160
- // For invalid JavaScript identifiers, use the quoted version as the key
161
- } catch (err) {
162
- _iterator2.e(err);
163
- } finally {
164
- _iterator2.f();
134
+ for (const namespaceName of moduleImport.namespace) {
135
+ imports.push(`import * as ${namespaceName} from '${modulePath}';`);
165
136
  }
166
- var objectKey = isValidIdentifier(_modulePath) ? _modulePath : "\"".concat(_modulePath, "\"");
167
- var resolvedValue = void 0;
137
+
138
+ // Generate resolved externals entry for this module
139
+ // For invalid JavaScript identifiers, use the quoted version as the key
140
+ const objectKey = isValidIdentifier(modulePath) ? modulePath : `"${modulePath}"`;
141
+ let resolvedValue;
168
142
  if (hasDefault && !hasNamed && !hasNamespace) {
169
143
  // Single default export - use direct assignment (e.g., 'react': React)
170
- resolvedValue = moduleImport["default"];
144
+ resolvedValue = moduleImport.default;
171
145
  } else if (!hasDefault && hasNamed && !hasNamespace) {
172
146
  // Named exports only - use object syntax (e.g., '@mui/material': { Button, TextField })
173
- var namedExports = moduleImport.named.map(function (_ref2) {
174
- var original = _ref2.original;
175
- return original;
176
- }).join(', ');
177
- resolvedValue = "{ ".concat(namedExports, " }");
147
+ const namedExports = moduleImport.named.map(({
148
+ original
149
+ }) => original).join(', ');
150
+ resolvedValue = `{ ${namedExports} }`;
178
151
  } else if (!hasDefault && !hasNamed && hasNamespace) {
179
152
  // Single namespace export - use direct assignment (e.g., 'lodash': lodash)
180
153
  resolvedValue = moduleImport.namespace[0];
181
154
  } else if (hasDefault) {
182
155
  // Mixed imports - prefer default for the resolved externals
183
- resolvedValue = moduleImport["default"];
156
+ resolvedValue = moduleImport.default;
184
157
  } else if (hasNamespace) {
185
158
  // Mixed imports - use namespace if no default
186
159
  resolvedValue = moduleImport.namespace[0];
@@ -192,7 +165,7 @@ export function generateResolvedExternals(externals) {
192
165
  resolvedExternalsObject[objectKey] = resolvedValue;
193
166
  }
194
167
  return {
195
- imports: imports,
168
+ imports,
196
169
  resolvedExternals: resolvedExternalsObject
197
170
  };
198
171
  }
@@ -6,16 +6,16 @@ export function injectImportsIntoSource(source, importLines) {
6
6
  if (importLines.length === 0) {
7
7
  return source;
8
8
  }
9
- var importString = "".concat(importLines.join('\n'), "\n\n");
9
+ const importString = `${importLines.join('\n')}\n\n`;
10
10
 
11
11
  // Check if file starts with 'use client'
12
- var useClientMatch = source.match(/^['"]use client['"]\s*;\s*\n/);
12
+ const useClientMatch = source.match(/^['"]use client['"]\s*;\s*\n/);
13
13
  if (useClientMatch) {
14
14
  // Insert after 'use client' directive
15
- var afterUseClient = useClientMatch[0];
16
- return "".concat(afterUseClient).concat(importString).concat(source.slice(afterUseClient.length));
15
+ const afterUseClient = useClientMatch[0];
16
+ return `${afterUseClient}${importString}${source.slice(afterUseClient.length)}`;
17
17
  }
18
18
 
19
19
  // Insert at the beginning
20
- return "".concat(importString).concat(source);
20
+ return `${importString}${source}`;
21
21
  }
@@ -1,7 +1,3 @@
1
- import _createForOfIteratorHelper from "@babel/runtime/helpers/esm/createForOfIteratorHelper";
2
- import _regenerator from "@babel/runtime/helpers/esm/regenerator";
3
- import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
4
- import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
5
1
  // webpack does not like node: imports
6
2
  // eslint-disable-next-line n/prefer-node-protocol
7
3
  import { readFile } from 'fs/promises';
@@ -30,214 +26,168 @@ import { replacePrecomputeValue } from "../loadPrecomputedCodeHighlighter/replac
30
26
  *
31
27
  * Automatically skips processing if skipPrecompute: true is set.
32
28
  */
33
- export function loadPrecomputedCodeHighlighterClient(_x) {
34
- return _loadPrecomputedCodeHighlighterClient.apply(this, arguments);
35
- }
29
+ export async function loadPrecomputedCodeHighlighterClient(source) {
30
+ const callback = this.async();
31
+ this.cacheable();
32
+ try {
33
+ // Convert the filesystem path to a file:// URL for cross-platform compatibility
34
+ // pathToFileURL handles Windows drive letters correctly (e.g., C:\... → file:///C:/...)
35
+ const resourceFileUrl = pathToFileURL(this.resourcePath).toString();
36
36
 
37
- // Default export for webpack loader
38
- function _loadPrecomputedCodeHighlighterClient() {
39
- _loadPrecomputedCodeHighlighterClient = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(source) {
40
- var _this = this;
41
- var callback, resourceFileUrl, demoCall, allDependencies, allExternalsArray, clientDir, indexPath, indexFileUrl, indexDemoCall, indexSource, resolvedVariantMap, loadSource, variantPromises, variantResults, _iterator, _step, result, allExternals, runtimeExternals, _generateResolvedExte, importLines, resolvedExternals, precomputeData, modifiedSource, _t2, _t3;
42
- return _regenerator().w(function (_context2) {
43
- while (1) switch (_context2.p = _context2.n) {
44
- case 0:
45
- callback = this.async();
46
- this.cacheable();
47
- _context2.p = 1;
48
- // Convert the filesystem path to a file:// URL for cross-platform compatibility
49
- // pathToFileURL handles Windows drive letters correctly (e.g., C:\... file:///C:/...)
50
- resourceFileUrl = pathToFileURL(this.resourcePath).toString(); // Parse the source to find a single createDemoClient call
51
- // Use metadataOnly mode since client calls only have (url, options?) arguments
52
- _context2.n = 2;
53
- return parseCreateFactoryCall(source, resourceFileUrl, {
54
- metadataOnly: true
55
- });
56
- case 2:
57
- demoCall = _context2.v;
58
- if (demoCall) {
59
- _context2.n = 3;
60
- break;
61
- }
62
- callback(null, source);
63
- return _context2.a(2);
64
- case 3:
65
- if (demoCall.functionName.includes('Client')) {
66
- _context2.n = 4;
67
- break;
68
- }
69
- callback(null, source);
70
- return _context2.a(2);
71
- case 4:
72
- if (!demoCall.options.skipPrecompute) {
73
- _context2.n = 5;
74
- break;
75
- }
76
- callback(null, source);
77
- return _context2.a(2);
78
- case 5:
79
- // Load variant data for all variants to collect externals
80
- allDependencies = [];
81
- allExternalsArray = []; // For client files, we need to read the corresponding index.ts to get variants
82
- // The client.ts and index.ts should be in the same directory
83
- clientDir = path.dirname(this.resourcePath);
84
- indexPath = path.join(clientDir, 'index.ts'); // Convert to file:// URL for parseCreateFactoryCall
85
- indexFileUrl = pathToFileURL(indexPath).toString(); // Read and parse the index.ts file to get variant information
86
- indexDemoCall = null;
87
- _context2.p = 6;
88
- _context2.n = 7;
89
- return readFile(indexPath, 'utf-8');
90
- case 7:
91
- indexSource = _context2.v;
92
- // Add index.ts as a dependency for hot reloading
93
- this.addDependency(indexPath);
94
- _context2.n = 8;
95
- return parseCreateFactoryCall(indexSource, indexFileUrl);
96
- case 8:
97
- indexDemoCall = _context2.v;
98
- _context2.n = 10;
99
- break;
100
- case 9:
101
- _context2.p = 9;
102
- _t2 = _context2.v;
103
- // If we can't read index.ts, we can't determine variants
104
- console.warn("Could not read ".concat(indexPath, " to determine variants for client: ").concat(_t2));
105
- callback(null, source);
106
- return _context2.a(2);
107
- case 10:
108
- if (!(!indexDemoCall || !indexDemoCall.variants)) {
109
- _context2.n = 11;
110
- break;
111
- }
112
- console.warn("No createDemo call or variants found in ".concat(indexPath, " for client processing"));
113
- callback(null, source);
114
- return _context2.a(2);
115
- case 11:
116
- _context2.n = 12;
117
- return resolveVariantPathsWithFs(indexDemoCall.variants);
118
- case 12:
119
- resolvedVariantMap = _context2.v;
120
- // Create loader functions
121
- loadSource = createLoadServerSource({
122
- includeDependencies: true,
123
- storeAt: 'flat' // TODO: choose whichever is most performant as it shouldn't affect the output
124
- }); // Process variants in parallel to collect externals
125
- variantPromises = Array.from(resolvedVariantMap.entries()).map(/*#__PURE__*/function () {
126
- var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(_ref) {
127
- var _indexDemoCall$namedE;
128
- var _ref3, variantName, fileUrl, namedExport, variant, _getFileNameFromUrl, fileName, _yield$loadCodeVarian, dependencies, externals, _t;
129
- return _regenerator().w(function (_context) {
130
- while (1) switch (_context.p = _context.n) {
131
- case 0:
132
- _ref3 = _slicedToArray(_ref, 2), variantName = _ref3[0], fileUrl = _ref3[1];
133
- namedExport = (_indexDemoCall$namedE = indexDemoCall.namedExports) == null ? void 0 : _indexDemoCall$namedE[variantName];
134
- variant = fileUrl;
135
- if (!namedExport) {
136
- _context.n = 2;
137
- break;
138
- }
139
- _getFileNameFromUrl = getFileNameFromUrl(variant), fileName = _getFileNameFromUrl.fileName;
140
- if (fileName) {
141
- _context.n = 1;
142
- break;
143
- }
144
- throw new Error("Cannot determine fileName from URL \"".concat(variant, "\" for variant \"").concat(variantName, "\". ") + "Please ensure the URL has a valid file extension.");
145
- case 1:
146
- variant = {
147
- url: fileUrl,
148
- fileName: fileName,
149
- namedExport: namedExport
150
- };
151
- case 2:
152
- _context.p = 2;
153
- _context.n = 3;
154
- return loadCodeVariant(fileUrl,
155
- // URL for the variant entry point (already includes file://)
156
- variantName, variant, {
157
- loadSource: loadSource,
158
- // For loading source files and dependencies
159
- maxDepth: 5,
160
- disableParsing: true,
161
- disableTransforms: true
162
- });
163
- case 3:
164
- _yield$loadCodeVarian = _context.v;
165
- dependencies = _yield$loadCodeVarian.dependencies;
166
- externals = _yield$loadCodeVarian.externals;
167
- return _context.a(2, {
168
- variantName: variantName,
169
- dependencies: dependencies,
170
- // All files that were loaded
171
- externals: externals // Combined externals from all loaded files
172
- });
173
- case 4:
174
- _context.p = 4;
175
- _t = _context.v;
176
- throw new Error("Failed to load variant ".concat(variantName, " from ").concat(fileUrl, ": ").concat(_t));
177
- case 5:
178
- return _context.a(2);
179
- }
180
- }, _callee, null, [[2, 4]]);
181
- }));
182
- return function (_x2) {
183
- return _ref2.apply(this, arguments);
184
- };
185
- }());
186
- _context2.n = 13;
187
- return Promise.all(variantPromises);
188
- case 13:
189
- variantResults = _context2.v;
190
- // Process results and collect dependencies and externals
191
- _iterator = _createForOfIteratorHelper(variantResults);
192
- try {
193
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
194
- result = _step.value;
195
- if (result) {
196
- result.dependencies.forEach(function (file) {
197
- allDependencies.push(file);
198
- });
199
- // Collect externals for proper merging
200
- allExternalsArray.push(result.externals);
201
- }
202
- }
203
-
204
- // Properly merge externals from all variants
205
- } catch (err) {
206
- _iterator.e(err);
207
- } finally {
208
- _iterator.f();
209
- }
210
- allExternals = mergeExternals(allExternalsArray); // Filter out type-only imports since they don't exist at runtime
211
- runtimeExternals = filterRuntimeExternals(allExternals); // Generate import statements and resolved externals object
212
- _generateResolvedExte = generateResolvedExternals(runtimeExternals), importLines = _generateResolvedExte.imports, resolvedExternals = _generateResolvedExte.resolvedExternals; // Add externals argument to the createDemoClient call using replacePrecomputeValue first
213
- // (before injecting imports, so the original positions are still valid)
214
- // with passPrecomputeAsIs enabled so externals are passed as resolved objects
215
- precomputeData = {
216
- externals: resolvedExternals
217
- };
218
- modifiedSource = replacePrecomputeValue(source, precomputeData, demoCall, {
219
- passPrecomputeAsIs: true
220
- }); // Then inject imports at the top of the file (after 'use client' if present)
221
- modifiedSource = injectImportsIntoSource(modifiedSource, importLines);
222
-
223
- // Add all dependencies to webpack's watch list
224
- allDependencies.forEach(function (dep) {
225
- // Convert file:// URLs to proper file system paths for webpack's dependency tracking
226
- // Using fileURLToPath handles Windows drive letters correctly (e.g., file:///C:/... → C:\...)
227
- _this.addDependency(dep.startsWith('file://') ? fileURLToPath(dep) : dep);
228
- });
229
- callback(null, modifiedSource);
230
- _context2.n = 15;
231
- break;
232
- case 14:
233
- _context2.p = 14;
234
- _t3 = _context2.v;
235
- callback(_t3 instanceof Error ? _t3 : new Error(String(_t3)));
236
- case 15:
237
- return _context2.a(2);
37
+ // Parse the source to find a single createDemoClient call
38
+ // Use metadataOnly mode since client calls only have (url, options?) arguments
39
+ const demoCall = await parseCreateFactoryCall(source, resourceFileUrl, {
40
+ metadataOnly: true
41
+ });
42
+
43
+ // If no createDemoClient call found, return the source unchanged
44
+ if (!demoCall) {
45
+ callback(null, source);
46
+ return;
47
+ }
48
+
49
+ // Only process client factory calls (functions with "Client" in the name)
50
+ if (!demoCall.functionName.includes('Client')) {
51
+ callback(null, source);
52
+ return;
53
+ }
54
+
55
+ // If skipPrecompute is true, return the source unchanged
56
+ if (demoCall.options.skipPrecompute) {
57
+ callback(null, source);
58
+ return;
59
+ }
60
+
61
+ // Load variant data for all variants to collect externals
62
+ const allDependencies = [];
63
+ const allExternalsArray = [];
64
+
65
+ // For client files, we need to read the corresponding index.ts to get variants
66
+ // The client.ts and index.ts should be in the same directory
67
+ const clientDir = path.dirname(this.resourcePath);
68
+ const indexPath = path.join(clientDir, 'index.ts');
69
+ // Convert to file:// URL for parseCreateFactoryCall
70
+ const indexFileUrl = pathToFileURL(indexPath).toString();
71
+
72
+ // Read and parse the index.ts file to get variant information
73
+ let indexDemoCall = null;
74
+ try {
75
+ const indexSource = await readFile(indexPath, 'utf-8');
76
+
77
+ // Add index.ts as a dependency for hot reloading
78
+ this.addDependency(indexPath);
79
+ indexDemoCall = await parseCreateFactoryCall(indexSource, indexFileUrl);
80
+ } catch (error) {
81
+ // If we can't read index.ts, we can't determine variants
82
+ console.warn(`Could not read ${indexPath} to determine variants for client: ${error}`);
83
+ callback(null, source);
84
+ return;
85
+ }
86
+ if (!indexDemoCall || !indexDemoCall.variants) {
87
+ console.warn(`No createDemo call or variants found in ${indexPath} for client processing`);
88
+ callback(null, source);
89
+ return;
90
+ }
91
+
92
+ // Use variants from the index.ts file
93
+ const resolvedVariantMap = await resolveVariantPathsWithFs(indexDemoCall.variants);
94
+
95
+ // Create loader functions
96
+ const loadSource = createLoadServerSource({
97
+ includeDependencies: true,
98
+ storeAt: 'flat' // TODO: choose whichever is most performant as it shouldn't affect the output
99
+ });
100
+
101
+ // Process variants in parallel to collect externals
102
+ const variantPromises = Array.from(resolvedVariantMap.entries()).map(async ([variantName, fileUrl]) => {
103
+ const namedExport = indexDemoCall.namedExports?.[variantName];
104
+ let variant = fileUrl;
105
+ if (namedExport) {
106
+ const {
107
+ fileName
108
+ } = getFileNameFromUrl(variant);
109
+ if (!fileName) {
110
+ throw new Error(`Cannot determine fileName from URL "${variant}" for variant "${variantName}". ` + `Please ensure the URL has a valid file extension.`);
111
+ }
112
+ variant = {
113
+ url: fileUrl,
114
+ fileName,
115
+ namedExport
116
+ };
238
117
  }
239
- }, _callee2, this, [[6, 9], [1, 14]]);
240
- }));
241
- return _loadPrecomputedCodeHighlighterClient.apply(this, arguments);
118
+ try {
119
+ // Use loadCodeVariant to collect all dependencies and externals
120
+ const {
121
+ dependencies,
122
+ externals
123
+ } = await loadCodeVariant(fileUrl,
124
+ // URL for the variant entry point (already includes file://)
125
+ variantName, variant, {
126
+ loadSource,
127
+ // For loading source files and dependencies
128
+ maxDepth: 5,
129
+ disableParsing: true,
130
+ disableTransforms: true
131
+ });
132
+ return {
133
+ variantName,
134
+ dependencies,
135
+ // All files that were loaded
136
+ externals // Combined externals from all loaded files
137
+ };
138
+ } catch (error) {
139
+ throw new Error(`Failed to load variant ${variantName} from ${fileUrl}: ${error}`);
140
+ }
141
+ });
142
+ const variantResults = await Promise.all(variantPromises);
143
+
144
+ // Process results and collect dependencies and externals
145
+ for (const result of variantResults) {
146
+ if (result) {
147
+ result.dependencies.forEach(file => {
148
+ allDependencies.push(file);
149
+ });
150
+ // Collect externals for proper merging
151
+ allExternalsArray.push(result.externals);
152
+ }
153
+ }
154
+
155
+ // Properly merge externals from all variants
156
+ const allExternals = mergeExternals(allExternalsArray);
157
+
158
+ // Filter out type-only imports since they don't exist at runtime
159
+ const runtimeExternals = filterRuntimeExternals(allExternals);
160
+
161
+ // Generate import statements and resolved externals object
162
+ const {
163
+ imports: importLines,
164
+ resolvedExternals
165
+ } = generateResolvedExternals(runtimeExternals);
166
+
167
+ // Add externals argument to the createDemoClient call using replacePrecomputeValue first
168
+ // (before injecting imports, so the original positions are still valid)
169
+ // with passPrecomputeAsIs enabled so externals are passed as resolved objects
170
+ const precomputeData = {
171
+ externals: resolvedExternals
172
+ };
173
+ let modifiedSource = replacePrecomputeValue(source, precomputeData, demoCall, {
174
+ passPrecomputeAsIs: true
175
+ });
176
+
177
+ // Then inject imports at the top of the file (after 'use client' if present)
178
+ modifiedSource = injectImportsIntoSource(modifiedSource, importLines);
179
+
180
+ // Add all dependencies to webpack's watch list
181
+ allDependencies.forEach(dep => {
182
+ // Convert file:// URLs to proper file system paths for webpack's dependency tracking
183
+ // Using fileURLToPath handles Windows drive letters correctly (e.g., file:///C:/... → C:\...)
184
+ this.addDependency(dep.startsWith('file://') ? fileURLToPath(dep) : dep);
185
+ });
186
+ callback(null, modifiedSource);
187
+ } catch (error) {
188
+ callback(error instanceof Error ? error : new Error(String(error)));
189
+ }
242
190
  }
191
+
192
+ // Default export for webpack loader
243
193
  export default loadPrecomputedCodeHighlighterClient;