@pie-element/cli 0.1.3-next.20261002220849 → 0.1.3-next.20261005184705

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 (113) hide show
  1. package/README.md +4 -138
  2. package/dist/commands/verify/controllers.js +1 -6
  3. package/dist/commands/verify/controllers.js.map +1 -1
  4. package/dist/lib/{upstream/sync-demo-metadata.js → demo/demo-metadata.js} +1 -1
  5. package/dist/lib/demo/demo-metadata.js.map +1 -0
  6. package/dist/utils/package-json.d.ts +0 -1
  7. package/dist/utils/package-json.js +0 -19
  8. package/dist/utils/package-json.js.map +1 -1
  9. package/package.json +4 -7
  10. package/dist/commands/packages/create-controllers.d.ts +0 -12
  11. package/dist/commands/packages/create-controllers.js +0 -103
  12. package/dist/commands/packages/create-controllers.js.map +0 -1
  13. package/dist/commands/packages/create-lib-react.d.ts +0 -16
  14. package/dist/commands/packages/create-lib-react.js +0 -226
  15. package/dist/commands/packages/create-lib-react.js.map +0 -1
  16. package/dist/commands/packages/create-react-elements.d.ts +0 -15
  17. package/dist/commands/packages/create-react-elements.js +0 -239
  18. package/dist/commands/packages/create-react-elements.js.map +0 -1
  19. package/dist/commands/packages/init-synced-elements.d.ts +0 -15
  20. package/dist/commands/packages/init-synced-elements.js +0 -202
  21. package/dist/commands/packages/init-synced-elements.js.map +0 -1
  22. package/dist/commands/upstream/analyze-esm.d.ts +0 -58
  23. package/dist/commands/upstream/analyze-esm.js +0 -1452
  24. package/dist/commands/upstream/analyze-esm.js.map +0 -1
  25. package/dist/commands/upstream/check.d.ts +0 -14
  26. package/dist/commands/upstream/check.js +0 -165
  27. package/dist/commands/upstream/check.js.map +0 -1
  28. package/dist/commands/upstream/deps.d.ts +0 -14
  29. package/dist/commands/upstream/deps.js +0 -174
  30. package/dist/commands/upstream/deps.js.map +0 -1
  31. package/dist/commands/upstream/sync.d.ts +0 -34
  32. package/dist/commands/upstream/sync.js +0 -886
  33. package/dist/commands/upstream/sync.js.map +0 -1
  34. package/dist/commands/upstream/track.d.ts +0 -14
  35. package/dist/commands/upstream/track.js +0 -115
  36. package/dist/commands/upstream/track.js.map +0 -1
  37. package/dist/commands/upstream/update.d.ts +0 -14
  38. package/dist/commands/upstream/update.js +0 -128
  39. package/dist/commands/upstream/update.js.map +0 -1
  40. package/dist/lib/upstream/editor-runtime.d.ts +0 -15
  41. package/dist/lib/upstream/editor-runtime.js +0 -55
  42. package/dist/lib/upstream/editor-runtime.js.map +0 -1
  43. package/dist/lib/upstream/repo-utils.d.ts +0 -8
  44. package/dist/lib/upstream/repo-utils.js +0 -10
  45. package/dist/lib/upstream/repo-utils.js.map +0 -1
  46. package/dist/lib/upstream/sync-compatibility.d.ts +0 -20
  47. package/dist/lib/upstream/sync-compatibility.js +0 -39
  48. package/dist/lib/upstream/sync-compatibility.js.map +0 -1
  49. package/dist/lib/upstream/sync-constants.d.ts +0 -86
  50. package/dist/lib/upstream/sync-constants.js +0 -130
  51. package/dist/lib/upstream/sync-constants.js.map +0 -1
  52. package/dist/lib/upstream/sync-controllers-strategy.d.ts +0 -17
  53. package/dist/lib/upstream/sync-controllers-strategy.js +0 -253
  54. package/dist/lib/upstream/sync-controllers-strategy.js.map +0 -1
  55. package/dist/lib/upstream/sync-demo-metadata.js.map +0 -1
  56. package/dist/lib/upstream/sync-entry-discovery.d.ts +0 -3
  57. package/dist/lib/upstream/sync-entry-discovery.js +0 -23
  58. package/dist/lib/upstream/sync-entry-discovery.js.map +0 -1
  59. package/dist/lib/upstream/sync-externals.d.ts +0 -29
  60. package/dist/lib/upstream/sync-externals.js +0 -180
  61. package/dist/lib/upstream/sync-externals.js.map +0 -1
  62. package/dist/lib/upstream/sync-filesystem.d.ts +0 -20
  63. package/dist/lib/upstream/sync-filesystem.js +0 -64
  64. package/dist/lib/upstream/sync-filesystem.js.map +0 -1
  65. package/dist/lib/upstream/sync-imports.d.ts +0 -297
  66. package/dist/lib/upstream/sync-imports.js +0 -1318
  67. package/dist/lib/upstream/sync-imports.js.map +0 -1
  68. package/dist/lib/upstream/sync-package-json.d.ts +0 -8
  69. package/dist/lib/upstream/sync-package-json.js +0 -15
  70. package/dist/lib/upstream/sync-package-json.js.map +0 -1
  71. package/dist/lib/upstream/sync-package-manager.d.ts +0 -66
  72. package/dist/lib/upstream/sync-package-manager.js +0 -959
  73. package/dist/lib/upstream/sync-package-manager.js.map +0 -1
  74. package/dist/lib/upstream/sync-pielib-strategy.d.ts +0 -27
  75. package/dist/lib/upstream/sync-pielib-strategy.js +0 -463
  76. package/dist/lib/upstream/sync-pielib-strategy.js.map +0 -1
  77. package/dist/lib/upstream/sync-presets.d.ts +0 -57
  78. package/dist/lib/upstream/sync-presets.js +0 -262
  79. package/dist/lib/upstream/sync-presets.js.map +0 -1
  80. package/dist/lib/upstream/sync-react-strategy.d.ts +0 -59
  81. package/dist/lib/upstream/sync-react-strategy.js +0 -941
  82. package/dist/lib/upstream/sync-react-strategy.js.map +0 -1
  83. package/dist/lib/upstream/sync-source-edit.d.ts +0 -14
  84. package/dist/lib/upstream/sync-source-edit.js +0 -89
  85. package/dist/lib/upstream/sync-source-edit.js.map +0 -1
  86. package/dist/lib/upstream/sync-source-tree.d.ts +0 -22
  87. package/dist/lib/upstream/sync-source-tree.js +0 -101
  88. package/dist/lib/upstream/sync-source-tree.js.map +0 -1
  89. package/dist/lib/upstream/sync-strategy.d.ts +0 -49
  90. package/dist/lib/upstream/sync-strategy.js +0 -2
  91. package/dist/lib/upstream/sync-strategy.js.map +0 -1
  92. package/dist/lib/upstream/sync-summary.d.ts +0 -19
  93. package/dist/lib/upstream/sync-summary.js +0 -157
  94. package/dist/lib/upstream/sync-summary.js.map +0 -1
  95. package/dist/lib/upstream/sync-transforms.d.ts +0 -62
  96. package/dist/lib/upstream/sync-transforms.js +0 -105
  97. package/dist/lib/upstream/sync-transforms.js.map +0 -1
  98. package/dist/lib/upstream/sync-vite-config.d.ts +0 -21
  99. package/dist/lib/upstream/sync-vite-config.js +0 -239
  100. package/dist/lib/upstream/sync-vite-config.js.map +0 -1
  101. package/dist/lib/upstream/workspace-pie-lib.d.ts +0 -2
  102. package/dist/lib/upstream/workspace-pie-lib.js +0 -29
  103. package/dist/lib/upstream/workspace-pie-lib.js.map +0 -1
  104. package/dist/utils/compatibility.d.ts +0 -126
  105. package/dist/utils/compatibility.js +0 -151
  106. package/dist/utils/compatibility.js.map +0 -1
  107. package/dist/utils/conversion.d.ts +0 -19
  108. package/dist/utils/conversion.js +0 -102
  109. package/dist/utils/conversion.js.map +0 -1
  110. package/dist/utils/git.d.ts +0 -12
  111. package/dist/utils/git.js +0 -58
  112. package/dist/utils/git.js.map +0 -1
  113. /package/dist/lib/{upstream/sync-demo-metadata.d.ts → demo/demo-metadata.d.ts} +0 -0
