@eightshift/frontend-libs-tailwind 4.0.0-beta.1 → 4.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,381 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, resolve, sep } from 'node:path';
4
+ import { Linter } from 'eslint';
5
+
6
+ const linter = new Linter();
7
+ const inDependencies = (path) => path.split(sep).includes('node_modules');
8
+ const comparePaths = (a, b) => (a.path < b.path ? -1 : Number(a.path > b.path));
9
+
10
+ function parse(source) {
11
+ let ast;
12
+ const messages = linter.verify(
13
+ source,
14
+ [
15
+ {
16
+ languageOptions: { ecmaVersion: 'latest', sourceType: 'module', parserOptions: { ecmaFeatures: { jsx: true } } },
17
+ plugins: {
18
+ capture: {
19
+ rules: {
20
+ ast: {
21
+ create: () => ({
22
+ Program: (node) => {
23
+ ast = node;
24
+ },
25
+ }),
26
+ },
27
+ },
28
+ },
29
+ },
30
+ rules: { 'capture/ast': 'error' },
31
+ },
32
+ ],
33
+ { filename: 'module.js' },
34
+ );
35
+ return messages.length ? undefined : ast;
36
+ }
37
+
38
+ function inspect(source) {
39
+ const ast = parse(source);
40
+ if (!ast) {
41
+ return;
42
+ }
43
+ const factories = new Set();
44
+ const locals = new Set();
45
+ const names = [];
46
+ const pure = (node) => {
47
+ if (!node) {
48
+ return false;
49
+ }
50
+ if (node.type === 'Literal') {
51
+ return !node.regex && (node.value === null || ['string', 'number', 'boolean'].includes(typeof node.value));
52
+ }
53
+ if (node.type === 'UnaryExpression') {
54
+ return ['+', '-', '!'].includes(node.operator) && node.argument.type === 'Literal' && pure(node.argument);
55
+ }
56
+ if (node.type === 'ArrayExpression') {
57
+ return node.elements.every((element) => element === null || pure(element));
58
+ }
59
+ if (node.type === 'ObjectExpression') {
60
+ return node.properties.every((property) => property.type === 'Property' && property.kind === 'init' && !property.method && !property.computed && !property.shorthand && pure(property.value));
61
+ }
62
+ return (
63
+ node.type === 'CallExpression' &&
64
+ !node.optional &&
65
+ node.callee.type === 'Identifier' &&
66
+ factories.has(node.callee.name) &&
67
+ node.arguments.length >= 2 &&
68
+ node.arguments.length <= 3 &&
69
+ node.arguments[0].type === 'Literal' &&
70
+ typeof node.arguments[0].value === 'string' &&
71
+ node.arguments[1].type === 'ObjectExpression' &&
72
+ (node.arguments.length === 2 || node.arguments[2].type === 'Literal') &&
73
+ node.arguments.slice(1).every(pure)
74
+ );
75
+ };
76
+ for (const node of ast.body) {
77
+ if (node.type === 'ImportDeclaration') {
78
+ if (node.source.value !== 'react/jsx-runtime' || !node.specifiers.length || node.attributes?.length) {
79
+ return;
80
+ }
81
+ for (const specifier of node.specifiers) {
82
+ if (specifier.type !== 'ImportSpecifier' || !['jsx', 'jsxs'].includes(specifier.imported.name) || factories.has(specifier.local.name) || locals.has(specifier.local.name)) {
83
+ return;
84
+ }
85
+ factories.add(specifier.local.name);
86
+ }
87
+ } else if (node.type === 'VariableDeclaration') {
88
+ for (const declaration of node.declarations) {
89
+ if (declaration.id.type !== 'Identifier' || locals.has(declaration.id.name) || factories.has(declaration.id.name) || !pure(declaration.init)) {
90
+ return;
91
+ }
92
+ locals.add(declaration.id.name);
93
+ }
94
+ } else if (node.type === 'ExportNamedDeclaration' && !node.source && !node.declaration) {
95
+ for (const specifier of node.specifiers) {
96
+ if (specifier.type !== 'ExportSpecifier' || !locals.has(specifier.local.name) || specifier.exported.type !== 'Identifier') {
97
+ return;
98
+ }
99
+ names.push(specifier.exported.name);
100
+ }
101
+ } else {
102
+ return;
103
+ }
104
+ }
105
+ if (!factories.size || !names.length || new Set(names).size !== names.length) {
106
+ return;
107
+ }
108
+ return { ast, names };
109
+ }
110
+
111
+ function combine({ source, ast }, index) {
112
+ const prefix = `__eightshiftPure${index}_`;
113
+ const edits = [];
114
+ const names = [];
115
+ const replace = (node, text) => edits.push({ start: node.range[0], end: node.range[1], text });
116
+ const visit = (node) => {
117
+ if (!node || typeof node !== 'object') {
118
+ return;
119
+ }
120
+ if (node.type === 'ExportNamedDeclaration') {
121
+ for (const specifier of node.specifiers) {
122
+ names.push(`${prefix}${specifier.local.name} as ${specifier.exported.name}`);
123
+ }
124
+ replace(node, '');
125
+ return;
126
+ }
127
+ if (node.type === 'ImportSpecifier') {
128
+ replace(node, `${node.imported.name} as ${prefix}${node.local.name}`);
129
+ return;
130
+ }
131
+ if (node.type === 'VariableDeclarator') {
132
+ replace(node.id, `${prefix}${node.id.name}`);
133
+ visit(node.init);
134
+ return;
135
+ }
136
+ if (node.type === 'CallExpression') {
137
+ replace(node.callee, `${prefix}${node.callee.name}`);
138
+ node.arguments.forEach(visit);
139
+ return;
140
+ }
141
+ for (const [key, value] of Object.entries(node)) {
142
+ if (['parent', 'tokens', 'comments', 'loc', 'range'].includes(key)) {
143
+ continue;
144
+ }
145
+ if (Array.isArray(value)) {
146
+ value.forEach(visit);
147
+ } else {
148
+ visit(value);
149
+ }
150
+ }
151
+ };
152
+ visit(ast);
153
+ for (const edit of edits.sort((a, b) => b.start - a.start)) {
154
+ source = source.slice(0, edit.start) + edit.text + source.slice(edit.end);
155
+ }
156
+ return `${source}\nexport { ${names.join(', ')} };\n`;
157
+ }
158
+
159
+ async function analyzeGraph({ result, metadata, directory, entries }) {
160
+ const outputs = new Map(Object.entries(metadata.outputs).map(([path, info]) => [resolve(directory, path), info]));
161
+ const artifacts = new Map(result.outputs.map((output) => [output.path, output]));
162
+ const roots = [...outputs].filter(([, info]) => info.entryPoint && entries.has(resolve(info.entryPoint))).map(([path]) => path);
163
+ if (roots.length !== entries.size) {
164
+ throw new Error('Ambiguous initial editor roots');
165
+ }
166
+ const graph = new Map();
167
+ const scanner = new Bun.Transpiler();
168
+ for (const [path] of outputs) {
169
+ if (!path.endsWith('.js')) {
170
+ continue;
171
+ }
172
+ const artifact = artifacts.get(path);
173
+ if (!artifact) {
174
+ throw new Error('Missing native editor artifact');
175
+ }
176
+ const edges = [];
177
+ for (const imported of scanner.scan(await artifact.text()).imports) {
178
+ if (!imported.path.startsWith('.')) {
179
+ continue;
180
+ }
181
+ const target = resolve(dirname(path), imported.path);
182
+ if (!outputs.has(target) || !['import-statement', 'dynamic-import'].includes(imported.kind)) {
183
+ throw new Error('Unknown native editor graph edge');
184
+ }
185
+ edges.push({ path: target, lazy: Number(imported.kind === 'dynamic-import') });
186
+ }
187
+ graph.set(path, edges);
188
+ }
189
+ const depths = new Map();
190
+ const pending = roots.map((path) => ({ path, depth: 0 }));
191
+ for (let index = 0; index < pending.length; index++) {
192
+ const { path, depth } = pending[index];
193
+ if ((depths.get(path) ?? Infinity) <= depth) {
194
+ continue;
195
+ }
196
+ depths.set(path, depth);
197
+ for (const edge of graph.get(path) ?? []) {
198
+ pending.push({ path: edge.path, depth: depth + edge.lazy });
199
+ }
200
+ }
201
+ const sourceDepths = new Map();
202
+ for (const [path, info] of outputs) {
203
+ for (const [source, input] of Object.entries(info.inputs ?? {})) {
204
+ if (input.bytesInOutput > 0 && depths.has(path)) {
205
+ const key = source.includes(':') ? source : resolve(source);
206
+ sourceDepths.set(key, Math.min(sourceDepths.get(key) ?? Infinity, depths.get(path)));
207
+ }
208
+ }
209
+ }
210
+ return { outputs, depths, sourceDepths };
211
+ }
212
+
213
+ /** Analyze native output, but rebuild original sources rather than editing emitted chunks. */
214
+ export async function createPureJsxGroups({ result, metadata, directory, entries, maxBytes }) {
215
+ const { outputs, depths, sourceDepths } = await analyzeGraph({ result, metadata, directory, entries });
216
+ const inputs = new Map(
217
+ Object.entries(metadata.inputs)
218
+ .filter(([path]) => !path.includes(':'))
219
+ .map(([path, info]) => [resolve(path), info]),
220
+ );
221
+ const occurrences = new Map();
222
+ for (const info of outputs.values()) {
223
+ for (const [path, input] of Object.entries(info.inputs ?? {})) {
224
+ if (input.bytesInOutput > 0) {
225
+ const absolute = resolve(path);
226
+ occurrences.set(absolute, (occurrences.get(absolute) ?? 0) + 1);
227
+ }
228
+ }
229
+ }
230
+ const candidates = [];
231
+ for (const [output, info] of outputs) {
232
+ if (info.entryPoint || !depths.has(output) || !Number.isFinite(info.bytes) || info.bytes > maxBytes) {
233
+ continue;
234
+ }
235
+ const sources = Object.entries(info.inputs ?? {})
236
+ .filter(([, input]) => input.bytesInOutput > 0)
237
+ .map(([path]) => resolve(path));
238
+ if (sources.length !== 1) {
239
+ continue;
240
+ }
241
+ const [path] = sources;
242
+ const input = inputs.get(path);
243
+ if (!inDependencies(path) || !path.endsWith('.js') || occurrences.get(path) !== 1 || !input || input.bytes > maxBytes) {
244
+ continue;
245
+ }
246
+ const imports = input.imports;
247
+ if (!imports.length || imports.some((item) => item.original !== 'react/jsx-runtime' || item.kind !== 'import-statement' || item.external) || new Set(imports.map((item) => item.path)).size !== 1) {
248
+ continue;
249
+ }
250
+ const source = await readFile(path, 'utf8');
251
+ const bytes = Buffer.byteLength(source);
252
+ const proof = bytes <= maxBytes && bytes === input.bytes && inspect(source);
253
+ if (proof) {
254
+ candidates.push({ path, source, bytes, ...proof, runtime: imports[0].path, depth: depths.get(output) });
255
+ }
256
+ }
257
+ const buckets = new Map();
258
+ for (const candidate of candidates.sort(comparePaths)) {
259
+ const key = JSON.stringify([dirname(candidate.path), candidate.runtime, candidate.depth]);
260
+ if (!buckets.has(key)) {
261
+ buckets.set(key, []);
262
+ }
263
+ buckets.get(key).push(candidate);
264
+ }
265
+ const groups = [];
266
+ for (const bucket of buckets.values()) {
267
+ let members = [];
268
+ let bytes = 0;
269
+ let names = new Set();
270
+ const flush = () => {
271
+ if (members.length > 1) {
272
+ const id = createHash('sha256')
273
+ .update(members.map((member) => `${member.path}\0${member.source}`).join('\0'))
274
+ .digest('hex')
275
+ .slice(0, 20);
276
+ groups.push({ members, bytes, path: resolve(dirname(members[0].path), `__eightshift-pure-${id}.js`) });
277
+ }
278
+ members = [];
279
+ bytes = 0;
280
+ names = new Set();
281
+ };
282
+ for (const member of bucket) {
283
+ if (bytes + member.bytes > maxBytes || member.names.some((name) => names.has(name))) {
284
+ flush();
285
+ }
286
+ members.push(member);
287
+ bytes += member.bytes;
288
+ member.names.forEach((name) => names.add(name));
289
+ }
290
+ flush();
291
+ }
292
+ const byPath = new Map(groups.flatMap((group) => group.members.map((member) => [member.path, { group, member }])));
293
+ const byGroup = new Map(groups.map((group) => [group.path, group]));
294
+ const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
295
+ // Broad no-op hooks can disable Bun's import optimization for unrelated modules.
296
+ const sourceFilter = new RegExp(`^(?:${[...byPath.keys()].map(escape).join('|')})$`);
297
+ const importFilter = new RegExp(`(?:^|/)(?:${[...new Set([...byPath.keys()].map((path) => basename(path)))].map(escape).join('|')})$`);
298
+ const consumerCache = new Map();
299
+ async function namedOnly(importer, specifier) {
300
+ // Audited discovery only transforms require.context files; those retain native facades.
301
+ if (!isAbsolute(importer) || !importer.endsWith('.js')) {
302
+ return false;
303
+ }
304
+ if (!consumerCache.has(importer)) {
305
+ const source = await readFile(importer, 'utf8');
306
+ consumerCache.set(importer, source.includes('require.context') ? undefined : parse(source));
307
+ }
308
+ const ast = consumerCache.get(importer);
309
+ const references = ast?.body.filter((node) => node.source?.value === specifier) ?? [];
310
+ return (
311
+ references.length > 0 &&
312
+ references.every(
313
+ (node) =>
314
+ !node.attributes?.length &&
315
+ ((node.type === 'ImportDeclaration' && node.specifiers.length > 0 && node.specifiers.every((item) => item.type === 'ImportSpecifier')) || (node.type === 'ExportNamedDeclaration' && node.specifiers.length > 0 && node.specifiers.every((item) => item.type === 'ExportSpecifier'))),
316
+ )
317
+ );
318
+ }
319
+ const plugin = {
320
+ name: 'eightshift-bounded-pure-jsx',
321
+ setup(builder) {
322
+ builder.onResolve({ filter: /^eightshift-pure:/ }, ({ path }) => {
323
+ const target = path.slice('eightshift-pure:'.length);
324
+ if (byGroup.has(target)) {
325
+ return { path: target, namespace: 'eightshift-pure' };
326
+ }
327
+ });
328
+ builder.onResolve({ filter: importFilter }, async ({ path, importer, kind }) => {
329
+ if (kind !== 'import-statement') {
330
+ return;
331
+ }
332
+ const matches = inputs.get(importer)?.imports.filter((item) => item.original === path && item.kind === 'import-statement' && !item.external) ?? [];
333
+ if (matches.length !== 1) {
334
+ return;
335
+ }
336
+ const candidate = byPath.get(resolve(matches[0].path));
337
+ if (candidate && (await namedOnly(importer, path))) {
338
+ return { path: candidate.group.path, namespace: 'eightshift-pure' };
339
+ }
340
+ });
341
+ builder.onLoad({ filter: sourceFilter }, async ({ path }) => {
342
+ const candidate = byPath.get(path);
343
+ if (!candidate) {
344
+ return;
345
+ }
346
+ if ((await readFile(path, 'utf8')) !== candidate.member.source) {
347
+ throw new Error('Pure JSX source changed during compilation');
348
+ }
349
+ return { contents: `export { ${candidate.member.names.join(', ')} } from ${JSON.stringify(`eightshift-pure:${candidate.group.path}`)};`, loader: 'js', resolveDir: dirname(path) };
350
+ });
351
+ builder.onLoad({ filter: /.*/, namespace: 'eightshift-pure' }, async ({ path }) => {
352
+ const group = byGroup.get(path);
353
+ for (const member of group.members) {
354
+ if ((await readFile(member.path, 'utf8')) !== member.source) {
355
+ throw new Error('Pure JSX source changed during compilation');
356
+ }
357
+ }
358
+ return { contents: group.members.map(combine).join('\n'), loader: 'js', resolveDir: dirname(path) };
359
+ });
360
+ },
361
+ };
362
+ return {
363
+ plugin,
364
+ groups,
365
+ async verify(nextMetadata, nextResult) {
366
+ const next = await analyzeGraph({ result: nextResult, metadata: nextMetadata, directory, entries });
367
+ for (const [source, depth] of next.sourceDepths) {
368
+ if (!source.startsWith('eightshift-pure:') && !byPath.has(source) && depth < (sourceDepths.get(source) ?? Infinity)) {
369
+ throw new Error(`Grouping would advance non-grouped source evaluation: ${source}`);
370
+ }
371
+ }
372
+ for (const group of groups) {
373
+ const input = nextMetadata.inputs?.[`eightshift-pure:${group.path}`];
374
+ if (!input || !Array.isArray(input.imports) || !input.imports.length || input.imports.some((item) => item.original !== 'react/jsx-runtime' || item.path !== group.members[0].runtime || item.kind !== 'import-statement' || item.external)) {
375
+ throw new Error('Pure JSX runtime resolution changed during compilation');
376
+ }
377
+ }
378
+ },
379
+ summary: { maxBytes, groups: groups.map((group) => ({ source: `eightshift-pure:${group.path}`, members: group.members.map((member) => member.path), bytes: group.bytes, depth: group.members[0].depth, runtime: group.members[0].runtime })) },
380
+ };
381
+ }
package/bun/editor.mjs CHANGED
@@ -1,14 +1,31 @@
1
- import { mkdir, writeFile } from 'node:fs/promises';
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
3
  import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
