@wavemaker/rn-codegen 11.16.0-rc.647821 → 11.16.1-rc.647845

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 (142) hide show
  1. package/command.js +111 -269
  2. package/command.js.map +1 -1
  3. package/index.js +1 -1
  4. package/index.js.map +1 -1
  5. package/npm-shrinkwrap.json +4840 -3624
  6. package/package-lock.json +4840 -3624
  7. package/package.json +62 -42
  8. package/src/app.generator.js +249 -87
  9. package/src/app.generator.js.map +1 -1
  10. package/src/fomatter.js.map +1 -1
  11. package/src/handlebar-helpers.js.map +1 -1
  12. package/src/increment-builder.js.map +1 -1
  13. package/src/pipeline/build-common.js +63 -0
  14. package/src/pipeline/build-common.js.map +1 -0
  15. package/src/pipeline/build-pipeline.js +152 -0
  16. package/src/pipeline/build-pipeline.js.map +1 -0
  17. package/src/pipeline/generation-store.js +288 -0
  18. package/src/pipeline/generation-store.js.map +1 -0
  19. package/src/pipeline/shared-node-modules.js +775 -0
  20. package/src/pipeline/shared-node-modules.js.map +1 -0
  21. package/src/pipeline/web-preview-templates.js +80 -0
  22. package/src/pipeline/web-preview-templates.js.map +1 -0
  23. package/src/pipeline/working-set.js +103 -0
  24. package/src/pipeline/working-set.js.map +1 -0
  25. package/src/profiles/legacy-web-preview.profile.js +15 -0
  26. package/src/profiles/legacy-web-preview.profile.js.map +1 -0
  27. package/src/project.service.js +17 -7
  28. package/src/project.service.js.map +1 -1
  29. package/src/templates/babel.config.js.template +0 -1
  30. package/src/templates/bootstrap.template +3 -1
  31. package/src/templates/device-plugin-service.template +7 -9
  32. package/src/templates/package.web.json +108 -83
  33. package/src/templates/page-stub.template +27 -0
  34. package/src/templates/project/app.json +4 -11
  35. package/src/templates/project/esbuild/esbuild.script.js +129 -89
  36. package/src/templates/project/metro/container-limits.js +195 -0
  37. package/src/templates/project/metro/metro.script.js +833 -0
  38. package/src/templates/project/metro/module-path.js +237 -0
  39. package/src/templates/project/metro/split.serializer.js +184 -0
  40. package/src/templates/project/metro/split.static.js +633 -0
  41. package/src/templates/project/metro/stable-module-ids.js +54 -0
  42. package/src/templates/project/metro/vendor-cache.js +475 -0
  43. package/src/templates/project/metro/wm-boundary.js +138 -0
  44. package/src/templates/project/metro/wm-crawl-override.js +147 -0
  45. package/src/templates/project/metro/wm-fastbuild.js +196 -0
  46. package/src/templates/project/metro/wm-live-reload.js +482 -0
  47. package/src/templates/project/metro/wm-metro-adapter.js +25 -0
  48. package/src/templates/project/metro.config.js +209 -8
  49. package/src/templates/project/package.json +106 -83
  50. package/src/templates/project/patch-utils.js +331 -0
  51. package/src/templates/project/scripts/post-build.js +3 -0
  52. package/src/theme/app-override-css.generator.js +10 -4
  53. package/src/theme/app-override-css.generator.js.map +1 -1
  54. package/src/theme/components/basic/base.styledef.js.map +1 -1
  55. package/src/theme/components/style-definition.provider.js.map +1 -1
  56. package/src/theme/font-stylesheet.transpiler.js +17 -7
  57. package/src/theme/font-stylesheet.transpiler.js.map +1 -1
  58. package/src/theme/rn-stylesheet.transpiler.js +17 -7
  59. package/src/theme/rn-stylesheet.transpiler.js.map +1 -1
  60. package/src/theme/theme.service.js +7 -19
  61. package/src/theme/theme.service.js.map +1 -1
  62. package/src/theme/token.transpiler.js +17 -7
  63. package/src/theme/token.transpiler.js.map +1 -1
  64. package/src/transpile/bind.ex.transformer.js +36 -23
  65. package/src/transpile/bind.ex.transformer.js.map +1 -1
  66. package/src/transpile/components/advanced/carousel.transformer.js.map +1 -1
  67. package/src/transpile/components/advanced/customwidget.transformer.js.map +1 -1
  68. package/src/transpile/components/advanced/login.transformer.js.map +1 -1
  69. package/src/transpile/components/advanced/webview.transformer.js.map +1 -1
  70. package/src/transpile/components/basic/buttongroup.transformer.js.map +1 -1
  71. package/src/transpile/components/basic/custom.transformer.js.map +1 -1
  72. package/src/transpile/components/basic/picture.transformer.js.map +1 -1
  73. package/src/transpile/components/basic/progress-bar.transformer.js.map +1 -1
  74. package/src/transpile/components/basic/search.transformer.js.map +1 -1
  75. package/src/transpile/components/chart/area-chart.transformer.js.map +1 -1
  76. package/src/transpile/components/container/accordion/accordionpane.transformer.js.map +1 -1
  77. package/src/transpile/components/container/accordion.transformer.js.map +1 -1
  78. package/src/transpile/components/container/container.transformer.js.map +1 -1
  79. package/src/transpile/components/container/layoutgrid/gridcolumn.transformer.js.map +1 -1
  80. package/src/transpile/components/container/layoutgrid/gridrow.transformer.js.map +1 -1
  81. package/src/transpile/components/container/layoutgrid.transformer.js.map +1 -1
  82. package/src/transpile/components/container/linearlayout.transformer.js.map +1 -1
  83. package/src/transpile/components/container/panel.transformer.js.map +1 -1
  84. package/src/transpile/components/container/tabs/tabpane.transformer.js.map +1 -1
  85. package/src/transpile/components/container/tabs.transformer.js.map +1 -1
  86. package/src/transpile/components/container/wizard/wizardstep.transformer.js.map +1 -1
  87. package/src/transpile/components/container/wizard.transformer.js.map +1 -1
  88. package/src/transpile/components/data/card/card-content.transformer.js.map +1 -1
  89. package/src/transpile/components/data/form/form-action.transformer.js.map +1 -1
  90. package/src/transpile/components/data/form/form-field.transformer.js.map +1 -1
  91. package/src/transpile/components/data/form.transformer.js.map +1 -1
  92. package/src/transpile/components/data/list.transformer.js +17 -7
  93. package/src/transpile/components/data/list.transformer.js.map +1 -1
  94. package/src/transpile/components/data/liveform.transformer.js.map +1 -1
  95. package/src/transpile/components/dialogs/dialog.transformer.js.map +1 -1
  96. package/src/transpile/components/input/checkboxset.transformer.js.map +1 -1
  97. package/src/transpile/components/input/chips.transformer.js.map +1 -1
  98. package/src/transpile/components/input/epoch/date.transformer.js.map +1 -1
  99. package/src/transpile/components/input/epoch/datetime.transformer.js.map +1 -1
  100. package/src/transpile/components/input/epoch/time.transformer.js.map +1 -1
  101. package/src/transpile/components/input/radioset.transformer.js.map +1 -1
  102. package/src/transpile/components/input/rating.transformer.js.map +1 -1
  103. package/src/transpile/components/input/select.transformer.js.map +1 -1
  104. package/src/transpile/components/input/slider.transformer.js.map +1 -1
  105. package/src/transpile/components/input/switch.transformer.js.map +1 -1
  106. package/src/transpile/components/input/textarea.transformer.js.map +1 -1
  107. package/src/transpile/components/input/toggle.transformer.js.map +1 -1
  108. package/src/transpile/components/navigation/appnavbar.transformer.js.map +1 -1
  109. package/src/transpile/components/navigation/menu.transformer.js.map +1 -1
  110. package/src/transpile/components/navigation/navbar.transformer.js.map +1 -1
  111. package/src/transpile/components/navigation/navitem.transformer.js.map +1 -1
  112. package/src/transpile/components/navigation/popover.transformer.js.map +1 -1
  113. package/src/transpile/components/page/left-panel.transformer.js.map +1 -1
  114. package/src/transpile/components/page/page.transformer.js.map +1 -1
  115. package/src/transpile/components/page/partial-container.transformer.js +17 -7
  116. package/src/transpile/components/page/partial-container.transformer.js.map +1 -1
  117. package/src/transpile/components/prefab/prefab.transformer.js.map +1 -1
  118. package/src/transpile/components/utils.js.map +1 -1
  119. package/src/transpile/property/property-parser.js.map +1 -1
  120. package/src/transpile/property/show-in-device.parser.js.map +1 -1
  121. package/src/transpile/style/background-image.parser.js.map +1 -1
  122. package/src/transpile/style/dimension-style.parser.js.map +1 -1
  123. package/src/transpile/style/multi-dimension-style.parser.js.map +1 -1
  124. package/src/transpile/style/numeric-style.parser.js.map +1 -1
  125. package/src/transpile/style.transformer.js.map +1 -1
  126. package/src/transpile/transpile.js +17 -7
  127. package/src/transpile/transpile.js.map +1 -1
  128. package/src/utils.js +8 -1
  129. package/src/utils.js.map +1 -1
  130. package/src/variables/variable.transformer.js.map +1 -1
  131. package/src/wm-namespace.js +14 -0
  132. package/src/wm-namespace.js.map +1 -0
  133. package/test/pipeline/live-reload-pacing.test.js +76 -0
  134. package/test/pipeline/live-reload-pacing.test.js.map +1 -0
  135. package/test/pipeline/npm-install-retry.test.js +57 -0
  136. package/test/pipeline/npm-install-retry.test.js.map +1 -0
  137. package/test/pipeline/repair-vendor-packages.test.js +134 -0
  138. package/test/pipeline/repair-vendor-packages.test.js.map +1 -0
  139. package/test/pipeline/web-preview-files.test.js +48 -0
  140. package/test/pipeline/web-preview-files.test.js.map +1 -0
  141. package/web-preview.js +165 -0
  142. package/web-preview.js.map +1 -0