@@ -1,1452 +0,0 @@
1
- import { Command, Flags } from '@oclif/core';
2
- import { Logger } from '../../utils/logger.js';
3
- import { loadPackageJson } from '../../utils/package-json.js';
4
- import { existsSync } from 'node:fs';
5
- import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
6
- import { join } from 'node:path';
7
- import { createTrackedCompatibilityReport, deriveStaticBrowserEsmReport, } from '../../utils/compatibility.js';
8
- import { assertReposExist } from '../../lib/upstream/repo-utils.js';
9
- // PIE elements that are actively used in pie-elements-ng
10
- // Only these elements will be analyzed
11
- const ACTIVE_ELEMENTS = [
12
- 'categorize',
13
- 'charting',
14
- 'complex-rubric',
15
- 'drag-in-the-blank',
16
- 'drawing-response',
17
- 'ebsr',
18
- 'explicit-constructed-response',
19
- 'extended-text-entry',
20
- 'fraction-model',
21
- 'graphing',
22
- 'graphing-solution-set',
23
- 'hotspot',
24
- 'image-cloze-association',
25
- 'inline-dropdown',
26
- 'likert',
27
- 'match',
28
- 'match-list',
29
- 'math-inline',
30
- 'math-templated',
31
- 'matrix',
32
- 'multi-trait-rubric',
33
- 'multiple-choice',
34
- 'number-line',
35
- 'passage',
36
- 'placement-ordering',
37
- 'rubric',
38
- 'select-text',
39
- ];
40
- // Known ESM blockers - packages that prevent ESM builds
41
- const ESM_BLOCKERS = [
42
- // Old Slate editor (v0.36.x) - not ESM compatible
43
- { pattern: /^slate@0\.[0-4]\d/, reason: 'Slate v0.x is not ESM compatible' },
44
- { pattern: /^slate-/, reason: 'Slate v0.x plugins are not ESM compatible' },
45
- // Known CommonJS-only packages (add more as discovered)
46
- { pattern: /^enzyme/, reason: 'Enzyme is not ESM compatible' },
47
- ];
48
- export default class AnalyzeEsm extends Command {
49
- static description = 'Analyze PIE elements for ESM compatibility';
50
- static examples = [
51
- '<%= config.bin %> <%= command.id %>',
52
- '<%= config.bin %> <%= command.id %> --verbose',
53
- '<%= config.bin %> <%= command.id %> --output=./.compatibility/custom-report.json',
54
- ];
55
- static flags = {
56
- verbose: Flags.boolean({
57
- char: 'v',
58
- description: 'Show detailed analysis output',
59
- default: false,
60
- }),
61
- 'pie-elements': Flags.string({
62
- description: 'Path to pie-elements repo',
63
- default: '../pie-elements',
64
- }),
65
- 'pie-lib': Flags.string({
66
- description: 'Path to pie-lib repo',
67
- default: '../pie-lib',
68
- }),
69
- output: Flags.string({
70
- description: 'Output JSON file path',
71
- default: './.compatibility/report.json',
72
- }),
73
- 'include-dev-deps': Flags.boolean({
74
- description: 'Include devDependencies in blocker analysis (usually unnecessary since pie-elements-ng does not sync upstream tests)',
75
- default: false,
76
- }),
77
- 'validate-esm-player': Flags.boolean({
78
- description: 'Validate ESM player compatibility (package.json structure, exports).',
79
- default: true,
80
- allowNo: true,
81
- }),
82
- 'runtime-cdn-base-url': Flags.string({
83
- description: 'CDN base URL to use for runtime probes (e.g. https://esm.sh)',
84
- default: 'https://esm.sh',
85
- }),
86
- 'runtime-local-pie-elements-path': Flags.string({
87
- description: 'Path to sibling pie-elements repo used for local PIE resolution during probes.',
88
- default: '../pie-elements',
89
- }),
90
- 'runtime-local-pie-lib-path': Flags.string({
91
- description: 'Path to sibling pie-lib repo used for local PIE resolution during probes.',
92
- default: '../pie-lib',
93
- }),
94
- 'runtime-timeout-ms': Flags.integer({
95
- description: 'Timeout for each runtime probe request (ms)',
96
- default: 6000,
97
- }),
98
- 'runtime-concurrency': Flags.integer({
99
- description: 'Max concurrent runtime probes',
100
- default: 8,
101
- }),
102
- 'runtime-max-depth': Flags.integer({
103
- description: 'Max import graph depth for the deep runtime probe',
104
- default: 6,
105
- }),
106
- 'runtime-max-modules': Flags.integer({
107
- description: 'Max total modules fetched per element for the deep runtime probe',
108
- default: 250,
109
- }),
110
- 'runtime-cache-file': Flags.string({
111
- description: 'Optional JSON cache file path for runtime probe results (speeds up repeated runs)',
112
- default: './.cache/analyze-esm.runtime-cache.json',
113
- }),
114
- };
115
- logger = new Logger();
116
- async run() {
117
- const { flags } = await this.parse(AnalyzeEsm);
118
- this.logger = new Logger(flags.verbose);
119
- if (flags.verbose) {
120
- this.logger.section('🔍 Analyzing ESM Compatibility');
121
- this.logger.info(` PIE Elements: ${flags['pie-elements']}`);
122
- this.logger.info(` PIE Lib: ${flags['pie-lib']}\n`);
123
- }
124
- // Verify repos exist
125
- try {
126
- assertReposExist([
127
- { label: 'pie-elements', path: flags['pie-elements'] },
128
- { label: 'pie-lib', path: flags['pie-lib'] },
129
- ]);
130
- }
131
- catch (error) {
132
- this.error(error instanceof Error ? error.message : String(error));
133
- }
134
- const report = await this.analyzeCompatibility(flags['pie-elements'], flags['pie-lib'], flags.verbose, flags['include-dev-deps'], flags['validate-esm-player'], flags['runtime-cdn-base-url'], flags['runtime-local-pie-elements-path'], flags['runtime-local-pie-lib-path'], flags['runtime-timeout-ms'], flags['runtime-concurrency'], flags['runtime-max-depth'], flags['runtime-max-modules'], flags['runtime-cache-file']);
135
- const staticBrowserEsmReport = await deriveStaticBrowserEsmReport(process.cwd());
136
- report.browserEsmReady = staticBrowserEsmReport.browserEsmReady;
137
- report.browserEsmUnsupported = staticBrowserEsmReport.browserEsmUnsupported;
138
- // Save JSON report
139
- const outputDir = join(flags.output, '..');
140
- await mkdir(outputDir, { recursive: true });
141
- await writeFile(flags.output, `${JSON.stringify(createTrackedCompatibilityReport(report), null, 2)}\n`, 'utf-8');
142
- // Print summary
143
- this.printReport(report, flags.output);
144
- }
145
- async analyzeCompatibility(pieElementsPath, pieLibPath, verbose, includeDevDeps, validateEsmPlayer, runtimeCdnBaseUrl, runtimeLocalPieElementsPath, runtimeLocalPieLibPath, runtimeTimeoutMs, runtimeConcurrency, runtimeMaxDepth, runtimeMaxModules, runtimeCacheFile) {
146
- if (!verbose) {
147
- this.logger.progressStart('Analyzing ESM compatibility...');
148
- }
149
- const report = {
150
- elements: [],
151
- pieLibPackages: [],
152
- blockedElements: {},
153
- esmPlayerReady: [],
154
- esmValidation: {},
155
- esmPlayerValidationEnabled: validateEsmPlayer,
156
- esmRuntimeValidationEnabled: true,
157
- esmRuntimeCdnBaseUrl: runtimeCdnBaseUrl,
158
- esmRuntimeValidation: {},
159
- elementDetails: {},
160
- pieLibDetails: {},
161
- lastAnalyzed: new Date().toISOString(),
162
- summary: {
163
- totalElements: 0,
164
- compatibleElements: 0,
165
- blockedElements: 0,
166
- esmPlayerReady: 0,
167
- esmRuntimeReady: 0,
168
- totalPieLibPackages: 0,
169
- compatiblePieLibPackages: 0,
170
- },
171
- };
172
- // Cache for pie-lib compatibility checks
173
- const pieLibCache = new Map();
174
- // Get all element packages
175
- const elementsDir = join(pieElementsPath, 'packages');
176
- const allElements = await readdir(elementsDir);
177
- // Filter to only active elements used in pie-elements-ng
178
- const elements = allElements.filter((name) => ACTIVE_ELEMENTS.includes(name));
179
- report.summary.totalElements = elements.length;
180
- if (verbose) {
181
- this.logger.info(`📊 Analyzing ${elements.length} elements...\n`);
182
- }
183
- // Track which elements use which pie-lib packages
184
- const pieLibUsage = new Map();
185
- // Analyze each element
186
- for (const element of elements.sort()) {
187
- const result = await this.checkElementCompatibility(element, pieElementsPath, pieLibPath, pieLibCache, verbose, includeDevDeps);
188
- // Check subdirectories separately
189
- const srcCheck = await this.checkSubdirectoryCompatibility(element, 'src', pieElementsPath, pieLibPath, pieLibCache, verbose, includeDevDeps);
190
- const configureCheck = await this.checkSubdirectoryCompatibility(element, 'configure', pieElementsPath, pieLibPath, pieLibCache, verbose, includeDevDeps);
191
- const controllerCheck = await this.checkSubdirectoryCompatibility(element, 'controller', pieElementsPath, pieLibPath, pieLibCache, verbose, includeDevDeps);
192
- // Add subdirectory results to element details
193
- if (srcCheck !== null) {
194
- result.studentUI = srcCheck;
195
- }
196
- if (configureCheck !== null) {
197
- result.configure = configureCheck;
198
- }
199
- if (controllerCheck !== null) {
200
- result.controller = controllerCheck;
201
- }
202
- report.elementDetails[element] = result;
203
- if (result.compatible) {
204
- report.elements.push(element);
205
- report.summary.compatibleElements++;
206
- // Track pie-lib usage (including transitive deps)
207
- // For example: if element uses text-select, and text-select uses style-utils,
208
- // we need to sync both text-select AND style-utils
209
- const allPieLibDeps = await this.collectAllTransitivePieLibDeps(result.pieLibDeps, pieLibPath, includeDevDeps);
210
- for (const pieLibDep of allPieLibDeps) {
211
- if (!pieLibUsage.has(pieLibDep)) {
212
- pieLibUsage.set(pieLibDep, new Set());
213
- }
214
- const usageSet = pieLibUsage.get(pieLibDep);
215
- if (usageSet) {
216
- usageSet.add(element);
217
- }
218
- }
219
- }
220
- else {
221
- report.blockedElements[element] = result.blockers;
222
- report.summary.blockedElements++;
223
- }
224
- }
225
- // Second pass: Check element-to-element dependencies
226
- // Elements can only be compatible if all their element dependencies are also compatible
227
- if (verbose) {
228
- this.logger.info('\n🔗 Checking element-to-element dependencies...\n');
229
- }
230
- let changed = true;
231
- while (changed) {
232
- changed = false;
233
- for (const element of elements) {
234
- const details = report.elementDetails[element];
235
- if (!details?.compatible)
236
- continue; // Already blocked, skip
237
- // Check if this element depends on any blocked elements
238
- for (const depElement of details.pieElementDeps) {
239
- const depDetails = report.elementDetails[depElement];
240
- if (!depDetails?.compatible) {
241
- // This element depends on a blocked element
242
- const blocker = `@pie-element/${depElement} - dependency is not ESM compatible`;
243
- details.blockers.push(blocker);
244
- details.compatible = false;
245
- // Move from compatible to blocked
246
- const idx = report.elements.indexOf(element);
247
- if (idx !== -1) {
248
- report.elements.splice(idx, 1);
249
- report.summary.compatibleElements--;
250
- }
251
- report.blockedElements[element] = details.blockers;
252
- report.summary.blockedElements++;
253
- changed = true;
254
- if (verbose) {
255
- this.logger.info(` ❌ ${element}: depends on blocked element ${depElement}`);
256
- }
257
- break;
258
- }
259
- }
260
- }
261
- }
262
- // Build pie-lib report
263
- for (const [pieLibPkg, usedBy] of pieLibUsage.entries()) {
264
- const check = pieLibCache.get(pieLibPkg);
265
- if (check?.compatible) {
266
- report.pieLibPackages.push(pieLibPkg);
267
- report.pieLibDetails[pieLibPkg] = {
268
- compatible: true,
269
- usedBy: Array.from(usedBy),
270
- blockers: [],
271
- };
272
- }
273
- else if (check) {
274
- report.pieLibDetails[pieLibPkg] = {
275
- compatible: false,
276
- usedBy: Array.from(usedBy),
277
- blockers: check.blockers,
278
- };
279
- }
280
- }
281
- report.summary.totalPieLibPackages = pieLibUsage.size;
282
- report.summary.compatiblePieLibPackages = report.pieLibPackages.length;
283
- // Identify student-UI-only elements (blocked overall but student UI is compatible)
284
- report.studentUIOnly = [];
285
- for (const element of elements) {
286
- const details = report.elementDetails[element];
287
- if (!details?.compatible && details?.studentUI?.compatible) {
288
- report.studentUIOnly.push(element);
289
- }
290
- }
291
- report.summary.studentUIOnlyElements = report.studentUIOnly.length;
292
- if (verbose && report.studentUIOnly.length > 0) {
293
- this.logger.info(`\n📱 Found ${report.studentUIOnly.length} elements with student-UI-only support:\n`);
294
- for (const element of report.studentUIOnly) {
295
- this.logger.info(` ${element}`);
296
- }
297
- }
298
- // ESM player validation (only for compatible elements)
299
- if (validateEsmPlayer) {
300
- if (verbose) {
301
- this.logger.info('\n🎮 Validating ESM player compatibility...\n');
302
- }
303
- for (const element of report.elements) {
304
- const validation = await this.validateEsmPlayerCompatibility(element, pieElementsPath, verbose);
305
- report.esmValidation[element] = validation;
306
- if (validation.compatible) {
307
- report.esmPlayerReady.push(element);
308
- report.summary.esmPlayerReady++;
309
- }
310
- }
311
- }
312
- // Runtime-ish CDN probes (production-like signal)
313
- const base = runtimeCdnBaseUrl.replace(/\/+$/, '');
314
- // Probe all CommonJS-free elements by default.
315
- // Rationale: "ESM ready in production" is primarily about whether the CDN can resolve
316
- // the package + transitives into browser-loadable ESM, not whether upstream package.json
317
- // has ideal exports metadata (which we often rewrite during sync).
318
- const elementsToProbe = report.elements.slice();
319
- const cache = await this.loadRuntimeCache(runtimeCacheFile);
320
- if (verbose) {
321
- this.logger.info(`\n🌐 Probing ESM runtime readiness via CDN (${elementsToProbe.length} elements, concurrency=${runtimeConcurrency})...\n`);
322
- this.logger.info(` CDN base: ${base}\n`);
323
- this.logger.info(` Mode: deep (maxDepth=${runtimeMaxDepth}, maxModules=${runtimeMaxModules})\n`);
324
- this.logger.info(` Local PIE resolution: enabled (pie-elements=${runtimeLocalPieElementsPath}, pie-lib=${runtimeLocalPieLibPath})\n`);
325
- }
326
- else {
327
- this.logger.info(`🌐 Probing ESM runtime readiness via CDN (${elementsToProbe.length} elements, concurrency=${runtimeConcurrency})...`);
328
- }
329
- const results = await this.probeElementsRuntime({
330
- elements: elementsToProbe,
331
- pieElementsPath,
332
- cdnBaseUrl: base,
333
- localPieEnabled: true,
334
- localPieElementsPath: runtimeLocalPieElementsPath,
335
- localPieLibPath: runtimeLocalPieLibPath,
336
- timeoutMs: runtimeTimeoutMs,
337
- concurrency: runtimeConcurrency,
338
- deep: true,
339
- maxDepth: runtimeMaxDepth,
340
- maxModules: runtimeMaxModules,
341
- cache,
342
- verbose,
343
- });
344
- let okCount = 0;
345
- for (const [element, result] of Object.entries(results)) {
346
- report.esmRuntimeValidation ??= {};
347
- report.esmRuntimeValidation[element] = result;
348
- if (result.compatible)
349
- okCount++;
350
- }
351
- report.summary.esmRuntimeReady = okCount;
352
- await this.saveRuntimeCache(runtimeCacheFile, cache);
353
- if (!verbose) {
354
- this.logger.info(` Runtime-ready: ${okCount}/${elementsToProbe.length}\n`);
355
- }
356
- if (!verbose) {
357
- this.logger.progressComplete();
358
- this.logger.info('');
359
- this.logger.success(`${report.summary.compatibleElements} elements compatible`);
360
- if (report.summary.blockedElements > 0) {
361
- this.logger.warn(`${report.summary.blockedElements} elements blocked`);
362
- }
363
- if (report.summary.compatiblePieLibPackages > 0) {
364
- this.logger.info(`${report.summary.compatiblePieLibPackages} @pie-lib packages compatible`);
365
- }
366
- if (report.summary.totalPieLibPackages - report.summary.compatiblePieLibPackages > 0) {
367
- this.logger.warn(`${report.summary.totalPieLibPackages - report.summary.compatiblePieLibPackages} @pie-lib packages blocked`);
368
- }
369
- this.logger.info('');
370
- this.logger.info('Run with --verbose to see detailed blocker information');
371
- this.logger.info('');
372
- }
373
- return report;
374
- }
375
- async loadRuntimeCache(filePath) {
376
- try {
377
- if (!existsSync(filePath))
378
- return {};
379
- const raw = await readFile(filePath, 'utf-8');
380
- return JSON.parse(raw);
381
- }
382
- catch {
383
- return {};
384
- }
385
- }
386
- async saveRuntimeCache(filePath, cache) {
387
- try {
388
- const dir = filePath.includes('/') ? filePath.split('/').slice(0, -1).join('/') : '.';
389
- if (dir && dir !== '.' && !existsSync(dir)) {
390
- await mkdir(dir, { recursive: true });
391
- }
392
- await writeFile(filePath, JSON.stringify(cache, null, 2), 'utf-8');
393
- }
394
- catch {
395
- // Best-effort cache only.
396
- }
397
- }
398
- async parseAsEsm(code) {
399
- try {
400
- const mod = (await import('es-module-lexer'));
401
- await mod.init;
402
- mod.parse(code);
403
- return true;
404
- }
405
- catch {
406
- // Fallback: very light heuristic (still useful signal for obvious non-JS responses).
407
- return typeof code === 'string' && code.length > 0;
408
- }
409
- }
410
- async getImportSpecifiers(code) {
411
- try {
412
- const mod = (await import('es-module-lexer'));
413
- await mod.init;
414
- const [imports] = mod.parse(code);
415
- const specs = [];
416
- for (const i of imports) {
417
- const spec = code.slice(i.s, i.e);
418
- if (spec)
419
- specs.push(spec);
420
- }
421
- return specs;
422
- }
423
- catch {
424
- return [];
425
- }
426
- }
427
- resolveImportUrl(fromUrl, spec, cdnBaseUrl) {
428
- if (!spec)
429
- return null;
430
- if (spec.startsWith('data:'))
431
- return null;
432
- if (spec.startsWith('http://') || spec.startsWith('https://'))
433
- return spec;
434
- if (spec.startsWith('//'))
435
- return `https:${spec}`;
436
- if (spec.startsWith('/'))
437
- return `${cdnBaseUrl.replace(/\/+$/, '')}${spec}`;
438
- if (spec.startsWith('./') || spec.startsWith('../'))
439
- return new URL(spec, fromUrl).toString();
440
- // Bare specifiers shouldn't typically appear in CDN output; best-effort map to base.
441
- return `${cdnBaseUrl.replace(/\/+$/, '')}/${spec}`;
442
- }
443
- isPiePackageSpecifier(spec) {
444
- return (spec.startsWith('@pie-lib/') ||
445
- spec.startsWith('@pie-element/') ||
446
- spec.startsWith('@pie-element/'));
447
- }
448
- tryResolvePieToLocalFile(spec, pieElementsPath, pieLibPath) {
449
- // Map PIE package specifiers to sibling upstream source trees.
450
- // Supports:
451
- // - @pie-lib/<name>[/subpath] -> <pie-lib>/packages/<name>/src/...
452
- // - @pie-element/<name>[/subpath] -> <pie-elements>/packages/<name>/src/... (and controller/configure sources)
453
- const [scope, name, ...rest] = spec.split('/');
454
- const subpath = rest.join('/');
455
- if (scope === '@pie-lib') {
456
- const base = join(pieLibPath, 'packages', name, 'src');
457
- return this.resolveLocalEntrypoint(base, subpath);
458
- }
459
- if (scope === '@pie-element') {
460
- // Special-case known subpaths that live outside src/ in upstream.
461
- if (subpath === 'controller' || subpath.startsWith('controller/')) {
462
- const controllerSub = subpath === 'controller' ? '' : subpath.replace(/^controller\//, '');
463
- const base = join(pieElementsPath, 'packages', name, 'controller', 'src');
464
- return this.resolveLocalEntrypoint(base, controllerSub);
465
- }
466
- if (subpath === 'configure' || subpath.startsWith('configure/')) {
467
- const cfgSub = subpath === 'configure' ? '' : subpath.replace(/^configure\//, '');
468
- const base = join(pieElementsPath, 'packages', name, 'configure', 'src');
469
- return this.resolveLocalEntrypoint(base, cfgSub);
470
- }
471
- const base = join(pieElementsPath, 'packages', name, 'src');
472
- return this.resolveLocalEntrypoint(base, subpath);
473
- }
474
- return null;
475
- }
476
- resolveLocalEntrypoint(srcBaseDir, subpath) {
477
- const candidates = [];
478
- if (!subpath) {
479
- candidates.push(join(srcBaseDir, 'index.ts'));
480
- candidates.push(join(srcBaseDir, 'index.tsx'));
481
- candidates.push(join(srcBaseDir, 'index.js'));
482
- candidates.push(join(srcBaseDir, 'index.jsx'));
483
- }
484
- else {
485
- const normalized = subpath.replace(/^\/+/, '');
486
- // common convention: <subpath>/index.*
487
- candidates.push(join(srcBaseDir, normalized, 'index.ts'));
488
- candidates.push(join(srcBaseDir, normalized, 'index.tsx'));
489
- candidates.push(join(srcBaseDir, normalized, 'index.js'));
490
- candidates.push(join(srcBaseDir, normalized, 'index.jsx'));
491
- // direct file
492
- candidates.push(join(srcBaseDir, `${normalized}.ts`));
493
- candidates.push(join(srcBaseDir, `${normalized}.tsx`));
494
- candidates.push(join(srcBaseDir, `${normalized}.js`));
495
- candidates.push(join(srcBaseDir, `${normalized}.jsx`));
496
- }
497
- for (const c of candidates) {
498
- if (existsSync(c))
499
- return `file://${c}`;
500
- }
501
- return null;
502
- }
503
- resolveLocalImport(fromFileUrl, spec) {
504
- // Supports extensionless TS/JS imports and index resolution.
505
- const fromPath = fromFileUrl.startsWith('file://')
506
- ? fromFileUrl.slice('file://'.length)
507
- : fromFileUrl;
508
- const baseDir = join(fromPath, '..');
509
- const tryPaths = [];
510
- const resolved = join(baseDir, spec);
511
- if (spec.endsWith('.ts') ||
512
- spec.endsWith('.tsx') ||
513
- spec.endsWith('.js') ||
514
- spec.endsWith('.jsx')) {
515
- tryPaths.push(resolved);
516
- }
517
- else {
518
- tryPaths.push(resolved + '.ts');
519
- tryPaths.push(resolved + '.tsx');
520
- tryPaths.push(resolved + '.js');
521
- tryPaths.push(resolved + '.jsx');
522
- tryPaths.push(join(resolved, 'index.ts'));
523
- tryPaths.push(join(resolved, 'index.tsx'));
524
- tryPaths.push(join(resolved, 'index.js'));
525
- tryPaths.push(join(resolved, 'index.jsx'));
526
- }
527
- for (const p of tryPaths) {
528
- if (existsSync(p))
529
- return `file://${p}`;
530
- }
531
- return null;
532
- }
533
- getTsImportSpecifiers(code) {
534
- // Minimal TS import extractor that handles import ... from "x" and export ... from "x".
535
- // We do not attempt full TS AST walking here to keep dependencies minimal.
536
- const specs = new Set();
537
- const re = /\b(?:import|export)\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g;
538
- for (const m of code.matchAll(re)) {
539
- if (m[1])
540
- specs.add(m[1]);
541
- }
542
- // dynamic import("x")
543
- const reDyn = /\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
544
- for (const m of code.matchAll(reDyn)) {
545
- if (m[1])
546
- specs.add(m[1]);
547
- }
548
- return Array.from(specs);
549
- }
550
- async deepProbeFromUrl(opts) {
551
- const { entryUrl, cdnBaseUrl, timeoutMs, maxDepth, maxModules, logPrefix, localPieEnabled, localPieElementsPath, localPieLibPath, } = opts;
552
- const visited = new Set();
553
- const errors = [];
554
- let fetched = 0;
555
- let fetchedOk = 0;
556
- let firstFailingUrl;
557
- let lastLogAt = 0;
558
- const queue = [{ url: entryUrl, depth: 0 }];
559
- while (queue.length > 0) {
560
- const next = queue.shift();
561
- if (!next)
562
- break;
563
- if (next.depth > maxDepth)
564
- continue;
565
- if (visited.has(next.url))
566
- continue;
567
- if (visited.size >= maxModules)
568
- break;
569
- visited.add(next.url);
570
- fetched++;
571
- // Periodic progress logging (deep probe can take a while)
572
- // Log at most every ~2s, and also on notable milestones.
573
- const now = Date.now();
574
- if (fetched === 1 || fetched % 50 === 0 || now - lastLogAt > 2000) {
575
- lastLogAt = now;
576
- this.logger.info(` ⏳ ${logPrefix}: fetched ${fetched}/${maxModules} modules (ok ${fetchedOk}), queue ${queue.length}, depth ${next.depth}/${maxDepth}`);
577
- }
578
- const res = await this.fetchTextWithTimeout(next.url, timeoutMs);
579
- if (!res.ok) {
580
- const baseMsg = `fetch ${next.url} -> ${res.status || 'error'} (${res.text.slice(0, 120)})`;
581
- const jsxHint = typeof res.text === 'string' &&
582
- res.text.includes('The JSX syntax extension is not currently enabled')
583
- ? ' Hint: CDN failed parsing JSX in a .js/.mjs file. This usually means the published package contains uncompiled JSX; fix build output or file extensions.'
584
- : '';
585
- const msg = baseMsg + jsxHint;
586
- errors.push(msg);
587
- if (!firstFailingUrl)
588
- firstFailingUrl = next.url;
589
- continue;
590
- }
591
- fetchedOk++;
592
- // For local file:// sources, parse imports in a TS-friendly way (regex-based).
593
- // For CDN URLs, parse as ESM and use es-module-lexer import locations.
594
- const isFile = next.url.startsWith('file://');
595
- if (!isFile) {
596
- const parses = await this.parseAsEsm(res.text);
597
- if (!parses) {
598
- const msg = `parse ${next.url} -> non-parseable JS`;
599
- errors.push(msg);
600
- if (!firstFailingUrl)
601
- firstFailingUrl = next.url;
602
- continue;
603
- }
604
- }
605
- const specs = isFile
606
- ? this.getTsImportSpecifiers(res.text)
607
- : await this.getImportSpecifiers(res.text);
608
- for (const spec of specs) {
609
- let resolved = null;
610
- // Prefer local resolution for PIE packages when enabled.
611
- if (localPieEnabled && this.isPiePackageSpecifier(spec)) {
612
- resolved = this.tryResolvePieToLocalFile(spec, localPieElementsPath, localPieLibPath);
613
- }
614
- if (!resolved) {
615
- if (isFile && (spec.startsWith('./') || spec.startsWith('../'))) {
616
- resolved = this.resolveLocalImport(next.url, spec);
617
- }
618
- else {
619
- resolved = this.resolveImportUrl(next.url, spec, cdnBaseUrl);
620
- }
621
- }
622
- if (!resolved)
623
- continue;
624
- if (!visited.has(resolved))
625
- queue.push({ url: resolved, depth: next.depth + 1 });
626
- }
627
- }
628
- return { ok: errors.length === 0, fetched, fetchedOk, firstFailingUrl, errors };
629
- }
630
- async fetchTextWithTimeout(url, timeoutMs) {
631
- const controller = new AbortController();
632
- const t = setTimeout(() => controller.abort(), timeoutMs);
633
- try {
634
- const res = await fetch(url, { signal: controller.signal });
635
- const text = await res.text();
636
- return { ok: res.ok, status: res.status, text };
637
- }
638
- catch (e) {
639
- return { ok: false, status: 0, text: String(e?.message || e) };
640
- }
641
- finally {
642
- clearTimeout(t);
643
- }
644
- }
645
- async probeElementsRuntime(opts) {
646
- const { elements, pieElementsPath, cdnBaseUrl, localPieEnabled, localPieElementsPath, localPieLibPath, timeoutMs, concurrency, deep, maxDepth, maxModules, cache, verbose, } = opts;
647
- const results = {};
648
- const queue = elements.slice();
649
- let done = 0;
650
- const worker = async () => {
651
- while (queue.length > 0) {
652
- const element = queue.shift();
653
- if (!element)
654
- return;
655
- const pkgPath = join(pieElementsPath, 'packages', element, 'package.json');
656
- const pkg = (await loadPackageJson(pkgPath));
657
- const pkgName = `@pie-element/${element}`;
658
- const version = String(pkg.version || 'latest');
659
- // Cache key must include probe mode + limits, otherwise a shallow cached result
660
- // would incorrectly satisfy a deep/transitive run.
661
- const cacheKey = `${cdnBaseUrl}|${pkgName}@${version}|mode=${deep ? 'deep' : 'shallow'}|depth=${maxDepth}|modules=${maxModules}`;
662
- if (cache[cacheKey]) {
663
- results[element] = cache[cacheKey];
664
- done++;
665
- if (!verbose && done % 5 === 0)
666
- this.logger.info(` Progress: ${done}/${elements.length}`);
667
- continue;
668
- }
669
- const entryUrl = `${cdnBaseUrl}/${pkgName}@${version}`;
670
- const controllerUrl = `${cdnBaseUrl}/${pkgName}@${version}/controller`;
671
- const out = {
672
- compatible: false,
673
- cdnBaseUrl,
674
- version,
675
- entryOk: false,
676
- controllerOk: false,
677
- entryParseOk: false,
678
- controllerParseOk: false,
679
- errors: [],
680
- probeMode: deep ? 'deep' : 'shallow',
681
- maxDepth: deep ? maxDepth : undefined,
682
- maxModules: deep ? maxModules : undefined,
683
- };
684
- if (!deep) {
685
- const entry = await this.fetchTextWithTimeout(entryUrl, timeoutMs);
686
- out.entryOk = entry.ok;
687
- if (!entry.ok) {
688
- out.errors.push(`entry ${entryUrl} -> ${entry.status || 'error'} (${entry.text.slice(0, 120)})`);
689
- }
690
- else {
691
- out.entryParseOk = await this.parseAsEsm(entry.text);
692
- if (!out.entryParseOk)
693
- out.errors.push(`entry ${entryUrl} returned non-parseable JS`);
694
- }
695
- const ctrl = await this.fetchTextWithTimeout(controllerUrl, timeoutMs);
696
- out.controllerOk = ctrl.ok;
697
- if (!ctrl.ok) {
698
- out.errors.push(`controller ${controllerUrl} -> ${ctrl.status || 'error'} (${ctrl.text.slice(0, 120)})`);
699
- }
700
- else {
701
- out.controllerParseOk = await this.parseAsEsm(ctrl.text);
702
- if (!out.controllerParseOk)
703
- out.errors.push(`controller ${controllerUrl} returned non-parseable JS`);
704
- }
705
- out.compatible =
706
- out.entryOk && out.entryParseOk && out.controllerOk && out.controllerParseOk;
707
- }
708
- else {
709
- // Deep probe: walk import graphs for entry and controller
710
- // Still record the top-level entry/controller status for readability.
711
- const entryTop = await this.fetchTextWithTimeout(entryUrl, timeoutMs);
712
- out.entryOk = entryTop.ok;
713
- out.entryParseOk = entryTop.ok ? await this.parseAsEsm(entryTop.text) : false;
714
- const ctrlTop = await this.fetchTextWithTimeout(controllerUrl, timeoutMs);
715
- out.controllerOk = ctrlTop.ok;
716
- out.controllerParseOk = ctrlTop.ok ? await this.parseAsEsm(ctrlTop.text) : false;
717
- const entryDeep = await this.deepProbeFromUrl({
718
- entryUrl,
719
- cdnBaseUrl,
720
- timeoutMs,
721
- maxDepth,
722
- maxModules,
723
- logPrefix: `${element} entry`,
724
- localPieEnabled,
725
- localPieElementsPath,
726
- localPieLibPath,
727
- });
728
- const ctrlDeep = await this.deepProbeFromUrl({
729
- entryUrl: controllerUrl,
730
- cdnBaseUrl,
731
- timeoutMs,
732
- maxDepth,
733
- maxModules,
734
- logPrefix: `${element} controller`,
735
- localPieEnabled,
736
- localPieElementsPath,
737
- localPieLibPath,
738
- });
739
- out.fetchedModules = (entryDeep.fetched || 0) + (ctrlDeep.fetched || 0);
740
- out.fetchedOk = (entryDeep.fetchedOk || 0) + (ctrlDeep.fetchedOk || 0);
741
- out.firstFailingUrl = entryDeep.firstFailingUrl || ctrlDeep.firstFailingUrl;
742
- out.errors.push(...entryDeep.errors.slice(0, 5));
743
- out.errors.push(...ctrlDeep.errors.slice(0, 5));
744
- out.compatible =
745
- out.entryOk &&
746
- out.entryParseOk &&
747
- out.controllerOk &&
748
- out.controllerParseOk &&
749
- entryDeep.ok &&
750
- ctrlDeep.ok;
751
- }
752
- cache[cacheKey] = out;
753
- results[element] = out;
754
- done++;
755
- if (verbose) {
756
- this.logger.info(` • ${element} -> ${out.compatible ? '✅' : '❌'} (entry:${out.entryOk ? 'ok' : 'bad'}, controller:${out.controllerOk ? 'ok' : 'bad'})`);
757
- if (!out.compatible && out.errors.length > 0) {
758
- this.logger.info(` - ${out.errors[0]}`);
759
- }
760
- }
761
- else if (done % 5 === 0 || done === elements.length) {
762
- this.logger.info(` Progress: ${done}/${elements.length}`);
763
- }
764
- }
765
- };
766
- await Promise.all(Array.from({ length: Math.max(1, Math.min(concurrency, elements.length)) }, () => worker()));
767
- return results;
768
- }
769
- async checkElementCompatibility(elementName, pieElementsPath, pieLibPath, pieLibCache, verbose, includeDevDeps) {
770
- const blockers = [];
771
- const elementPath = join(pieElementsPath, 'packages', elementName, 'package.json');
772
- const pkg = await loadPackageJson(elementPath);
773
- if (!pkg) {
774
- blockers.push(`Package.json not found at ${elementPath}`);
775
- return { compatible: false, directDeps: [], pieLibDeps: [], pieElementDeps: [], blockers };
776
- }
777
- const deps = this.getAllDeps(pkg, includeDevDeps);
778
- const directDeps = Object.keys(deps);
779
- const pieLibDeps = this.extractPieLibDeps(deps);
780
- const pieElementDeps = this.extractPieElementDeps(deps);
781
- if (verbose) {
782
- this.logger.info(`\n 📦 ${elementName}:`);
783
- this.logger.info(` Direct deps: ${directDeps.length}`);
784
- this.logger.info(` PIE Lib deps: ${pieLibDeps.join(', ') || 'none'}`);
785
- this.logger.info(` PIE Element deps: ${pieElementDeps.join(', ') || 'none'}`);
786
- }
787
- // Deep scan all dependencies recursively
788
- const depCache = new Map();
789
- for (const [dep, version] of Object.entries(deps)) {
790
- // Skip pie-lib packages - we'll check those separately
791
- if (dep.startsWith('@pie-lib/')) {
792
- continue;
793
- }
794
- await this.checkDependencyDeep(dep, version, pieElementsPath, pieLibPath, depCache, blockers, verbose, includeDevDeps, []);
795
- }
796
- // Check transitive pie-lib dependencies
797
- for (const pieLibDep of pieLibDeps) {
798
- let pieLibCheck = pieLibCache.get(pieLibDep);
799
- if (!pieLibCheck) {
800
- pieLibCheck = await this.checkPieLibCompatibility(pieLibDep, pieLibPath, verbose, includeDevDeps, pieLibCache);
801
- pieLibCache.set(pieLibDep, pieLibCheck);
802
- }
803
- if (!pieLibCheck.compatible) {
804
- for (const blocker of pieLibCheck.blockers) {
805
- const transitiveBlocker = `@pie-lib/${pieLibDep} -> ${blocker}`;
806
- blockers.push(transitiveBlocker);
807
- if (verbose) {
808
- this.logger.info(` ❌ Transitive: ${transitiveBlocker}`);
809
- }
810
- }
811
- }
812
- }
813
- const compatible = blockers.length === 0;
814
- if (verbose && compatible) {
815
- this.logger.info(' ✅ Compatible!');
816
- }
817
- return {
818
- compatible,
819
- directDeps,
820
- pieLibDeps,
821
- pieElementDeps,
822
- blockers,
823
- };
824
- }
825
- /**
826
- * Check subdirectory compatibility (src/, configure/, controller/)
827
- * Returns compatibility status for each subdirectory that has its own package.json
828
- */
829
- async checkSubdirectoryCompatibility(elementName, subdirName, pieElementsPath, pieLibPath, pieLibCache, verbose, includeDevDeps) {
830
- const subdirPath = join(pieElementsPath, 'packages', elementName, subdirName);
831
- const pkgJsonPath = join(subdirPath, 'package.json');
832
- // If no package.json in subdirectory, it's part of the main element
833
- if (!existsSync(pkgJsonPath)) {
834
- return null;
835
- }
836
- const blockers = [];
837
- const pkg = await loadPackageJson(pkgJsonPath);
838
- if (!pkg) {
839
- return null;
840
- }
841
- const deps = this.getAllDeps(pkg, includeDevDeps);
842
- const pieLibDeps = this.extractPieLibDeps(deps);
843
- if (verbose) {
844
- this.logger.info(` 📁 ${subdirName}/: checking ${Object.keys(deps).length} dependencies`);
845
- }
846
- // Deep scan all dependencies
847
- const depCache = new Map();
848
- for (const [dep, version] of Object.entries(deps)) {
849
- if (dep.startsWith('@pie-lib/')) {
850
- continue;
851
- }
852
- await this.checkDependencyDeep(dep, version, pieElementsPath, pieLibPath, depCache, blockers, verbose, includeDevDeps, []);
853
- }
854
- // Check pie-lib dependencies
855
- for (const pieLibDep of pieLibDeps) {
856
- let pieLibCheck = pieLibCache.get(pieLibDep);
857
- if (!pieLibCheck) {
858
- pieLibCheck = await this.checkPieLibCompatibility(pieLibDep, pieLibPath, verbose, includeDevDeps, pieLibCache);
859
- pieLibCache.set(pieLibDep, pieLibCheck);
860
- }
861
- if (!pieLibCheck.compatible) {
862
- for (const blocker of pieLibCheck.blockers) {
863
- const transitiveBlocker = `@pie-lib/${pieLibDep} -> ${blocker}`;
864
- blockers.push(transitiveBlocker);
865
- if (verbose) {
866
- this.logger.info(` ❌ ${subdirName}/: ${transitiveBlocker}`);
867
- }
868
- }
869
- }
870
- }
871
- const compatible = blockers.length === 0;
872
- if (verbose) {
873
- if (compatible) {
874
- this.logger.info(` ✅ ${subdirName}/: Compatible`);
875
- }
876
- else {
877
- this.logger.info(` ❌ ${subdirName}/: Blocked`);
878
- }
879
- }
880
- return { compatible, blockers };
881
- }
882
- async checkDependencyDeep(depName, version, pieElementsPath, pieLibPath, cache, blockers, verbose, includeDevDeps, depChain) {
883
- const depKey = `${depName}@${version}`;
884
- // Check cache
885
- if (cache.has(depKey)) {
886
- const cached = cache.get(depKey);
887
- if (cached && !cached.compatible) {
888
- for (const blocker of cached.blockers) {
889
- const chain = [...depChain, blocker].join(' -> ');
890
- if (!blockers.includes(chain)) {
891
- blockers.push(chain);
892
- }
893
- }
894
- }
895
- return;
896
- }
897
- // Check if this is a known ESM blocker
898
- const blocker = this.checkEsmBlocker(depName, version);
899
- if (blocker) {
900
- const chain = [...depChain, blocker].join(' -> ');
901
- if (!blockers.includes(chain)) {
902
- blockers.push(chain);
903
- if (verbose) {
904
- this.logger.info(` ❌ Transitive: ${chain}`);
905
- }
906
- }
907
- cache.set(depKey, { compatible: false, blockers: [blocker] });
908
- return;
909
- }
910
- // Try to load package.json from upstream repos to get transitive deps
911
- // Look in pie-elements node_modules first, then pie-lib node_modules
912
- let pkg = null;
913
- const possiblePaths = [
914
- join(pieElementsPath, 'node_modules', depName, 'package.json'),
915
- join(pieLibPath, 'node_modules', depName, 'package.json'),
916
- ];
917
- for (const path of possiblePaths) {
918
- if (existsSync(path)) {
919
- pkg = await loadPackageJson(path);
920
- if (pkg)
921
- break;
922
- }
923
- }
924
- if (!pkg) {
925
- // Can't resolve - assume compatible (will be caught by runtime validation if problematic)
926
- cache.set(depKey, { compatible: true, blockers: [] });
927
- return;
928
- }
929
- // Check transitive dependencies
930
- const transitiveDeps = this.getAllDeps(pkg, false); // Don't include devDeps for transitive checks
931
- const hasBlockers = false;
932
- for (const [transitiveDep, transitiveVersion] of Object.entries(transitiveDeps)) {
933
- // Skip PIE packages in transitive scan
934
- if (transitiveDep.startsWith('@pie-lib/') ||
935
- transitiveDep.startsWith('@pie-element/') ||
936
- transitiveDep.startsWith('@pie-element/')) {
937
- continue;
938
- }
939
- await this.checkDependencyDeep(transitiveDep, transitiveVersion, pieElementsPath, pieLibPath, cache, blockers, verbose, includeDevDeps, [...depChain, `${depName}@${version}`]);
940
- }
941
- cache.set(depKey, { compatible: !hasBlockers, blockers: [] });
942
- }
943
- async checkPieLibCompatibility(pkgName, pieLibPath, verbose, includeDevDeps, pieLibCache) {
944
- // Check cache first to avoid infinite recursion
945
- if (pieLibCache?.has(pkgName)) {
946
- const cached = pieLibCache.get(pkgName);
947
- if (cached)
948
- return cached;
949
- }
950
- const blockers = [];
951
- const pkgPath = join(pieLibPath, 'packages', pkgName, 'package.json');
952
- const pkg = await loadPackageJson(pkgPath);
953
- if (!pkg) {
954
- blockers.push(`Package.json not found at ${pkgPath}`);
955
- return { compatible: false, blockers };
956
- }
957
- const deps = this.getAllDeps(pkg, includeDevDeps);
958
- // Check direct dependencies for blockers
959
- for (const [dep, version] of Object.entries(deps)) {
960
- // Check for direct ESM blockers (non pie-lib packages)
961
- if (!dep.startsWith('@pie-lib/')) {
962
- const blocker = this.checkEsmBlocker(dep, version);
963
- if (blocker) {
964
- blockers.push(blocker);
965
- if (verbose) {
966
- this.logger.info(` ❌ ${pkgName}: ${blocker}`);
967
- }
968
- }
969
- }
970
- }
971
- // Store preliminary result in cache to prevent infinite recursion
972
- const preliminaryResult = {
973
- compatible: blockers.length === 0,
974
- blockers: [...blockers],
975
- };
976
- if (pieLibCache) {
977
- pieLibCache.set(pkgName, preliminaryResult);
978
- }
979
- // Recursively check transitive pie-lib dependencies
980
- const pieLibDeps = this.extractPieLibDeps(deps);
981
- for (const transitivePieLib of pieLibDeps) {
982
- const transitiveCheck = await this.checkPieLibCompatibility(transitivePieLib, pieLibPath, verbose, includeDevDeps, pieLibCache);
983
- if (!transitiveCheck.compatible) {
984
- for (const blocker of transitiveCheck.blockers) {
985
- const transitiveBlocker = `@pie-lib/${transitivePieLib} -> ${blocker}`;
986
- blockers.push(transitiveBlocker);
987
- if (verbose) {
988
- this.logger.info(` ❌ ${pkgName}: transitive ${transitiveBlocker}`);
989
- }
990
- }
991
- }
992
- }
993
- // Update cache with final result
994
- const finalResult = {
995
- compatible: blockers.length === 0,
996
- blockers,
997
- };
998
- if (pieLibCache) {
999
- pieLibCache.set(pkgName, finalResult);
1000
- }
1001
- return finalResult;
1002
- }
1003
- /**
1004
- * Collect all transitive pie-lib dependencies recursively.
1005
- * For example, if text-select depends on style-utils, we need style-utils too.
1006
- */
1007
- async collectAllTransitivePieLibDeps(pieLibDeps, pieLibPath, includeDevDeps, visited = new Set()) {
1008
- const allDeps = new Set(pieLibDeps);
1009
- for (const dep of pieLibDeps) {
1010
- if (visited.has(dep)) {
1011
- continue;
1012
- }
1013
- visited.add(dep);
1014
- const pkgPath = join(pieLibPath, 'packages', dep, 'package.json');
1015
- let pkg = null;
1016
- try {
1017
- pkg = await loadPackageJson(pkgPath);
1018
- }
1019
- catch (error) {
1020
- // Package doesn't exist or can't be read, skip it
1021
- continue;
1022
- }
1023
- if (!pkg)
1024
- continue;
1025
- const deps = this.getAllDeps(pkg, includeDevDeps);
1026
- const transitivePieLibDeps = this.extractPieLibDeps(deps);
1027
- // Recursively collect transitive deps
1028
- const deepDeps = await this.collectAllTransitivePieLibDeps(transitivePieLibDeps, pieLibPath, includeDevDeps, visited);
1029
- for (const transitiveDep of deepDeps) {
1030
- allDeps.add(transitiveDep);
1031
- }
1032
- }
1033
- return Array.from(allDeps);
1034
- }
1035
- getAllDeps(pkg, includeDevDeps) {
1036
- const optionalDependencies = pkg.optionalDependencies ?? {};
1037
- return {
1038
- ...pkg.dependencies,
1039
- ...optionalDependencies,
1040
- ...(includeDevDeps ? pkg.devDependencies : {}),
1041
- };
1042
- }
1043
- extractPieLibDeps(deps) {
1044
- return Object.keys(deps)
1045
- .filter((dep) => dep.startsWith('@pie-lib/'))
1046
- .map((dep) => dep.replace('@pie-lib/', ''));
1047
- }
1048
- extractPieElementDeps(deps) {
1049
- return Object.keys(deps)
1050
- .filter((dep) => dep.startsWith('@pie-element/'))
1051
- .map((dep) => dep.replace('@pie-element/', ''));
1052
- }
1053
- checkEsmBlocker(dep, version) {
1054
- const depVersion = `${dep}@${version}`;
1055
- for (const blocker of ESM_BLOCKERS) {
1056
- if (blocker.pattern.test(depVersion) || blocker.pattern.test(dep)) {
1057
- return `${dep}@${version} - ${blocker.reason}`;
1058
- }
1059
- }
1060
- return null;
1061
- }
1062
- async validateEsmPlayerCompatibility(elementName, pieElementsPath, verbose) {
1063
- const blockers = [];
1064
- const warnings = [];
1065
- const elementPath = join(pieElementsPath, 'packages', elementName, 'package.json');
1066
- const pkg = await loadPackageJson(elementPath);
1067
- if (!pkg) {
1068
- blockers.push(`Package.json not found at ${elementPath}`);
1069
- return {
1070
- compatible: false,
1071
- packageJson: {
1072
- hasTypeModule: false,
1073
- hasExportsField: false,
1074
- hasMainExport: false,
1075
- hasControllerExport: false,
1076
- sideEffectsFree: false,
1077
- mainExportIsEsm: false,
1078
- controllerExportIsEsm: false,
1079
- },
1080
- blockers,
1081
- warnings,
1082
- };
1083
- }
1084
- // Check 1: type: "module"
1085
- const hasTypeModule = pkg.type === 'module';
1086
- if (!hasTypeModule) {
1087
- blockers.push('Missing "type": "module" in package.json');
1088
- }
1089
- // Check 2: exports field exists
1090
- const hasExportsField = !!pkg.exports;
1091
- if (!hasExportsField) {
1092
- blockers.push('Missing "exports" field in package.json');
1093
- }
1094
- // Check 3: main export (".")
1095
- const exportsObj = pkg.exports;
1096
- const mainExport = exportsObj?.['.'];
1097
- const hasMainExport = !!mainExport;
1098
- if (!hasMainExport && hasExportsField) {
1099
- blockers.push('Missing "." export in package.json exports field');
1100
- }
1101
- // Check 4: controller export ("./controller")
1102
- const controllerExport = exportsObj?.['./controller'];
1103
- const hasControllerExport = !!controllerExport;
1104
- if (!hasControllerExport && hasExportsField) {
1105
- warnings.push('Missing "./controller" export - ESM player needs controller subpath');
1106
- }
1107
- // Check 5: sideEffects
1108
- const sideEffectsFree = pkg.sideEffects === false;
1109
- if (!sideEffectsFree) {
1110
- warnings.push('Consider adding "sideEffects": false for better tree-shaking');
1111
- }
1112
- // Check 6: main export points to .js file
1113
- let mainExportIsEsm = false;
1114
- if (mainExport) {
1115
- const exportObj = mainExport;
1116
- const mainPath = typeof exportObj === 'string'
1117
- ? exportObj
1118
- : exportObj.import || exportObj.default;
1119
- mainExportIsEsm = typeof mainPath === 'string' && mainPath.endsWith('.js');
1120
- if (!mainExportIsEsm) {
1121
- blockers.push(`Main export must point to .js file (ESM), got: ${mainPath}`);
1122
- }
1123
- }
1124
- // Check 7: controller export points to .js file
1125
- let controllerExportIsEsm = false;
1126
- if (controllerExport) {
1127
- const exportObj = controllerExport;
1128
- const controllerPath = typeof exportObj === 'string'
1129
- ? exportObj
1130
- : exportObj.import || exportObj.default;
1131
- controllerExportIsEsm = typeof controllerPath === 'string' && controllerPath.endsWith('.js');
1132
- if (!controllerExportIsEsm) {
1133
- warnings.push(`Controller export should point to .js file (ESM), got: ${controllerPath}`);
1134
- }
1135
- }
1136
- const validation = {
1137
- hasTypeModule,
1138
- hasExportsField,
1139
- hasMainExport,
1140
- hasControllerExport,
1141
- sideEffectsFree,
1142
- mainExportIsEsm,
1143
- controllerExportIsEsm,
1144
- };
1145
- const compatible = blockers.length === 0;
1146
- if (verbose) {
1147
- if (compatible) {
1148
- this.logger.info(` ✅ ${elementName}: ESM player ready`);
1149
- }
1150
- else {
1151
- this.logger.info(` ❌ ${elementName}: Not ESM player ready`);
1152
- for (const blocker of blockers) {
1153
- this.logger.info(` - ${blocker}`);
1154
- }
1155
- }
1156
- }
1157
- return {
1158
- compatible,
1159
- packageJson: validation,
1160
- blockers,
1161
- warnings,
1162
- };
1163
- }
1164
- printReport(report, outputPath) {
1165
- const verbose = this.logger.isVerbose();
1166
- if (verbose) {
1167
- this.log(`\n${'='.repeat(70)}`);
1168
- this.log('📊 ESM COMPATIBILITY REPORT');
1169
- this.log('='.repeat(70));
1170
- this.log('\n📦 Elements:');
1171
- this.log(` Total: ${report.summary.totalElements}`);
1172
- this.log(` CommonJS-free: ${report.summary.compatibleElements} ✅ (no CommonJS deps)`);
1173
- if (report.esmPlayerValidationEnabled) {
1174
- this.log(` ESM player ready: ${report.summary.esmPlayerReady} ✅ (package.json exports)`);
1175
- }
1176
- else {
1177
- this.log(' ESM player ready: n/a (validation disabled)');
1178
- }
1179
- if (report.esmRuntimeValidationEnabled) {
1180
- const runtimeReady = report.summary.esmRuntimeReady ?? 0;
1181
- this.log(` Runtime ready: ${runtimeReady} ✅ (CDN probe: fetch + parse)`);
1182
- }
1183
- else {
1184
- this.log(' Runtime ready: n/a (runtime probes disabled)');
1185
- }
1186
- this.log(` Blocked: ${report.summary.blockedElements} ❌`);
1187
- this.log('\n📚 PIE Lib Packages:');
1188
- this.log(` Total: ${report.summary.totalPieLibPackages}`);
1189
- this.log(` Compatible: ${report.summary.compatiblePieLibPackages} ✅`);
1190
- this.log(` Blocked: ${report.summary.totalPieLibPackages - report.summary.compatiblePieLibPackages} ❌`);
1191
- if (report.esmPlayerValidationEnabled) {
1192
- // ESM player ready elements (best category)
1193
- if (report.esmPlayerReady.length > 0) {
1194
- this.log(`\n✅ ESM Player Ready (${report.esmPlayerReady.length}):`);
1195
- for (const element of report.esmPlayerReady.sort()) {
1196
- const validation = report.esmValidation[element];
1197
- const deps = report.elementDetails[element]?.pieLibDeps || [];
1198
- this.log(` • ${element}`);
1199
- this.log(` - type: module ${validation.packageJson.hasTypeModule ? '✅' : '❌'}`);
1200
- this.log(` - exports: . ${validation.packageJson.hasMainExport ? '✅' : '❌'}`);
1201
- this.log(` - exports: ./controller ${validation.packageJson.hasControllerExport ? '✅' : '❌'}`);
1202
- this.log(` - deps: ${deps.length > 0 ? deps.join(', ') : 'none'}`);
1203
- if (report.esmRuntimeValidationEnabled && report.esmRuntimeValidation?.[element]) {
1204
- const r = report.esmRuntimeValidation[element];
1205
- this.log(` - runtime probe: ${r.compatible ? '✅' : '❌'} (${r.cdnBaseUrl}, entry:${r.entryOk ? 'ok' : 'bad'}, controller:${r.controllerOk ? 'ok' : 'bad'})`);
1206
- if (!r.compatible && r.errors?.length) {
1207
- this.log(` - ${r.errors[0]}`);
1208
- }
1209
- }
1210
- }
1211
- }
1212
- // CommonJS-free but not ESM player ready
1213
- const commonJsFreeNotEsmReady = report.elements.filter((element) => !report.esmPlayerReady.includes(element));
1214
- if (commonJsFreeNotEsmReady.length > 0) {
1215
- this.log(`\n⚠️ CommonJS-free but not ESM Player Ready (${commonJsFreeNotEsmReady.length}):`);
1216
- for (const element of commonJsFreeNotEsmReady.sort()) {
1217
- const validation = report.esmValidation[element];
1218
- this.log(` • ${element}`);
1219
- if (!validation.packageJson.hasTypeModule) {
1220
- this.log(` ❌ Missing "type": "module"`);
1221
- }
1222
- if (!validation.packageJson.hasExportsField) {
1223
- this.log(` ❌ Missing "exports" field`);
1224
- }
1225
- if (!validation.packageJson.hasMainExport) {
1226
- this.log(` ❌ Missing "." export`);
1227
- }
1228
- if (!validation.packageJson.hasControllerExport) {
1229
- this.log(` ❌ Missing "./controller" export`);
1230
- }
1231
- if (!validation.packageJson.mainExportIsEsm) {
1232
- this.log(` ❌ Main export not ESM (.js)`);
1233
- }
1234
- // Show warnings
1235
- for (const warning of validation.warnings) {
1236
- this.log(` ⚠️ ${warning}`);
1237
- }
1238
- }
1239
- }
1240
- }
1241
- if (Object.keys(report.blockedElements).length > 0) {
1242
- this.log(`\n❌ Blocked Elements (${Object.keys(report.blockedElements).length}):`);
1243
- for (const [element, blockers] of Object.entries(report.blockedElements).sort()) {
1244
- this.log(` • ${element}:`);
1245
- for (const blocker of blockers) {
1246
- this.log(` - ${blocker}`);
1247
- }
1248
- }
1249
- }
1250
- if (report.pieLibPackages.length > 0) {
1251
- this.log(`\n📚 Compatible PIE Lib Packages (${report.pieLibPackages.length}):`);
1252
- for (const pkg of report.pieLibPackages.sort()) {
1253
- const usedBy = report.pieLibDetails[pkg]?.usedBy || [];
1254
- this.log(` • ${pkg} (used by: ${usedBy.join(', ')})`);
1255
- }
1256
- }
1257
- const blockedPieLib = Object.entries(report.pieLibDetails)
1258
- .filter(([_, details]) => !details.compatible)
1259
- .sort();
1260
- if (blockedPieLib.length > 0) {
1261
- this.log(`\n❌ Blocked PIE Lib Packages (${blockedPieLib.length}):`);
1262
- for (const [pkg, details] of blockedPieLib) {
1263
- this.log(` • ${pkg} (needed by: ${details.usedBy.join(', ')}):`);
1264
- for (const blocker of details.blockers) {
1265
- this.log(` - ${blocker}`);
1266
- }
1267
- }
1268
- }
1269
- this.printNotReadyActionReport(report);
1270
- this.log(`\n${'='.repeat(70)}`);
1271
- this.log(`\n💾 Report saved to: ${outputPath}`);
1272
- this.log('\n💡 Next steps:');
1273
- this.log(' 1. Review the compatibility report above');
1274
- this.log(' 2. Run sync: bun run upstream:sync');
1275
- this.log(' 3. The sync will automatically use the ESM-compatible list\n');
1276
- }
1277
- else {
1278
- // Non-verbose: just show where report was saved
1279
- this.log(`\n💾 Report saved to: ${outputPath}`);
1280
- }
1281
- }
1282
- printNotReadyActionReport(report) {
1283
- const allElements = Object.keys(report.elementDetails).sort();
1284
- const blockedElements = allElements.filter((e) => !report.elementDetails[e]?.compatible);
1285
- const commonJsFreeNotEsmReady = report.esmPlayerValidationEnabled
1286
- ? report.elements.filter((e) => !report.esmPlayerReady.includes(e))
1287
- : [];
1288
- const runtimeNotReady = report.esmRuntimeValidationEnabled && report.esmRuntimeValidation
1289
- ? Object.entries(report.esmRuntimeValidation)
1290
- .filter(([_, r]) => !r.compatible)
1291
- .map(([e]) => e)
1292
- : [];
1293
- const blockedPieLib = Object.entries(report.pieLibDetails)
1294
- .filter(([_, details]) => !details.compatible)
1295
- .sort();
1296
- const hasAnyNotReady = blockedElements.length > 0 ||
1297
- commonJsFreeNotEsmReady.length > 0 ||
1298
- runtimeNotReady.length > 0 ||
1299
- blockedPieLib.length > 0;
1300
- if (!hasAnyNotReady)
1301
- return;
1302
- this.log('\n🚧 Not ESM-ready yet (action items for upstream maintainers)');
1303
- this.log(' Goal: “deploy package + ESM player can load entry + controller (and transitives)”\n');
1304
- if (blockedElements.length > 0) {
1305
- this.log(` ❌ CommonJS blockers (${blockedElements.length}):`);
1306
- this.log(' Fix: remove/upgrade/replace the listed CommonJS-only deps (direct or via @pie-lib/*).');
1307
- for (const element of blockedElements) {
1308
- const blockers = report.elementDetails[element]?.blockers ?? report.blockedElements[element] ?? [];
1309
- this.log(`\n • ${element}`);
1310
- for (const blocker of blockers.slice(0, 5)) {
1311
- this.log(` - ${blocker}`);
1312
- }
1313
- if (blockers.length > 5) {
1314
- this.log(` - …and ${blockers.length - 5} more`);
1315
- }
1316
- this.log(' What to do:');
1317
- this.log(' - Upgrade the dependency to a version that provides ESM + proper "exports"');
1318
- this.log(' - If no ESM exists, replace the dependency or move it behind build-time code (not runtime)');
1319
- }
1320
- this.log('');
1321
- }
1322
- if (report.esmPlayerValidationEnabled && commonJsFreeNotEsmReady.length > 0) {
1323
- this.log(` ⚠️ Package metadata / exports issues (${commonJsFreeNotEsmReady.length}):`);
1324
- this.log(' Fix: make package.json ESM-friendly so an ESM loader can resolve `@pie-element/<name>` + `/controller`.\n');
1325
- for (const element of commonJsFreeNotEsmReady.sort()) {
1326
- const validation = report.esmValidation[element];
1327
- if (!validation)
1328
- continue;
1329
- const pj = validation.packageJson;
1330
- this.log(` • ${element}`);
1331
- const issues = [];
1332
- const fixes = [];
1333
- if (!pj.hasTypeModule) {
1334
- issues.push('Missing `"type": "module"`');
1335
- fixes.push('Add `"type": "module"` (or use `.mjs` consistently) so Node/bundlers treat output as ESM.');
1336
- }
1337
- if (!pj.hasExportsField) {
1338
- issues.push('Missing `"exports"`');
1339
- fixes.push('Add `"exports"` with `"."` (entry) and `"./controller"` (controller) subpaths pointing at `dist/*`.');
1340
- }
1341
- if (pj.hasExportsField && !pj.hasMainExport) {
1342
- issues.push('Missing `"exports"."."`');
1343
- fixes.push('Add `"exports": { ".": { "default": "./dist/index.js" } }` (path may vary).');
1344
- }
1345
- if (!pj.hasControllerExport) {
1346
- issues.push('Missing `"exports"."./controller"`');
1347
- fixes.push('Add `"./controller": { "default": "./dist/controller/index.js" }` when a controller exists.');
1348
- }
1349
- if (!pj.mainExportIsEsm) {
1350
- issues.push('Main export does not point at a `.js` ESM build');
1351
- fixes.push('Ensure the published entry is transpiled ESM JS (no TS, no JSX) and the export points to it.');
1352
- }
1353
- if (pj.hasControllerExport && !pj.controllerExportIsEsm) {
1354
- issues.push('Controller export does not point at a `.js` ESM build');
1355
- fixes.push('Ensure the published controller is transpiled ESM JS (no TS, no JSX) and the export points to it.');
1356
- }
1357
- for (const issue of issues.slice(0, 6)) {
1358
- this.log(` - ${issue}`);
1359
- }
1360
- if (validation.blockers.length > 0) {
1361
- this.log(` - Details: ${validation.blockers[0]}`);
1362
- }
1363
- if (validation.warnings.length > 0) {
1364
- this.log(` - Warning: ${validation.warnings[0]}`);
1365
- }
1366
- this.log(' What to do:');
1367
- for (const fix of fixes.slice(0, 4)) {
1368
- this.log(` - ${fix}`);
1369
- }
1370
- this.log('');
1371
- }
1372
- }
1373
- if (report.esmRuntimeValidationEnabled &&
1374
- report.esmRuntimeValidation &&
1375
- runtimeNotReady.length > 0) {
1376
- this.log(` ❌ Runtime probe failures (${runtimeNotReady.length}):`);
1377
- this.log(' Fix: make sure the published JS parses as ESM and all transitives resolve in production-like loading.\n');
1378
- for (const element of runtimeNotReady.sort()) {
1379
- const r = report.esmRuntimeValidation[element];
1380
- if (!r)
1381
- continue;
1382
- this.log(` • ${element} (CDN: ${r.cdnBaseUrl}, mode: ${r.probeMode ?? 'shallow'})`);
1383
- if (r.firstFailingUrl)
1384
- this.log(` - First failing URL: ${r.firstFailingUrl}`);
1385
- const firstErr = r.errors?.[0];
1386
- if (firstErr)
1387
- this.log(` - Error: ${firstErr}`);
1388
- const suggestions = this.suggestionsFromRuntimeError(firstErr);
1389
- if (suggestions.length > 0) {
1390
- this.log(' What to do:');
1391
- for (const s of suggestions)
1392
- this.log(` - ${s}`);
1393
- }
1394
- this.log('');
1395
- }
1396
- }
1397
- if (blockedPieLib.length > 0) {
1398
- this.log(` ❌ PIE lib packages blocking ESM (${blockedPieLib.length}):`);
1399
- this.log(' Fix: these must become ESM-compatible because elements import them.\n');
1400
- for (const [pkg, details] of blockedPieLib) {
1401
- this.log(` • @pie-lib/${pkg} (used by: ${details.usedBy.join(', ')})`);
1402
- for (const blocker of details.blockers.slice(0, 5)) {
1403
- this.log(` - ${blocker}`);
1404
- }
1405
- if (details.blockers.length > 5) {
1406
- this.log(` - …and ${details.blockers.length - 5} more`);
1407
- }
1408
- }
1409
- this.log('');
1410
- }
1411
- }
1412
- suggestionsFromRuntimeError(err) {
1413
- if (!err) {
1414
- return [
1415
- 'Confirm the published entry and controller URLs return JavaScript (not HTML/404) and parse as ESM.',
1416
- 'Re-run with --verbose to see the exact failing URL + first error.',
1417
- ];
1418
- }
1419
- const e = err.toLowerCase();
1420
- if (e.includes('jsx syntax extension is not currently enabled') ||
1421
- e.includes('unexpected token <')) {
1422
- return [
1423
- 'Your published output likely contains raw JSX; transpile JSX away during build (do not ship JSX in `.js/.mjs`).',
1424
- 'Verify `dist/` contains plain JS and that `package.json` exports point at those `dist/` files.',
1425
- ];
1426
- }
1427
- if (e.includes('missing') && e.includes('specifier') && e.includes('exports')) {
1428
- return [
1429
- 'A dependency is deep-importing a path that is not exposed via `"exports"`; upgrade/replace that dependency or avoid that deep import.',
1430
- 'If this is a PIE package, ensure its `"exports"` explicitly lists the needed subpaths.',
1431
- ];
1432
- }
1433
- if (e.includes('could not resolve') || e.includes('not found') || e.includes('404')) {
1434
- return [
1435
- 'Ensure the entry/controller paths you publish actually exist on the CDN (and match `package.json` exports).',
1436
- 'If the controller exists, publish it as a subpath export (e.g. `./controller`) and ship the referenced `dist/` files.',
1437
- ];
1438
- }
1439
- if (e.includes('commonjs') ||
1440
- e.includes('require is not defined') ||
1441
- e.includes('module is not defined')) {
1442
- return [
1443
- 'A transitive dependency is CommonJS-only; upgrade/replace it with an ESM-capable version, or ship a pre-bundled ESM build.',
1444
- ];
1445
- }
1446
- return [
1447
- 'Inspect the first failing URL and error; fix whichever dependency/output is not valid ESM.',
1448
- 'Re-run with --verbose and (if needed) increase --runtime-max-depth / --runtime-max-modules to reproduce reliably.',
1449
- ];
1450
- }
1451
- }
1452
- //# sourceMappingURL=analyze-esm.js.map