3
4
  import { eightshiftDiscovery, editorLazyImports } from './eightshift-discovery.mjs';
5
+ import { buildNativeEditorChunks } from './editor-native.mjs';
4
6
 
5
7
  /**
6
- * Build a synchronous classic entry and lazy ESM chunks. Discovery, when
8
+ * Build classic registration with lazy ESM modules, or a unified ESM graph. Discovery, when
7
9
  * supplied, is composed with lazy rewriting so both can process one file.
8
10
  * Other onLoad plugins that consume the same file must compose the rewrite.
9
11
  * Editor output must not require extracted CSS or other emitted assets.
12
+ * sharing: 'native' compiles lazy targets as one ESM graph, separate from
13
+ * synchronous registration. 'unified' includes registration in the ESM graph
14
+ * and requires module-aware PHP readiness integration. The default is independent.
10
15
  */
11
- export async function buildEditor({ root, directory, entry, buildOptions = {}, plugins = [], chunkDir = 'editor-chunks', filename = 'editor.js', scriptUrlIdentifier = '__eightshiftEditorScriptUrl', discovery, lazy = {} }) {
16
+ export async function buildEditor({ root, directory, entry, buildOptions = {}, plugins = [], chunkDir = 'editor-chunks', filename = 'editor.js', scriptUrlIdentifier = '__eightshiftEditorScriptUrl', discovery, lazy = {}, sharedPackages, sharing = 'independent', pureJsxGroups = false }) {
17
+ if (!['independent', 'native', 'unified'].includes(sharing)) {
18
+ throw new TypeError('editor.sharing must be "independent", "native" or "unified"');
19
+ }
20
+ if (pureJsxGroups !== false && (!pureJsxGroups || typeof pureJsxGroups !== 'object' || Array.isArray(pureJsxGroups) || Object.keys(pureJsxGroups).some((key) => key !== 'maxBytes') || !Number.isSafeInteger(pureJsxGroups.maxBytes) || pureJsxGroups.maxBytes < 1 || pureJsxGroups.maxBytes > 65536)) {
21
+ throw new TypeError('editor.pureJsxGroups must be false or { maxBytes: integer between 1 and 65536 }');
22
+ }
23
+ if (pureJsxGroups && sharing !== 'unified') {
24
+ throw new TypeError('editor.pureJsxGroups requires unified sharing');
25
+ }
26
+ if (sharedPackages !== undefined) {
27
+ throw new TypeError('editor.sharedPackages was removed; use native or unified sharing after checking their initialization and readiness requirements');
28
+ }
12
29
  const inside = (path) => {
13
30
  if (typeof path !== 'string' || !path || isAbsolute(path)) {
14
31
  throw new TypeError('Editor output paths must be relative');
@@ -39,13 +56,58 @@ export async function buildEditor({ root, directory, entry, buildOptions = {}, p
39
56
  throw new TypeError('Editor sourcemap must be "none" or "external"');
40
57
  }
41
58
 
59
+ if (sharing === 'unified') {
60
+ if (!/^[$A-Z_a-z][$\w]*$/.test(scriptUrlIdentifier)) {
61
+ throw new TypeError('Invalid editor script URL identifier');
62
+ }
63
+ if (Object.keys(lazy).length) {
64
+ throw new TypeError('Unified editor sharing uses native imports and cannot apply lazy import rewriting');
65
+ }
66
+ const target = resolve(root, entry);
67
+ const nativeDiscovery = discovery ? eightshiftDiscovery({ ...discovery, root, outputDir: inside(discovery.outputDir ?? 'discovery') }) : undefined;
68
+ const {
69
+ names,
70
+ outputs,
71
+ pureJsxGroups: grouping,
72
+ } = await buildNativeEditorChunks({
73
+ pureJsxGroups,
74
+ chunks: new Map([[target, 'entry']]),
75
+ directory: chunkOutput,
76
+ entryOutput,
77
+ scriptUrlIdentifier,
78
+ buildOptions: { ...buildOptions, loader: { ...buildOptions.loader, '.svg': 'text' }, sourcemap: buildOptions.sourcemap ?? 'none' },
79
+ plugins: [...(nativeDiscovery ? [nativeDiscovery] : []), ...plugins],
80
+ });
81
+ const paths = [];
82
+ await mkdir(chunkOutput, { recursive: true });
83
+ for (const output of outputs) {
84
+ let contents = Buffer.from(await output.arrayBuffer());
85
+ if (output.sourcemap) {
86
+ contents = Buffer.from(`${await output.text()}\n//# sourceMappingURL=${basename(output.sourcemap.path)}\n`);
87
+ }
88
+ await writeFile(output.path, contents);
89
+ paths.push(output.path);
90
+ }
91
+ let imported = relative(dirname(entryOutput), resolve(chunkOutput, names.get(target)))
92
+ .split(sep)
93
+ .join('/');
94
+ if (!imported.startsWith('.')) {
95
+ imported = `./${imported}`;
96
+ }
97
+ const source = `import ${JSON.stringify(imported)};\nconst readiness = globalThis.eightshiftEditorModules;\nif (readiness?.version !== 1 || typeof readiness.complete !== 'function') throw new Error('Unified editor requires the Eightshift module readiness integration');\nreadiness.complete(import.meta.url);\n`;
98
+ await writeFile(entryOutput, source);
99
+ paths.push(entryOutput);
100
+ return { entry: entryOutput, paths, format: 'module', readiness: 'eightshift-editor-v1', ...(grouping ? { pureJsxGroups: grouping } : {}) };
101
+ }
102
+
42
103
  const chunks = new Map();
43
- const lazyImports = editorLazyImports({ ...lazy, root, chunks, chunkDir, scriptUrlIdentifier });
104
+ const lazyImports = editorLazyImports({ ...lazy, root, chunks, chunkDir, scriptUrlIdentifier, versioned: sharing !== 'native' });
44
105
  const discoveryPlugin = discovery ? eightshiftDiscovery({ ...discovery, root, outputDir: inside(discovery.outputDir ?? 'discovery'), transformSource: (source, path) => lazyImports.transformSource(discovery.transformSource ? discovery.transformSource(source, path) : source, path) }) : undefined;
45
106
  const sourcemap = buildOptions.sourcemap === 'external';
46
107
  const options = {
47
108
  target: 'browser',
48
109
  ...buildOptions,
110
+ ...(sharing === 'native' ? { minChunkSize: undefined } : {}),
49
111
  loader: { ...buildOptions.loader, '.svg': 'text' },
50
112
  sourcemap: sourcemap ? 'external' : 'none',
51
113
  entrypoints: [resolve(root, entry)],
@@ -79,27 +141,75 @@ export async function buildEditor({ root, directory, entry, buildOptions = {}, p
79
141
  await writeFile(path, source);
80
142
  paths.push(path);
81
143
  };
82
- const entryBuild = await compile(resolve(root, entry), 'iife');
144
+ let entryBuild = await compile(resolve(root, entry), 'iife');
83
145
  const entryMap = `${basename(entryOutput)}.map`;
84
- await write(entryOutput, `((${scriptUrlIdentifier}) => {\n${entryBuild.source}\n})(document.currentScript.src);\n${entryBuild.map ? `//# sourceMappingURL=${entryMap}\n` : ''}`);
85
- if (entryBuild.map) {
86
- await write(`${entryOutput}.map`, JSON.stringify(entryBuild.map));
146
+ if (sharing === 'native') {
147
+ if (chunks.size) {
148
+ const nativeDiscovery = discovery ? eightshiftDiscovery({ ...discovery, root, outputDir: inside(discovery.outputDir ?? 'discovery') }) : undefined;
149
+ const { names, outputs } = await buildNativeEditorChunks({
150
+ chunks,
151
+ directory: chunkOutput,
152
+ entryOutput,
153
+ scriptUrlIdentifier,
154
+ buildOptions: { ...buildOptions, loader: options.loader, sourcemap: options.sourcemap },
155
+ plugins: [...(nativeDiscovery ? [nativeDiscovery] : []), ...plugins],
156
+ });
157
+ for (const [target, name] of names) {
158
+ chunks.set(target, name);
159
+ }
160
+ // Compile against final URLs rather than rewriting code after source-map generation.
161
+ entryBuild = await compile(resolve(root, entry), 'iife');
162
+ if (chunks.size !== names.size) {
163
+ throw new Error('Editor lazy entries changed during native compilation');
164
+ }
165
+ for (const output of outputs) {
166
+ if (output.sourcemap) {
167
+ await write(output.path, `${await output.text()}\n//# sourceMappingURL=${basename(output.sourcemap.path)}\n`);
168
+ } else {
169
+ await write(output.path, Buffer.from(await output.arrayBuffer()));
170
+ }
171
+ }
172
+ }
173
+ await write(entryOutput, `((${scriptUrlIdentifier}) => {\n${entryBuild.source}\n})(document.currentScript.src);\n${entryBuild.map ? `//# sourceMappingURL=${entryMap}\n` : ''}`);
174
+ if (entryBuild.map) {
175
+ await write(`${entryOutput}.map`, JSON.stringify(entryBuild.map));
176
+ }
177
+ return { entry: entryOutput, paths };
87
178
  }
88
179
 
180
+ const lazyPaths = [];
181
+
89
182
  for (const [target, name] of chunks) {
90
183
  const output = inside(`${chunkDir}/${name}`);
91
184
  let entryPath = relative(dirname(output), entryOutput).split(sep).join('/');
92
-
93
185
  if (!entryPath.startsWith('.')) {
94
186
  entryPath = `./${entryPath}`;
95
187
  }
96
-
97
188
  const chunk = await compile(target, 'esm');
98
189
  await write(output, `const ${scriptUrlIdentifier} = new URL(${JSON.stringify(entryPath)}, import.meta.url).href;\n${chunk.source}${chunk.map ? `\n//# sourceMappingURL=${basename(output)}.map\n` : ''}`);
190
+ lazyPaths.push(output);
99
191
  if (chunk.map) {
100
192
  await write(`${output}.map`, JSON.stringify(chunk.map));
101
193
  }
102
194
  }
103
195
 
196
+ const digest = createHash('sha256').update(entryBuild.source);
197
+ const contents = new Map();
198
+ for (const path of lazyPaths.sort()) {
199
+ const source = await readFile(path, 'utf8');
200
+ contents.set(path, source);
201
+ digest.update(path.slice(directory.length)).update('\0').update(source).update('\0');
202
+ }
203
+ const version = digest.digest('hex').slice(0, 20);
204
+ const withVersion = (source) => source.replaceAll('?v=00000000000000000000', `?v=${version}`);
205
+ for (const [path, source] of contents) {
206
+ await writeFile(path, withVersion(source));
207
+ }
208
+
209
+ await write(entryOutput, `((${scriptUrlIdentifier}) => {\n${withVersion(entryBuild.source)}\n})(document.currentScript.src);\n${entryBuild.map ? `//# sourceMappingURL=${entryMap}\n` : ''}`);
210
+ if (entryBuild.map) {
211
+ await write(`${entryOutput}.map`, JSON.stringify(entryBuild.map));
212
+ }
213
+
104
214
  return { entry: entryOutput, paths };
105
215
  }
@@ -4,6 +4,7 @@ import { readFile } from 'node:fs/promises';
4
4
  import { createRequire } from 'node:module';
5
5
  import { dirname, resolve, relative, sep } from 'node:path';
6
6
  import { generateDiscovery } from './discovery.mjs';
7
+ import { allowPureJsxGrouping } from './plugin-capabilities.mjs';
7
8
 
8
9
  /**
9
10
  * Migrate literal webpack require.context calls in selected source files.
@@ -12,7 +13,7 @@ import { generateDiscovery } from './discovery.mjs';
12
13
  * omitContexts to match contexts handled separately (for example CSS).
13
14
  * Template-literal imports and nonliteral require.context calls are not rewritten.
14
15
  */
15
- export function eightshiftDiscovery({ root, outputDir, filter = /\.[cm]?jsx?$/, lazyContexts = () => false, omitContexts = () => false, transformSource = (source) => source } = {}) {
16
+ export function eightshiftDiscovery({ root, outputDir, filter = /\.[cm]?jsx?$/, lazyContexts = () => false, omitContexts = () => false, transformSource } = {}) {
16
17
  if (!root || !outputDir) {
17
18
  throw new TypeError('root and outputDir are required');
18
19
  }
@@ -20,7 +21,7 @@ export function eightshiftDiscovery({ root, outputDir, filter = /\.[cm]?jsx?$/,
20
21
  outputDir = resolve(root, outputDir);
21
22
  root = realpathSync(root);
22
23
 
23
- return {
24
+ const plugin = {
24
25
  name: 'eightshift-discovery',
25
26
  setup(builder) {
26
27
  builder.onLoad({ filter }, async ({ path }) => {
@@ -81,21 +82,24 @@ export function eightshiftDiscovery({ root, outputDir, filter = /\.[cm]?jsx?$/,
81
82
  contents = `import { ${definitions.map(({ name }) => name).join(', ')} } from ${JSON.stringify(output)};\n${contents}`;
82
83
  }
83
84
 
84
- contents = transformSource(contents, path);
85
+ contents = transformSource ? transformSource(contents, path) : contents;
85
86
 
86
87
  return { contents, loader: 'jsx', resolveDir: dirname(path) };
87
88
  });
88
89
  },
89
90
  };
91
+ return transformSource ? plugin : allowPureJsxGrouping(plugin);
90
92
  }
91
93
 
92
94
  /** Rewrite literal relative dynamic imports for a synchronous IIFE editor build.
93
- * Build each collected target as an ESM entry with the same plugin, then wrap
94
- * the IIFE in a function receiving scriptUrlIdentifier from currentScript.src.
95
- * Chunk URLs are relative to that script. The caller owns chunk output/builds.
95
+ * Build collected targets as ESM entries, then wrap the IIFE in a function
96
+ * receiving scriptUrlIdentifier from currentScript.src. Chunk URLs are relative
97
+ * to that script. The caller owns chunk output/builds.
96
98
  * Pass transformSource to eightshiftDiscovery to compose both onLoad hooks.
99
+ * Existing chunks Map names are reused. Set versioned: false when those names
100
+ * already contain content hashes, as in native editor sharing.
97
101
  */
98
- export function editorLazyImports({ root, chunks, chunkDir = 'editor-chunks', scriptUrlIdentifier = '__eightshiftEditorScriptUrl', filter = /\.[cm]?jsx?$/, include = (path) => !path.split(sep).includes('node_modules') } = {}) {
102
+ export function editorLazyImports({ root, chunks, chunkDir = 'editor-chunks', scriptUrlIdentifier = '__eightshiftEditorScriptUrl', filter = /\.[cm]?jsx?$/, include = (path) => !path.split(sep).includes('node_modules'), versioned = true } = {}) {
99
103
  if (!root || !(chunks instanceof Map) || !/^[$A-Z_a-z][$\w]*$/.test(scriptUrlIdentifier)) {
100
104
  throw new TypeError('Expected root, chunks Map and valid script URL identifier');
101
105
  }
@@ -107,11 +111,12 @@ export function editorLazyImports({ root, chunks, chunkDir = 'editor-chunks', sc
107
111
  ? source
108
112
  : source.replace(/import\(\s*(?:\/\*[\s\S]*?\*\/\s*)?(['"])(\.[^'"\n]+)\1\s*\)/g, (_match, _quote, specifier) => {
109
113
  const target = require.resolve(resolve(dirname(path), specifier));
110
- const name = `${createHash('sha256').update(relative(root, target)).digest('hex').slice(0, 20)}.js`;
114
+ const name = chunks.get(target) ?? `${createHash('sha256').update(relative(root, target)).digest('hex').slice(0, 20)}.js`;
111
115
 
112
116
  chunks.set(target, name);
117
+ const version = versioned ? '?v=00000000000000000000' : '';
113
118
 
114
- return `import(new URL(${JSON.stringify(`${chunkDir}/${name}`)}, ${scriptUrlIdentifier}).href)`;
119
+ return `import(new URL(${JSON.stringify(`${chunkDir}/${name}${version}`)}, ${scriptUrlIdentifier}).href)`;
115
120
  });
116
121
  const plugin = {
117
122
  name: 'eightshift-editor-lazy-imports',