@@ -0,0 +1,633 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const crypto = require('crypto');
5
+ const fs = require('fs-extra');
6
+
7
+ const { getVendorManifest, setVendorManifest } = require('./split.serializer');
8
+ const vendorCache = require('./vendor-cache');
9
+ const { normalizeKey, parseSourceUrl, expoAssetCacheFile } = require('./module-path');
10
+
11
+ const SOURCE_URL = (graph, split) =>
12
+ `http://localhost/index.bundle?platform=${graph.transformOptions?.platform ?? 'web'}&dev=${graph.transformOptions?.dev ?? false}&__split=${split}`;
13
+
14
+ // Content-hash filename, replacing @expo/metro-config's internal fileNameFromContents.
15
+ const contentHashFilename = (name, source) => {
16
+ const hash = crypto.createHash('md5').update(source).digest('hex').slice(0, 8);
17
+ return `./${hash}-${name}.js`;
18
+ };
19
+
20
+ function isStaticExport(options) {
21
+ if (options.serializerOptions?.output === 'static') {
22
+ return true;
23
+ }
24
+ const url = parseSourceUrl(options.sourceUrl);
25
+ return url?.searchParams.get('serializer.output') === 'static';
26
+ }
27
+
28
+ async function bundle(serializer, split, entry, pre, graph, options) {
29
+ const result = await serializer(entry, pre, graph, {
30
+ ...options,
31
+ sourceUrl: SOURCE_URL(graph, split),
32
+ });
33
+ return typeof result === 'string'
34
+ ? { code: result, map: null }
35
+ : { code: result.code, map: result.map ?? null };
36
+ }
37
+
38
+ const withMapRef = (code, jsFilename) =>
39
+ `${code}\n//# sourceMappingURL=${path.basename(jsFilename)}.map\n`;
40
+
41
+ const finalizeChunk = (name, code) => {
42
+ const filename = contentHashFilename(name, code);
43
+ return { filename, source: withMapRef(code, filename) };
44
+ };
45
+
46
+ const mapArtifact = (jsFilename, map, origin) => (map ? [{
47
+ filename: `${jsFilename}.map`,
48
+ originFilename: origin,
49
+ type: 'map',
50
+ metadata: {},
51
+ source: map,
52
+ }] : []);
53
+
54
+ // Expo's serializer costs ~650ms to produce ~5.8MB of JS chunks we discard outright; the only thing
55
+ // we keep from it is the asset list, which changes only when an asset is added, removed or edited.
56
+ // This cache is project-local because asset descriptors carry absolute paths, unlike the shared
57
+ // vendor cache whose key deliberately omits projectRoot.
58
+
59
+ // Keyed on each asset module's generated code, which embeds the content hash — so a replaced image
60
+ // invalidates the entry even though its path is unchanged.
61
+ function computeExpoAssetSetHash(graph) {
62
+ const h = crypto.createHash('md5');
63
+ const rows = [];
64
+ for (const m of graph.dependencies.values()) {
65
+ const out = (m.output || []).find(o => o.type === 'js/module/asset');
66
+ if (out) {
67
+ rows.push(`${m.path}\u0000${out.data?.code ?? ''}`);
68
+ }
69
+ }
70
+ rows.sort();
71
+ h.update(rows.join('\u0001'));
72
+ return `${rows.length}-${h.digest('hex')}`;
73
+ }
74
+
75
+ function readExpoAssetCache(projectRoot, platform, hash) {
76
+ try {
77
+ const cached = fs.readJSONSync(path.join(projectRoot, expoAssetCacheFile(platform)));
78
+ const hashOk = hash === null || cached.hash === hash;
79
+ if (cached && hashOk && cached.platform === platform && Array.isArray(cached.assets)) {
80
+ return cached;
81
+ }
82
+ } catch {}
83
+ return null;
84
+ }
85
+
86
+ // The served manifest is the authoritative list of what the cached vendor chunk holds — the same
87
+ // list wm-boundary.js consults when deciding which modules are safe to stub.
88
+ function readServedKeys(file) {
89
+ try {
90
+ const webapp = process.env.WM_PROJECT_SRC ? path.resolve(process.env.WM_PROJECT_SRC) : null;
91
+ if (!webapp) { return null; }
92
+ const keys = fs.readJSONSync(path.join(webapp, 'rn-bundle', file));
93
+ return Array.isArray(keys) && keys.length ? keys : null;
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+
99
+ /* Boundary mode may only REUSE cached artefacts, never PRODUCE them: its graph is missing every
100
+ module behind a stubbed node_modules, so anything derived from it is silently truncated — and
101
+ once cached, that truncation outlives the build that made it. Throwing this makes
102
+ metro.script.js retry the build once with the boundary disabled (it matches on the marker), so a
103
+ refusal costs time and never correctness. `reason` is a full phrase, not a noun. */
104
+ function refuseBoundary(reason) {
105
+ const err = new Error(`WM_BOUNDARY_INVALID: ${reason} — retrying with a full traversal`);
106
+ err.wmBoundaryInvalid = true;
107
+ return err;
108
+ }
109
+
110
+ const readServedVendorKeys = () => readServedKeys('vendor-manifest.json');
111
+ const readServedExtrasKeys = () => readServedKeys('extras-manifest.json');
112
+
113
+ // De-duplicated: several module paths can share one key (e.g. two nested copies of the same package
114
+ // version), and the served manifests are key SETS. Without this a full build hashes 2630 keys while
115
+ // boundary mode hashes the manifest's 2581, so boundary never matched and every build retried in full.
116
+ const keySetHash = (keys) =>
117
+ crypto.createHash('md5').update([...new Set(keys)].sort().join('\n')).digest('hex');
118
+
119
+ // Everything wm-fastbuild.js needs to re-emit a changed module without walking the graph: its
120
+ // module id, its dependency ids in Metro's `d`-array order, and the dependency names it resolved
121
+ // to. A later edit that changes those names means resolution moved, so the fast path must bail.
122
+ const FAST_PATH_MANIFEST_FILE = '.wm-fastpath.json';
123
+
124
+ // Project-local record of which ids the vendor chunk depends on outside itself (see the vendor
125
+ // section below). Needed because boundary mode cannot see vendor's dependencies. Per platform, like
126
+ // the asset list: the Expo Go android export must not overwrite the web build's record.
127
+ const vendorExternFile = (platform) => `.wm-vendor-extern.${platform}.json`;
128
+
129
+ // md5 over the sorted module ids that vendor modules require but that live in another chunk.
130
+ // Unresolved (optional) requires carry no absolutePath and are skipped, exactly as Metro emits them
131
+ // as null in the dependency array.
132
+ function computeVendorExternHash(graph, createModuleId, isVendor) {
133
+ const extern = new Set();
134
+ for (const m of graph.dependencies.values()) {
135
+ if (!isVendor(m.path)) { continue; }
136
+ for (const d of m.dependencies.values()) {
137
+ if (d.absolutePath && !isVendor(d.absolutePath)) {
138
+ extern.add(String(createModuleId(d.absolutePath)));
139
+ }
140
+ }
141
+ }
142
+ return crypto.createHash('md5').update([...extern].sort().join('\n')).digest('hex');
143
+ }
144
+
145
+ // Which project modules the fast path may re-transform on its own.
146
+ // This is a WHITELIST on the output type, not a blacklist on the extension. The fast path re-runs
147
+ // Metro's JS transformer over the raw file, so anything Metro did not treat as plain JS blows up on
148
+ // the first byte — a design-token .ttf produced `Unexpected character` and killed the fast path on
149
+ // EVERY build of every design-token project, because those fonts are regenerated each theme build
150
+ // and so always look "changed". Assets carry output type 'js/module/asset' (their real bytes are
151
+ // never JS; Metro emits a small descriptor instead), and future non-JS kinds would be equally
152
+ // unparseable, so only an exact 'js/module' is accepted. Asset CONTENT changes still reach the
153
+ // browser: their descriptors live in the user/modified chunks a full build emits, and an added or
154
+ // removed asset already forces one via the expo-asset-list containment check.
155
+ function fastPathable(m) {
156
+ // Metro synthesises virtual modules with a NUL-prefixed path (e.g. '\0shim:react-native-web/...').
157
+ // They have no file on disk, so they can never be the thing an editor changed — skip them rather
158
+ // than letting readFileSync throw and lose the whole manifest.
159
+ if (m.path.charCodeAt(0) === 0) { return 'virtual'; }
160
+ try { if (!fs.existsSync(m.path)) { return 'virtual'; } } catch { return 'virtual'; }
161
+ if (!(m.output || []).some(o => o.type === 'js/module')) { return 'non-js'; }
162
+ return 'ok';
163
+ }
164
+
165
+ function writeFastPathManifest(options, platform, srcModules, graph, entry, modifiedModules) {
166
+ // Only the web build has a fast path; the Expo Go export must not replace the web manifest.
167
+ if (process.env.WM_FASTPATH === '0' || platform !== 'web') { return; }
168
+ try {
169
+ const modules = {};
170
+ let virtualSkipped = 0;
171
+ let nonJsSkipped = 0;
172
+ // The `modified` chunk is an OVERRIDE layer: the user chunk already holds every project module,
173
+ // and `modified` wins only because it loads first (__d is first-registration-wins). So the fast
174
+ // path must re-emit this whole set, not just what changed since — dropping an entry silently
175
+ // reverts that file to its user-baseline version.
176
+ const overrideRel = (modifiedModules || [])
177
+ .filter(m => fastPathable(m) === 'ok')
178
+ .map(m => path.relative(options.projectRoot, m.path));
179
+ for (const m of srcModules) {
180
+ const verdict = fastPathable(m);
181
+ if (verdict === 'virtual') { virtualSkipped++; continue; }
182
+ if (verdict === 'non-js') { nonJsSkipped++; continue; }
183
+ const deps = [...m.dependencies.values()];
184
+ modules[path.relative(options.projectRoot, m.path)] = {
185
+ id: options.createModuleId(m.path),
186
+ // An unresolved (optional) dependency has no absolutePath; Metro emits null for it in the
187
+ // dependency map, so the manifest must too or createModuleId throws and no manifest is written.
188
+ depIds: deps.map(d => (d.absolutePath ? options.createModuleId(d.absolutePath) : null)),
189
+ // The Map is keyed by Metro's internal dependency key, not the import specifier — the
190
+ // specifier the transformer reports back lives at d.data.name.
191
+ depNames: deps.map(d => d.data?.name ?? null),
192
+ srcHash: crypto.createHash('md5').update(fs.readFileSync(m.path)).digest('hex'),
193
+ };
194
+ }
195
+ fs.writeJSONSync(path.join(options.projectRoot, FAST_PATH_MANIFEST_FILE), {
196
+ builtAt: Date.now(),
197
+ platform,
198
+ dev: !!graph.transformOptions?.dev,
199
+ // Metro composes the worker's options from these plus config.transformer.getTransformOptions();
200
+ // recording them here keeps the fast path off hardcoded guesses.
201
+ graphTransformOptions: graph.transformOptions ?? null,
202
+ entryModuleId: options.createModuleId(entry),
203
+ overrideRel,
204
+ moduleCount: Object.keys(modules).length,
205
+ modules,
206
+ });
207
+ if (virtualSkipped || nonJsSkipped) {
208
+ console.log(`[split] fast-path manifest: ${Object.keys(modules).length} modules `
209
+ + `(${virtualSkipped} virtual, ${nonJsSkipped} non-js skipped)`);
210
+ }
211
+ } catch (err) {
212
+ console.warn('[split] failed to write fast-path manifest:', err.message);
213
+ }
214
+ }
215
+
216
+ function writeExpoAssetCache(projectRoot, platform, hash, assets, nonJsArtifacts) {
217
+ try {
218
+ fs.writeJSONSync(path.join(projectRoot, expoAssetCacheFile(platform)), {
219
+ hash, platform, assets, nonJsArtifacts,
220
+ });
221
+ } catch (err) {
222
+ console.warn('[split] failed to cache expo asset list:', err.message);
223
+ }
224
+ }
225
+
226
+ module.exports.createExpoExportWrapper = (
227
+ expoSerializer,
228
+ splitSerializer,
229
+ metroConfig,
230
+ ) => async (entry, preModules, graph, options) => {
231
+
232
+ if (!isStaticExport(options)) {
233
+ return expoSerializer(entry, preModules, graph, options);
234
+ }
235
+
236
+ const platform = graph.transformOptions?.platform ?? 'web';
237
+ const boundaryMode = globalThis.__WM_BOUNDARY_ACTIVE__ === true;
238
+
239
+ // Run Expo's serializer as a black box for its non-JS output and asset list, discarding its JS
240
+ // bundle in favor of our own split — and skip it entirely when the asset set is unchanged.
241
+ const expoAssetHash = computeExpoAssetSetHash(graph);
242
+ const cachedExpoAssets = process.env.WM_EXPO_ASSET_CACHE === '0'
243
+ ? null
244
+ : readExpoAssetCache(options.projectRoot, platform, expoAssetHash);
245
+
246
+ let expoNonJsArtifacts;
247
+ let expoAssets;
248
+ // Boundary mode may not REGENERATE the asset list: its 159-module graph yields a short list
249
+ // (24 vs 57 — every vector-icon font missing) which would then be cached. But it also cannot match
250
+ // the cached entry's hash, which is computed from the FULL graph. So reuse the cached list by
251
+ // CONTAINMENT instead: every asset module the boundary graph can still see must already be in it.
252
+ // A newly added project image is therefore caught and falls back to a full build.
253
+ if (boundaryMode) {
254
+ const cachedAny = readExpoAssetCache(options.projectRoot, platform, null);
255
+ if (!cachedAny) { throw refuseBoundary('no cached expo asset list to reuse'); }
256
+ const covered = new Set();
257
+ for (const a of cachedAny.assets) { for (const f of a.files || []) { covered.add(f); } }
258
+ for (const m of graph.dependencies.values()) {
259
+ if (!(m.output || []).some(o => o.type === 'js/module/asset')) { continue; }
260
+ if (!covered.has(m.path)) { throw refuseBoundary(`asset ${path.basename(m.path)} is not in the cached expo asset list`); }
261
+ }
262
+ expoNonJsArtifacts = cachedAny.nonJsArtifacts ?? [];
263
+ expoAssets = cachedAny.assets;
264
+ console.log(`[split] boundary mode: reusing cached expo asset list (${expoAssets.length} assets)`);
265
+ } else if (cachedExpoAssets) {
266
+ expoNonJsArtifacts = cachedExpoAssets.nonJsArtifacts ?? [];
267
+ expoAssets = cachedExpoAssets.assets;
268
+ console.log(`[split] reusing cached expo asset list (${expoAssets.length} assets, expo serializer skipped)`);
269
+ } else {
270
+ const rawExpoResult = await expoSerializer(entry, preModules, graph, options);
271
+ const expoResult = typeof rawExpoResult === 'string' ? JSON.parse(rawExpoResult) : rawExpoResult;
272
+ expoNonJsArtifacts = (expoResult.artifacts ?? []).filter(a => a.type !== 'js');
273
+ expoAssets = expoResult.assets ?? [];
274
+ console.log(`[split] ran expo serializer for asset list (${expoAssets.length} assets, ${expoNonJsArtifacts.length} non-js artifacts)`);
275
+ writeExpoAssetCache(options.projectRoot, platform, expoAssetHash, expoAssets, expoNonJsArtifacts);
276
+ }
277
+
278
+ const dev = !!graph.transformOptions?.dev;
279
+ const origin = path.relative(options.projectRoot, entry);
280
+
281
+ // Under boundary traversal the graph holds only ~159 modules, so deriving the vendor set hash from
282
+ // it would miss and rebuild vendor from stubs. The hash is md5 over the SORTED NORMALIZED KEYS of
283
+ // baseline modules, and the served vendor-manifest.json is exactly that key list — verified to
284
+ // reproduce computeVendorSetHash's output byte for byte. So the cache key stays identical rather
285
+ // than the validity rule being weakened; the gate below is an ADDITIONAL check, not a replacement.
286
+ const servedVendorKeys = boundaryMode ? readServedVendorKeys() : null;
287
+
288
+ // Vendor membership = dependency closure of the baseline (vendor-cache.js computeChunkLayers).
289
+ // Boundary mode stubs vendor modules so the closure cannot be walked; the served manifest IS the
290
+ // closure recorded by the last full build, so membership comes from it instead.
291
+ const layers = boundaryMode ? null : vendorCache.computeChunkLayers(graph);
292
+ const vendorClosure = layers ? layers.vendor : null;
293
+ const servedVendorKeySet = servedVendorKeys ? new Set(servedVendorKeys) : null;
294
+ const inVendorChunk = (p) => (vendorClosure
295
+ ? vendorClosure.has(p)
296
+ : !!servedVendorKeySet && servedVendorKeySet.has(normalizeKey(p)));
297
+ options.wmChunkLayers = layers || undefined;
298
+
299
+ const vendorSetHash = servedVendorKeys
300
+ ? keySetHash(servedVendorKeys)
301
+ : keySetHash([...vendorClosure].map(p => normalizeKey(p)));
302
+
303
+ if (servedVendorKeys) {
304
+ // Anything wm-boundary.js did NOT stub was transformed for real and is in the graph. If such a
305
+ // module is a vendor module absent from the manifest, the cached chunk cannot contain it and the
306
+ // bundle would be missing a module at runtime — refuse rather than ship a broken preview.
307
+ const known = new Set(servedVendorKeys);
308
+ const missing = [];
309
+ for (const m of graph.dependencies.values()) {
310
+ if (!vendorCache.isBaselineModule(m.path)) { continue; }
311
+ const key = normalizeKey(m.path);
312
+ if (!known.has(key)) { missing.push(key); }
313
+ }
314
+ if (missing.length) {
315
+ const err = new Error(`WM_BOUNDARY_INVALID: ${missing.length} vendor module(s) not in the cached `
316
+ + `manifest (first: ${missing[0]}) — a full build is required`);
317
+ err.wmBoundaryInvalid = true;
318
+ throw err;
319
+ }
320
+ console.log(`[split] boundary mode: reusing ${servedVendorKeys.length}-key vendor manifest `
321
+ + `(graph carries ${graph.dependencies.size} modules)`);
322
+ }
323
+
324
+ // The vendor chunk is shared across projects, but it is NOT self-contained: vendor modules depend
325
+ // on modules that live in per-project chunks (measured on a real preview: 71 edges into extras,
326
+ // 13 into user — the user ones are the Metro-synthesised react-native-web shims). Those
327
+ // dependency ids are baked into the vendor bytes, yet the cache key only described WHICH modules
328
+ // vendor contains. A vendor built by project A could therefore be served to project B with the same
329
+ // vendor set, and B's runtime would require ids only A defines: "Requiring unknown module", thrown
330
+ // from vendor, different id each time, cured by the next rebuild. So the key now also covers the
331
+ // set of ids vendor reaches OUTSIDE itself.
332
+ // In boundary mode vendor modules are stubbed (no dependencies), so the fingerprint cannot be
333
+ // recomputed; it is recorded on every full traversal and reused, and boundary refuses without it.
334
+ const externFile = path.join(options.projectRoot, vendorExternFile(platform));
335
+ let vendorExternHash;
336
+ if (boundaryMode) {
337
+ let recorded = null;
338
+ try { recorded = fs.readJSONSync(externFile); } catch {}
339
+ if (!recorded || recorded.vendorSetHash !== vendorSetHash || !recorded.externHash) {
340
+ throw refuseBoundary('no recorded vendor dependency fingerprint for this vendor set');
341
+ }
342
+ vendorExternHash = recorded.externHash;
343
+ } else {
344
+ vendorExternHash = computeVendorExternHash(graph, options.createModuleId, inVendorChunk);
345
+ try { fs.writeJSONSync(externFile, { vendorSetHash, externHash: vendorExternHash }); } catch {}
346
+ }
347
+ const vendorKeyHash = `${vendorSetHash}|extern:${vendorExternHash}`;
348
+
349
+ // WM_BYPASS_CHUNK_CACHE=1 is set by metro.script.js when the publish gate caught an inconsistent
350
+ // chunk set: every cached chunk is rebuilt from this graph and the fresh result overwrites the
351
+ // cache entry, so a poisoned entry cannot survive the retry.
352
+ const bypassChunkCache = process.env.WM_BYPASS_CHUNK_CACHE === '1';
353
+ if (bypassChunkCache) {
354
+ console.log('[split] chunk caches bypassed — rebuilding vendor, extras and user from this graph');
355
+ }
356
+
357
+ const cacheHitFilenames = new Set();
358
+ const markHit = (filename) => cacheHitFilenames.add(path.basename(filename));
359
+
360
+ let vendor;
361
+ let vendorMap;
362
+ let vendorFilename;
363
+ let vendorCacheInfo = null; // { bundlePath, mapPath } — real on-disk cacache content paths
364
+
365
+ const cached = bypassChunkCache ? null
366
+ : await vendorCache.lookup(options.projectRoot, platform, dev, 'vendor', vendorKeyHash);
367
+ if (cached && cached.meta.filename) {
368
+ setVendorManifest(cached.meta.manifest || []);
369
+ vendorFilename = cached.meta.filename;
370
+ vendorCacheInfo = { bundlePath: cached.bundlePath, mapPath: cached.mapPath };
371
+ const vendorHardlinked = !!cached.bundlePath;
372
+ vendor = vendorHardlinked ? '' : cached.source;
373
+ vendorMap = vendorHardlinked ? null : cached.map;
374
+ markHit(vendorFilename);
375
+ console.log('[split] reusing cached vendor bundle (shared cache hit)');
376
+ } else if (boundaryMode) {
377
+ throw refuseBoundary('no cached vendor chunk to reuse');
378
+ } else {
379
+ console.log('[split] rebuilding vendor bundle (no shared cache entry)');
380
+ const built = await bundle(splitSerializer, 'vendor', entry, preModules, graph, options);
381
+ const fixedCode = built.code.replace(/(["'])\/assets\//g, '$1assets/');
382
+ ({ filename: vendorFilename, source: vendor } = finalizeChunk('vendor', fixedCode));
383
+ vendorMap = built.map;
384
+ try {
385
+ const key = vendorCache.computeKey(options.projectRoot, platform, dev, 'vendor', vendorKeyHash);
386
+ vendorCacheInfo = await vendorCache.store(key, platform, vendor, {
387
+ filename: vendorFilename,
388
+ manifest: getVendorManifest(),
389
+ platform,
390
+ }, 'vendor', vendorMap);
391
+ } catch (err) {
392
+ console.warn('[split] failed to cache vendor bundle:', err.message);
393
+ }
394
+ }
395
+
396
+ if (vendorCacheInfo?.bundlePath) {
397
+ try {
398
+ fs.writeJSONSync(path.join(options.projectRoot, '.wm-vendor-link.json'), {
399
+ cachePath: vendorCacheInfo.bundlePath,
400
+ mapPath: vendorCacheInfo.mapPath,
401
+ filename: vendorFilename,
402
+ platform,
403
+ });
404
+ } catch {}
405
+ }
406
+
407
+ // Virtual shims are not project code: they now live in vendor, and they have no file on disk, so
408
+ // keeping them here made them look "changed" on every build and re-emitted into modified.
409
+ const srcModules = [...graph.dependencies.values()]
410
+ .filter(m => vendorCache.isProjectSourceModule(m.path) && !inVendorChunk(m.path));
411
+
412
+ const userMeta = vendorCache.loadUserMeta(platform);
413
+ const forceFullRefresh = bypassChunkCache || vendorCache.shouldForceFullUserRefresh(userMeta);
414
+ const stableKeys = forceFullRefresh ? null : new Set(userMeta.stableKeys);
415
+
416
+ if (boundaryMode && !forceFullRefresh && userMeta && Array.isArray(userMeta.stableKeys)) {
417
+ const visible = new Set(srcModules.map(m => normalizeKey(m.path)));
418
+ const lost = userMeta.stableKeys.filter((k) => {
419
+ if (visible.has(k)) { return false; }
420
+ try { return fs.existsSync(k); } catch { return false; }
421
+ });
422
+ if (lost.length) {
423
+ throw refuseBoundary(`${lost.length} project module(s) are on disk but outside the boundary `
424
+ + `graph, e.g. ${path.basename(lost[0])}`);
425
+ }
426
+ }
427
+
428
+ const modifiedModules = stableKeys
429
+ ? srcModules.filter(m => !vendorCache.isStableModule(m.path, stableKeys, userMeta.builtAt, userMeta.stableHashes))
430
+ : [];
431
+
432
+ options.wmModifiedKeys = new Set(modifiedModules.map(m => normalizeKey(m.path)));
433
+
434
+ // Written here, not earlier, because it must record which modules this build put in the OVERRIDE
435
+ // chunk — the fast path has to keep re-emitting them or their edits revert to the user baseline.
436
+ writeFastPathManifest(options, platform, srcModules, graph, entry, modifiedModules);
437
+
438
+ let modifiedArtifact = null;
439
+ let modifiedMap = null;
440
+ if (modifiedModules.length) {
441
+ console.log(`[split] modified: ${modifiedModules.length} project file(s) changed since the cached user bundle was captured`);
442
+ const built = await bundle(splitSerializer, 'modified', entry, preModules, graph, options);
443
+ const { filename: modifiedFilename, source: modifiedSource } = finalizeChunk('modified', built.code);
444
+ modifiedMap = built.map;
445
+ modifiedArtifact = {
446
+ filename: modifiedFilename,
447
+ type: 'js',
448
+ metadata: { isAsync: false, requires: [], modulePaths: [] },
449
+ source: modifiedSource,
450
+ };
451
+ }
452
+
453
+ let user, userMap, userFilename;
454
+ if (forceFullRefresh) {
455
+ if (boundaryMode) { throw refuseBoundary('the user baseline may only be captured from a complete graph'); }
456
+ console.log('[split] rebuilding user bundle (full refresh'
457
+ + (userMeta ? `, ${userMeta.buildsSinceRefresh ?? 0} builds since last one` : ', no prior baseline')
458
+ + ')');
459
+ const builtAt = Date.now();
460
+ const built = await bundle(splitSerializer, 'user', entry, preModules, graph, options);
461
+ ({ filename: userFilename, source: user } = finalizeChunk('user', built.code));
462
+ userMap = built.map;
463
+ try {
464
+ vendorCache.storeUserBaseline(platform, userFilename, srcModules.map(m => normalizeKey(m.path)).sort(), builtAt);
465
+ } catch (err) {
466
+ console.warn('[split] failed to cache user bundle baseline:', err.message);
467
+ }
468
+ } else {
469
+ user = vendorCache.readCachedUserSource(userMeta);
470
+ userMap = vendorCache.readCachedUserMap(userMeta);
471
+ userFilename = userMeta.filename;
472
+ markHit(userFilename);
473
+ console.log(`[split] reusing cached user bundle (${(userMeta.buildsSinceRefresh ?? 0) + 1}/${vendorCache.USER_CACHE_REFRESH_INTERVAL} builds since last refresh)`);
474
+ try {
475
+ vendorCache.bumpUserBuildCount(platform, userMeta);
476
+ } catch (err) {
477
+ console.warn('[split] failed to update user cache build count:', err.message);
478
+ }
479
+ }
480
+
481
+ let extrasArtifact = null;
482
+ let extrasMapSource = null;
483
+ // Emitted as an artifact so a later boundary build has the same authoritative key list for extras
484
+ // that vendor-manifest.json already provides for vendor.
485
+ let emittedExtrasKeys = [];
486
+ // Extras = library modules outside vendor that never reach project code (computeChunkLayers).
487
+ const isExtrasChunk = (p) => !!layers && layers.extras.has(p);
488
+ if (vendorCache.extrasSplitEnabled()) {
489
+ const servedExtrasKeys = boundaryMode ? readServedExtrasKeys() : null;
490
+ const hasExtras = servedExtrasKeys
491
+ ? true
492
+ : [...graph.dependencies.values()].some(m => isExtrasChunk(m.path));
493
+ if (hasExtras) {
494
+ emittedExtrasKeys = servedExtrasKeys
495
+ || [...graph.dependencies.values()]
496
+ .filter(m => isExtrasChunk(m.path))
497
+ .map(m => normalizeKey(m.path))
498
+ .sort();
499
+ const extrasSetHash = servedExtrasKeys
500
+ ? keySetHash(servedExtrasKeys)
501
+ : keySetHash(emittedExtrasKeys);
502
+ const cachedExtras = bypassChunkCache ? null
503
+ : await vendorCache.lookup(options.projectRoot, platform, dev, 'extras', extrasSetHash);
504
+ let extras, extrasMap, extrasFilename;
505
+ if (cachedExtras) {
506
+ extras = cachedExtras.source;
507
+ extrasMap = cachedExtras.map;
508
+ extrasFilename = cachedExtras.meta.filename;
509
+ markHit(extrasFilename);
510
+ console.log('[split] reusing cached extras bundle (cache hit)');
511
+ } else if (boundaryMode) {
512
+ throw refuseBoundary('no cached extras chunk to reuse');
513
+ } else {
514
+ console.log('[split] rebuilding extras bundle (no cache entry)');
515
+ const built = await bundle(splitSerializer, 'extras', entry, preModules, graph, options);
516
+ ({ filename: extrasFilename, source: extras } = finalizeChunk('extras', built.code));
517
+ extrasMap = built.map;
518
+ try {
519
+ const key = vendorCache.computeKey(options.projectRoot, platform, dev, 'extras', extrasSetHash);
520
+ await vendorCache.store(key, platform, extras, { filename: extrasFilename, platform }, 'extras');
521
+ } catch (err) {
522
+ console.warn('[split] failed to cache extras bundle:', err.message);
523
+ }
524
+ }
525
+ extrasMapSource = extrasMap;
526
+ extrasArtifact = {
527
+ filename: extrasFilename,
528
+ type: 'js',
529
+ metadata: { isAsync: false, requires: [], modulePaths: [] },
530
+ source: extras,
531
+ };
532
+ }
533
+ }
534
+
535
+ let wmxArtifact = null;
536
+ let wmxMapSource = null;
537
+ const hasWmx = [...graph.dependencies.values()].some(m => vendorCache.isWmxModule(m.path));
538
+ if (hasWmx) {
539
+ const wmxContentHash = vendorCache.computeWmxContentHash(
540
+ [...graph.dependencies.values()].map(m => m.path),
541
+ );
542
+ const cachedWmx = await vendorCache.lookup(options.projectRoot, platform, dev, 'wmx', wmxContentHash);
543
+ let wmx, wmxMap, wmxFilename;
544
+ if (cachedWmx) {
545
+ wmx = cachedWmx.source;
546
+ wmxMap = cachedWmx.map;
547
+ wmxFilename = cachedWmx.meta.filename;
548
+ markHit(wmxFilename);
549
+ console.log('[split] reusing cached wmx bundle (cache hit)');
550
+ } else {
551
+ console.log('[split] rebuilding wmx bundle (no cache entry, or wmx-components changed)');
552
+ const built = await bundle(splitSerializer, 'wmx', entry, preModules, graph, options);
553
+ ({ filename: wmxFilename, source: wmx } = finalizeChunk('wmx', built.code));
554
+ wmxMap = built.map;
555
+ try {
556
+ const key = vendorCache.computeKey(options.projectRoot, platform, dev, 'wmx', wmxContentHash);
557
+ await vendorCache.store(key, platform, wmx, { filename: wmxFilename, platform }, 'wmx');
558
+ } catch (err) {
559
+ console.warn('[split] failed to cache wmx bundle:', err.message);
560
+ }
561
+ }
562
+ wmxMapSource = wmxMap;
563
+ wmxArtifact = {
564
+ filename: wmxFilename,
565
+ type: 'js',
566
+ metadata: { isAsync: false, requires: [], modulePaths: [] },
567
+ source: wmx,
568
+ };
569
+ }
570
+
571
+ const entryModuleId = options.createModuleId(entry);
572
+ const getRunModuleStatement = options.getRunModuleStatement
573
+ ?? ((moduleId) => `__r(${JSON.stringify(moduleId)});\n`);
574
+ const bootCode = getRunModuleStatement(entryModuleId);
575
+
576
+ return JSON.stringify({
577
+ artifacts: [
578
+ {
579
+ filename: vendorFilename,
580
+ originFilename: origin,
581
+ type: 'js',
582
+ metadata: { isAsync: false, requires: [], modulePaths: [] },
583
+ source: vendor,
584
+ },
585
+ ...mapArtifact(vendorFilename, vendorMap, origin),
586
+ ...(extrasArtifact ? [{ ...extrasArtifact, originFilename: origin }] : []),
587
+ ...(extrasArtifact ? mapArtifact(extrasArtifact.filename, extrasMapSource, origin) : []),
588
+ ...(wmxArtifact ? [{ ...wmxArtifact, originFilename: origin }] : []),
589
+ ...(wmxArtifact ? mapArtifact(wmxArtifact.filename, wmxMapSource, origin) : []),
590
+ // 'modified' MUST load before 'user' — Metro's __d() is first-registration-wins.
591
+ ...(modifiedArtifact ? [{ ...modifiedArtifact, originFilename: origin }] : []),
592
+ ...(modifiedArtifact ? mapArtifact(modifiedArtifact.filename, modifiedMap, origin) : []),
593
+ {
594
+ filename: userFilename,
595
+ originFilename: origin,
596
+ type: 'js',
597
+ metadata: { isAsync: false, requires: [], modulePaths: [] },
598
+ source: user,
599
+ },
600
+ ...mapArtifact(userFilename, userMap, origin),
601
+ {
602
+ filename: contentHashFilename('boot', bootCode),
603
+ originFilename: origin,
604
+ type: 'js',
605
+ metadata: { isAsync: false, requires: [], modulePaths: [] },
606
+ source: bootCode,
607
+ },
608
+ {
609
+ filename: 'extras-manifest.json',
610
+ originFilename: 'extras-manifest.json',
611
+ type: 'json',
612
+ metadata: {},
613
+ source: JSON.stringify(emittedExtrasKeys),
614
+ },
615
+ {
616
+ filename: 'vendor-manifest.json',
617
+ originFilename: 'vendor-manifest.json',
618
+ type: 'json',
619
+ metadata: {},
620
+ source: JSON.stringify(getVendorManifest()),
621
+ },
622
+ {
623
+ filename: 'wm-chunk-cache-hits.json',
624
+ originFilename: 'wm-chunk-cache-hits.json',
625
+ type: 'json',
626
+ metadata: {},
627
+ source: JSON.stringify([...cacheHitFilenames]),
628
+ },
629
+ ...expoNonJsArtifacts,
630
+ ],
631
+ assets: expoAssets,
632
+ });
633
+ };
@@ -0,0 +1,54 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const { stableIdKey } = require('./module-path');
5
+
6
+ // Fallback counter starts above the 48-bit hash space so it never aliases a real hash.
7
+ const FALLBACK_BASE = 0x1_0000_0000_0000;
8
+
9
+ // Hash-based module IDs so a shared vendor bundle and a project's user bundle agree on IDs — Metro's default sequential counter doesn't.
10
+ module.exports = function createStableModuleIdFactory() {
11
+ const fileToIdMap = new Map();
12
+ const keyToIdMap = new Map();
13
+ const idToKeyMap = new Map();
14
+ let fallbackCounter = FALLBACK_BASE;
15
+
16
+ return function stableModuleId(filePath) {
17
+ let id = fileToIdMap.get(filePath);
18
+ if (id != null) return id;
19
+
20
+ const key = stableIdKey(filePath);
21
+ const existingId = keyToIdMap.get(key);
22
+ if (existingId != null) {
23
+ fileToIdMap.set(filePath, existingId);
24
+ return existingId;
25
+ }
26
+
27
+ const hash = parseInt(
28
+ crypto.createHash('md5').update(key).digest('hex').slice(0, 12),
29
+ 16,
30
+ );
31
+
32
+ const existingKey = idToKeyMap.get(hash);
33
+
34
+ if (existingKey == null) {
35
+ id = hash;
36
+ } else {
37
+ // True hash collision: two different keys produced the same 48-bit prefix.
38
+ id = fallbackCounter++;
39
+ console.warn(
40
+ `[stable-module-ids] hash collision detected!\n` +
41
+ ` existing : ${existingKey}\n` +
42
+ ` collider : ${filePath}\n` +
43
+ ` key used : ${key}\n` +
44
+ ` hash : 0x${hash.toString(16)}\n` +
45
+ ` fallback : ${id}`,
46
+ );
47
+ }
48
+
49
+ fileToIdMap.set(filePath, id);
50
+ keyToIdMap.set(key, id);
51
+ idToKeyMap.set(id, key);
52
+ return id;
53
+ };
54
+ };