@tamagui/metro-plugin 2.7.7 → 3.0.0-beta.1097.1

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 (72) hide show
  1. package/README.md +12 -0
  2. package/dist/cjs/babel.cjs +76 -0
  3. package/dist/cjs/compilerCache.cjs +236 -0
  4. package/dist/cjs/diagnostics.cjs +40 -0
  5. package/dist/cjs/frontend.cjs +885 -0
  6. package/dist/cjs/index.cjs +113 -0
  7. package/dist/cjs/lowering.cjs +108 -0
  8. package/dist/cjs/metroResolver.cjs +196 -0
  9. package/dist/cjs/transformOptions.cjs +34 -0
  10. package/dist/cjs/transformer.cjs +146 -0
  11. package/dist/cjs/zeroRuntime.cjs +139 -0
  12. package/dist/cjs/zeroSerializer.cjs +149 -0
  13. package/dist/esm/babel.mjs +52 -0
  14. package/dist/esm/babel.mjs.map +1 -0
  15. package/dist/esm/compilerCache.mjs +212 -0
  16. package/dist/esm/compilerCache.mjs.map +1 -0
  17. package/dist/esm/diagnostics.mjs +18 -0
  18. package/dist/esm/diagnostics.mjs.map +1 -0
  19. package/dist/esm/frontend.mjs +855 -0
  20. package/dist/esm/frontend.mjs.map +1 -0
  21. package/dist/esm/index.mjs +76 -22
  22. package/dist/esm/index.mjs.map +1 -1
  23. package/dist/esm/lowering.mjs +89 -0
  24. package/dist/esm/lowering.mjs.map +1 -0
  25. package/dist/esm/metroResolver.mjs +173 -0
  26. package/dist/esm/metroResolver.mjs.map +1 -0
  27. package/dist/esm/transformOptions.mjs +14 -0
  28. package/dist/esm/transformOptions.mjs.map +1 -0
  29. package/dist/esm/transformer.mjs +124 -0
  30. package/dist/esm/transformer.mjs.map +1 -0
  31. package/dist/esm/zeroRuntime.mjs +105 -0
  32. package/dist/esm/zeroRuntime.mjs.map +1 -0
  33. package/dist/esm/zeroSerializer.mjs +123 -0
  34. package/dist/esm/zeroSerializer.mjs.map +1 -0
  35. package/package.json +33 -5
  36. package/src/babel.ts +87 -0
  37. package/src/compilerCache.ts +346 -0
  38. package/src/diagnostics.ts +47 -0
  39. package/src/frontend.ts +1216 -0
  40. package/src/index.ts +143 -14
  41. package/src/lowering.ts +136 -0
  42. package/src/metroResolver.ts +209 -0
  43. package/src/transformOptions.ts +36 -0
  44. package/src/transformer.ts +220 -0
  45. package/src/zeroRuntime.ts +212 -0
  46. package/src/zeroSerializer.ts +175 -0
  47. package/types/babel.d.ts +28 -0
  48. package/types/babel.d.ts.map +11 -0
  49. package/types/compilerCache.d.ts +63 -0
  50. package/types/compilerCache.d.ts.map +11 -0
  51. package/types/diagnostics.d.ts +16 -0
  52. package/types/diagnostics.d.ts.map +11 -0
  53. package/types/frontend.d.ts +73 -0
  54. package/types/frontend.d.ts.map +11 -0
  55. package/types/index.d.ts +49 -32
  56. package/types/index.d.ts.map +11 -1
  57. package/types/lowering.d.ts +20 -0
  58. package/types/lowering.d.ts.map +11 -0
  59. package/types/metroResolver.d.ts +21 -0
  60. package/types/metroResolver.d.ts.map +11 -0
  61. package/types/transformOptions.d.ts +13 -0
  62. package/types/transformOptions.d.ts.map +11 -0
  63. package/types/transformer.d.ts +28 -0
  64. package/types/transformer.d.ts.map +11 -0
  65. package/types/zeroRuntime.d.ts +75 -0
  66. package/types/zeroRuntime.d.ts.map +11 -0
  67. package/types/zeroSerializer.d.ts +6 -0
  68. package/types/zeroSerializer.d.ts.map +11 -0
  69. package/dist/cjs/index.js +0 -45
  70. package/dist/cjs/index.js.map +0 -6
  71. package/dist/esm/index.js +0 -25
  72. package/dist/esm/index.js.map +0 -1
@@ -0,0 +1,885 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all) __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true
11
+ });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: () => from[key],
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var frontend_exports = {};
28
+ __export(frontend_exports, {
29
+ METRO_RECORD_CACHE_VERSION: () => METRO_RECORD_CACHE_VERSION,
30
+ MetroCompilerFrontend: () => MetroCompilerFrontend,
31
+ describeMetroCompilerRoot: () => describeMetroCompilerRoot
32
+ });
33
+ module.exports = __toCommonJS(frontend_exports);
34
+ var import_node_fs = require("node:fs");
35
+ var import_promises = require("node:fs/promises");
36
+ var import_node_module = require("node:module");
37
+ var import_node_path = require("node:path");
38
+ var import_ignore = __toESM(require("ignore"), 1);
39
+ var import_compiler_core = require("@tamagui/compiler-core");
40
+ var import_static = __toESM(require("@tamagui/static"), 1);
41
+ var import_babel = require("./babel.cjs");
42
+ var import_zeroRuntime = require("./zeroRuntime.cjs");
43
+ var import_compilerCache = require("./compilerCache.cjs");
44
+ var import_diagnostics = require("./diagnostics.cjs");
45
+ var import_metroResolver = require("./metroResolver.cjs");
46
+ const import_meta = {};
47
+ const METRO_RECORD_CACHE_VERSION = 2;
48
+ function compareCodeUnits(left, right) {
49
+ return left < right ? -1 : left > right ? 1 : 0;
50
+ }
51
+ const requireFromFrontend = (0, import_node_module.createRequire)(typeof __filename === "string" ? __filename : import_meta.url);
52
+ const compilerImplementationVersions = [
53
+ "@tamagui/metro-plugin",
54
+ "@tamagui/static",
55
+ "@tamagui/compiler-core"
56
+ ].map((packageName) => {
57
+ const { version } = requireFromFrontend(`${packageName}/package.json`);
58
+ return `${packageName}@${version}`;
59
+ });
60
+ function scanOptionsHash(options, projectGeneration, projectSourcesHash) {
61
+ return (0, import_compiler_core.contentHash)(JSON.stringify({
62
+ options,
63
+ projectGeneration,
64
+ projectSourcesHash
65
+ }));
66
+ }
67
+ const speculativeWalkExcludedDirs = /* @__PURE__ */ new Set([
68
+ "__tests__",
69
+ "e2e",
70
+ "flows",
71
+ "plugins",
72
+ "screenshots",
73
+ "scripts",
74
+ "test",
75
+ "test-results",
76
+ "tests"
77
+ ]);
78
+ async function walkProjectSources(root) {
79
+ const inherited = [];
80
+ let ancestor = root;
81
+ while (!(0, import_node_fs.existsSync)((0, import_node_path.join)(ancestor, ".git"))) {
82
+ const parent = (0, import_node_path.dirname)(ancestor);
83
+ if (parent === ancestor) break;
84
+ inherited.unshift(parent);
85
+ ancestor = parent;
86
+ }
87
+ const rootScopes = [];
88
+ for (const dir of inherited) {
89
+ const source = await (0, import_promises.readFile)((0, import_node_path.join)(dir, ".gitignore"), "utf8").catch(() => null);
90
+ if (source) rootScopes.push({
91
+ dir,
92
+ matcher: (0, import_ignore.default)().add(source)
93
+ });
94
+ }
95
+ const found = [];
96
+ const stack = [{
97
+ dir: root,
98
+ scopes: rootScopes
99
+ }];
100
+ while (stack.length) {
101
+ const { dir, scopes } = stack.pop();
102
+ let entries;
103
+ try {
104
+ entries = await (0, import_promises.readdir)(dir, { withFileTypes: true });
105
+ } catch {
106
+ continue;
107
+ }
108
+ let active = scopes;
109
+ if (entries.some((entry) => entry.isFile() && entry.name === ".gitignore")) {
110
+ const source = await (0, import_promises.readFile)((0, import_node_path.join)(dir, ".gitignore"), "utf8").catch(() => null);
111
+ if (source) active = [...scopes, {
112
+ dir,
113
+ matcher: (0, import_ignore.default)().add(source)
114
+ }];
115
+ }
116
+ for (const entry of entries) {
117
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
118
+ const isDirectory = entry.isDirectory();
119
+ if (isDirectory && speculativeWalkExcludedDirs.has(entry.name)) continue;
120
+ if (!isDirectory && !(entry.isFile() && (0, import_metroResolver.isCompilerSourceFile)(entry.name))) continue;
121
+ if (!isDirectory && (/(?:^|[-.])(?:probe|run|spec|tests?)(?:[-.]|$)/i.test(entry.name) || /\.(?:build|config|workspace)\.[cm]?[jt]sx?$/.test(entry.name))) {
122
+ continue;
123
+ }
124
+ const path = (0, import_node_path.join)(dir, entry.name);
125
+ let ignored = false;
126
+ for (const scope of active) {
127
+ const relativePath = (0, import_node_path.relative)(scope.dir, path);
128
+ if (!relativePath || relativePath.startsWith("..")) continue;
129
+ const candidate = relativePath.split(import_node_path.sep).join("/") + (isDirectory ? "/" : "");
130
+ if (scope.matcher.ignores(candidate)) {
131
+ ignored = true;
132
+ break;
133
+ }
134
+ }
135
+ if (ignored) continue;
136
+ if (isDirectory) stack.push({
137
+ dir: path,
138
+ scopes: active
139
+ });
140
+ else found.push(path);
141
+ }
142
+ }
143
+ return found.sort(compareCodeUnits);
144
+ }
145
+ function compilerTarget(platform) {
146
+ return platform === "web" ? "web" : "native";
147
+ }
148
+ function retainsLiveGraph(options) {
149
+ return options.dev && options.hot;
150
+ }
151
+ var MetroCompilerFrontend = class {
152
+ constructor(config) {
153
+ this.config = config;
154
+ this.#cacheBaseRoot = config.cacheRoot ?? (0, import_compilerCache.defaultMetroCompilerCacheRoot)(config.projectRoot);
155
+ this.#resolver = (0, import_metroResolver.createMetroCompilerResolver)(config);
156
+ }
157
+ config;
158
+ #cacheBaseRoot;
159
+ #entries = /* @__PURE__ */ new Map();
160
+ #records = /* @__PURE__ */ new Map();
161
+ #watchers = /* @__PURE__ */ new Map();
162
+ #resolver;
163
+ #graph = null;
164
+ #host = null;
165
+ #registry = null;
166
+ #discovery = new import_static.ComponentDiscovery();
167
+ #externalClosure = (0, import_compiler_core.createExternalClosureLookup)();
168
+ #projectGeneration = null;
169
+ #publishedGeneration = null;
170
+ #scanOptions = null;
171
+ #scanOptionsHash = null;
172
+ #operationQueue = Promise.resolve();
173
+ #tamaguiConfig = null;
174
+ #zeroEntryGraph = null;
175
+ #planKeys = /* @__PURE__ */ new Map();
176
+ #recordCache = null;
177
+ #recordCacheIdentity = null;
178
+ #planCache = null;
179
+ #planCacheStamp = null;
180
+ get metroResolverVersion() {
181
+ return this.#resolver.version;
182
+ }
183
+ /**
184
+ * Per-file cache accounting for the last scan. The point of these caches is
185
+ * that one edited module leaves every other module's entry valid, and this is
186
+ * how that is observed rather than assumed.
187
+ */
188
+ get compileCacheStats() {
189
+ const empty = {
190
+ hits: 0,
191
+ misses: 0,
192
+ writes: 0
193
+ };
194
+ return {
195
+ plans: this.#planCache?.stats ?? empty,
196
+ records: this.#recordCache?.stats ?? empty
197
+ };
198
+ }
199
+ cacheRootFor(platform) {
200
+ return (0, import_node_path.join)(this.#cacheBaseRoot, platform ?? "default");
201
+ }
202
+ scan(options) {
203
+ return this.#enqueue(() => this.#scan(options));
204
+ }
205
+ async #scan(options, preparedProject, preparedProjectSources) {
206
+ this.#scanOptions = options;
207
+ this.#publishedGeneration = null;
208
+ const diagnostics = [];
209
+ const entryRoots = (await Promise.all(options.entryFiles.map((path) => (0, import_promises.realpath)((0, import_node_path.resolve)(this.config.projectRoot, path))))).sort(compareCodeUnits);
210
+ const compilerProject = preparedProject ?? await this.#loadCompilerProject(options, entryRoots[0], diagnostics);
211
+ this.#projectGeneration = compilerProject.generation;
212
+ const projectSources = preparedProjectSources ?? await walkProjectSources(this.config.projectRoot);
213
+ const projectSourcesHash = (0, import_compiler_core.contentHash)(JSON.stringify(projectSources));
214
+ this.#scanOptionsHash = scanOptionsHash(options, compilerProject.generation, projectSourcesHash);
215
+ this.#installCaches(options, compilerProject, projectSourcesHash);
216
+ const speculativeRoots = /* @__PURE__ */ new Set();
217
+ for (const file of projectSources) {
218
+ try {
219
+ const id = await (0, import_promises.realpath)(file);
220
+ if (!entryRoots.includes(id)) speculativeRoots.add(id);
221
+ } catch {}
222
+ }
223
+ const roots = [.../* @__PURE__ */ new Set([...entryRoots, ...speculativeRoots])].sort(compareCodeUnits);
224
+ const queue = [...roots];
225
+ const queued = new Set(queue);
226
+ for (const watcher of this.#watchers.values()) watcher.close();
227
+ this.#watchers.clear();
228
+ this.#records.clear();
229
+ while (queue.length) {
230
+ const path = queue.shift();
231
+ try {
232
+ const record = await this.#compileRecord(path, options, diagnostics);
233
+ this.#records.set(record.input.id, record);
234
+ for (const dependency of record.input.imports) {
235
+ if (dependency.external || !(0, import_metroResolver.isCompilerSourceFile)(dependency.resolvedId) || queued.has(dependency.resolvedId)) {
236
+ continue;
237
+ }
238
+ queued.add(dependency.resolvedId);
239
+ queue.push(dependency.resolvedId);
240
+ }
241
+ } catch (error) {
242
+ if (speculativeRoots.has(path)) continue;
243
+ const diagnostic = (0, import_diagnostics.metroDiagnostic)("metro/transform-failed", `Failed to compile ${path}: ${error instanceof Error ? error.message : String(error)}`, { moduleId: path });
244
+ diagnostics.push(diagnostic);
245
+ this.#report(diagnostic);
246
+ }
247
+ }
248
+ if (!compilerProject.projectInfo.tamaguiConfig || !compilerProject.projectInfo.components) {
249
+ throw new Error("Metro compiler project has no Tamagui config or components");
250
+ }
251
+ this.#tamaguiConfig = compilerProject.projectInfo.tamaguiConfig;
252
+ this.#entries.clear();
253
+ const unplanned = await this.#restorePlans(options);
254
+ const zero = this.config.zero;
255
+ this.#graph = null;
256
+ this.#host = null;
257
+ if (unplanned.length || retainsLiveGraph(options)) {
258
+ this.#graph = new import_compiler_core.ProjectGraph(import_compiler_core.yukuFactory, { modules: [...this.#records.values()].map(({ input }) => input) });
259
+ const componentModules = compilerProject.componentModules.map(({ moduleName, id }) => ({
260
+ moduleName,
261
+ resolvedId: id
262
+ }));
263
+ this.#discovery.clear();
264
+ this.#registry = (0, import_static.createComponentRegistry)(compilerProject.projectInfo.components, componentModules);
265
+ this.#host = (0, import_static.createTamaguiCompilerHost)({
266
+ target: compilerTarget(options.platform),
267
+ tamaguiConfig: compilerProject.projectInfo.tamaguiConfig,
268
+ components: compilerProject.projectInfo.components,
269
+ componentModules,
270
+ registry: this.#registry,
271
+ disablePartialExtraction: compilerProject.disablePartialExtraction,
272
+ experimentalNativeFastPath: compilerProject.experimentalNativeFastPath,
273
+ zeroRuntime: compilerProject.zeroRuntime
274
+ });
275
+ if (zero) {
276
+ if (zero.isEnforcing) {
277
+ import_static.default.assertZeroConfigDrivers(compilerProject.projectInfo.tamaguiConfig);
278
+ }
279
+ zero.plansRestoredFromCache = false;
280
+ zero.configCSS = compilerProject.projectInfo.tamaguiConfig.getCSS?.() ?? "";
281
+ zero.artifact.clearGraphs();
282
+ zero.bridges.clear();
283
+ zero.violations.length = 0;
284
+ zero.transformed.clear();
285
+ zero.erasedExports.clear();
286
+ this.#zeroEntryGraph = this.#reachableFrom(entryRoots.map(import_compiler_core.resolvedModuleId));
287
+ }
288
+ for (const id of unplanned) await this.#refreshEntry(id);
289
+ await this.#storePlans(unplanned);
290
+ }
291
+ if (zero) {
292
+ import_static.default.writeZeroViolationReport(zero.resolved.outDir, "metro-zero", {
293
+ integration: "metro-web",
294
+ mode: zero.isEnforcing ? "enforce" : "report",
295
+ violations: zero.violations
296
+ });
297
+ if (zero.isEnforcing && zero.violations.length) {
298
+ throw new Error(import_static.default.formatZeroViolations(zero.violations));
299
+ }
300
+ }
301
+ const totalFound = [...this.#entries.values()].reduce((sum, entry) => sum + entry.plan.stats.found, 0);
302
+ if (this.#entries.size > 0 && totalFound === 0) {
303
+ const componentNames = compilerProject.componentModules.map(({ moduleName }) => moduleName);
304
+ const cjsComponentImporters = [...this.#records.values()].filter((record) => record.requireSpecifiers.some((specifier) => componentNames.some((name) => specifier === name || specifier.startsWith(`${name}/`)))).length;
305
+ if (cjsComponentImporters > 0) {
306
+ const diagnostic = (0, import_diagnostics.metroDiagnostic)("metro/no-linked-components", `The Tamagui compiler linked 0 components across ${this.#entries.size} modules even though ${cjsComponentImporters} module(s) reference ${componentNames.join(", ")} through require() calls. Metro compiled modules to CommonJS before the compiler could analyze them, so component imports cannot be linked and nothing will be optimized. Enable experimentalImportSupport in your transformer's getTransformOptions (Expo enables it by default) to restore Tamagui compilation.`);
307
+ diagnostics.push(diagnostic);
308
+ this.#report(diagnostic);
309
+ }
310
+ }
311
+ const generation = await this.#publish(options.platform);
312
+ const moduleIds = [...this.#records.keys()].sort(compareCodeUnits);
313
+ if (this.config.watch !== false && retainsLiveGraph(options)) {
314
+ this.#installWatchers();
315
+ } else if (!retainsLiveGraph(options)) {
316
+ this.#releaseGraph();
317
+ }
318
+ return {
319
+ generation,
320
+ moduleIds,
321
+ diagnostics
322
+ };
323
+ }
324
+ ensureValidCache(options) {
325
+ return this.#enqueue(() => this.#ensureValidCache(options));
326
+ }
327
+ async #ensureValidCache(options) {
328
+ const diagnostics = [];
329
+ const firstEntry = options.entryFiles[0];
330
+ const importer = firstEntry ? await (0, import_promises.realpath)((0, import_node_path.resolve)(this.config.projectRoot, firstEntry)) : this.config.projectRoot;
331
+ const compilerProject = await this.#loadCompilerProject(options, importer, diagnostics);
332
+ const cache = new import_compilerCache.MetroCompilerCache(this.cacheRootFor(options.platform));
333
+ const validation = await cache.validate();
334
+ const projectSources = await walkProjectSources(this.config.projectRoot);
335
+ const optionsHash = scanOptionsHash(options, compilerProject.generation, (0, import_compiler_core.contentHash)(JSON.stringify(projectSources)));
336
+ if (validation.valid && validation.generation && validation.optionsHash === optionsHash && await this.#sourcesAreFresh(validation.sourceHashes) && (!retainsLiveGraph(options) && !this.#graph || this.#publishedGeneration && this.#scanOptionsHash === optionsHash) && await this.#rehydrateZeroCSS(cache, validation.generation)) {
337
+ this.#publishedGeneration = validation.generation;
338
+ this.#scanOptions = options;
339
+ this.#scanOptionsHash = optionsHash;
340
+ this.#projectGeneration = compilerProject.generation;
341
+ return {
342
+ generation: validation.generation,
343
+ moduleIds: validation.moduleIds,
344
+ diagnostics
345
+ };
346
+ }
347
+ for (const diagnostic of validation.diagnostics) this.#report(diagnostic);
348
+ await cache.discardManifest();
349
+ return await this.#scan(options, compilerProject, projectSources);
350
+ }
351
+ async updateFile(path) {
352
+ let result = {
353
+ changed: false,
354
+ affectedIds: [],
355
+ generation: null
356
+ };
357
+ return this.#enqueue(async () => {
358
+ const graph = this.#graph;
359
+ const options = this.#scanOptions;
360
+ if (!graph || !options) return result;
361
+ let record;
362
+ const diagnostics = [];
363
+ try {
364
+ record = await this.#compileRecord(path, options, diagnostics);
365
+ } catch (error) {
366
+ if (error.code === "ENOENT") {
367
+ const id = (0, import_compiler_core.resolvedModuleId)((0, import_node_path.resolve)(path));
368
+ const invalidation2 = graph.removeModule(id);
369
+ this.#watchers.get(id)?.close();
370
+ this.#watchers.delete(id);
371
+ this.#records.delete(id);
372
+ this.#entries.delete(id);
373
+ for (const affected of invalidation2.invalidatedIds) {
374
+ if (affected !== id) await this.#refreshEntry(affected);
375
+ }
376
+ const generation2 = await this.#publish(options.platform);
377
+ result = {
378
+ changed: invalidation2.changed,
379
+ affectedIds: invalidation2.invalidatedIds,
380
+ generation: generation2
381
+ };
382
+ return result;
383
+ }
384
+ const diagnostic = (0, import_diagnostics.metroDiagnostic)("metro/transform-failed", `Failed to update ${path}: ${error instanceof Error ? error.message : String(error)}`, { moduleId: path });
385
+ this.#report(diagnostic);
386
+ return result;
387
+ }
388
+ for (const dependency of record.input.imports) {
389
+ if (dependency.external || !(0, import_metroResolver.isCompilerSourceFile)(dependency.resolvedId) || this.#records.has(dependency.resolvedId)) {
390
+ continue;
391
+ }
392
+ await this.#addDependency(dependency.resolvedId, options, diagnostics);
393
+ }
394
+ this.#records.set(record.input.id, record);
395
+ const invalidation = graph.updateModule(record.input);
396
+ for (const affected of invalidation.invalidatedIds) await this.#refreshEntry(affected);
397
+ const generation = invalidation.changed ? await this.#publish(options.platform) : null;
398
+ result = {
399
+ changed: invalidation.changed,
400
+ affectedIds: invalidation.invalidatedIds,
401
+ generation
402
+ };
403
+ if (this.config.watch !== false && retainsLiveGraph(options)) {
404
+ this.#watchModule(record.input.id);
405
+ }
406
+ return result;
407
+ });
408
+ }
409
+ /** A published plan only applies while every recorded module source is unchanged. */
410
+ async #sourcesAreFresh(sourceHashes) {
411
+ const checks = Object.entries(sourceHashes).map(async ([moduleId, sourceHash]) => {
412
+ try {
413
+ return (0, import_compiler_core.contentHash)(await (0, import_promises.readFile)(moduleId, "utf8")) === sourceHash;
414
+ } catch {
415
+ return false;
416
+ }
417
+ });
418
+ return (await Promise.all(checks)).every(Boolean);
419
+ }
420
+ #enqueue(operation) {
421
+ const queued = this.#operationQueue.then(operation);
422
+ this.#operationQueue = queued.then(() => void 0, () => void 0);
423
+ return queued;
424
+ }
425
+ close() {
426
+ return this.#enqueue(async () => {
427
+ this.#releaseGraph();
428
+ });
429
+ }
430
+ #releaseGraph() {
431
+ for (const watcher of this.#watchers.values()) watcher.close();
432
+ this.#watchers.clear();
433
+ this.#entries.clear();
434
+ this.#records.clear();
435
+ this.#planKeys.clear();
436
+ this.#graph = null;
437
+ this.#host = null;
438
+ this.#registry = null;
439
+ this.#projectGeneration = null;
440
+ }
441
+ async #loadCompilerProject(options, importer, diagnostics) {
442
+ const target = compilerTarget(options.platform);
443
+ if (this.config.loadCompilerProject) {
444
+ return await this.config.loadCompilerProject(target, options.platform);
445
+ }
446
+ return import_static.default.loadCompilerProject({
447
+ root: this.config.projectRoot,
448
+ target,
449
+ options: this.config.tamaguiOptions ?? {},
450
+ hostVersions: compilerImplementationVersions,
451
+ missingProjectMessage: "Unable to load the Tamagui project for Metro compilation",
452
+ generation: (projectInfo, componentModules, normalizedOptions) => {
453
+ return (0, import_compiler_core.contentHash)(JSON.stringify({
454
+ cacheVersion: import_compilerCache.METRO_COMPILER_CACHE_VERSION,
455
+ compilerImplementationVersions,
456
+ componentModules,
457
+ configCss: projectInfo.tamaguiConfig?.getCSS?.() ?? "",
458
+ disablePartialExtraction: !!normalizedOptions.disablePartialExtraction,
459
+ experimentalNativeFastPath: target === "native" && normalizedOptions.experimental?.nativeFastPath === true,
460
+ target,
461
+ zeroRuntime: !!this.config.zero
462
+ }));
463
+ },
464
+ resolveComponents: async (moduleNames) => {
465
+ const componentModules = [];
466
+ for (const moduleName of moduleNames) {
467
+ try {
468
+ const resolution = this.#resolver.resolve(importer, {
469
+ specifier: moduleName,
470
+ isESMImport: true
471
+ }, options.platform);
472
+ if (!resolution) continue;
473
+ componentModules.push({
474
+ moduleName,
475
+ id: resolution.resolvedId
476
+ });
477
+ } catch (error) {
478
+ const diagnostic = (0, import_diagnostics.metroDiagnostic)("metro/resolve-failed", `Failed to resolve compiler component ${moduleName}: ${error instanceof Error ? error.message : String(error)}`, {
479
+ moduleId: importer,
480
+ dependency: moduleName
481
+ });
482
+ diagnostics.push(diagnostic);
483
+ this.#report(diagnostic);
484
+ }
485
+ }
486
+ return componentModules;
487
+ }
488
+ });
489
+ }
490
+ async #compileRecord(rawPath, options, diagnostics) {
491
+ const path = await (0, import_promises.realpath)((0, import_node_path.resolve)(rawPath));
492
+ const source = await (0, import_promises.readFile)(path, "utf8");
493
+ const sourceHash = (0, import_compiler_core.contentHash)(source);
494
+ const id = (0, import_compiler_core.resolvedModuleId)(path);
495
+ const cache = this.#recordCache;
496
+ const identity = this.#recordCacheIdentity;
497
+ const key = cache && identity ? (0, import_compiler_core.contentHash)(`${identity}\0${sourceHash}`) : null;
498
+ if (cache && key) {
499
+ const cached = await cache.read(key, (value) => {
500
+ const entry = value;
501
+ return entry?.schemaVersion === METRO_RECORD_CACHE_VERSION && entry.sourceHash === sourceHash && Array.isArray(entry.imports) && Array.isArray(entry.requireSpecifiers) && Array.isArray(entry.diagnostics) ? entry : null;
502
+ });
503
+ if (cached) {
504
+ for (const diagnostic of cached.diagnostics) {
505
+ diagnostics.push(diagnostic);
506
+ this.#report(diagnostic);
507
+ }
508
+ return {
509
+ input: {
510
+ id,
511
+ source,
512
+ imports: cached.imports
513
+ },
514
+ sourceHash,
515
+ requireSpecifiers: cached.requireSpecifiers
516
+ };
517
+ }
518
+ }
519
+ const args = this.#babelArgs(path, source, options);
520
+ const compiled = await (0, import_babel.compileWithUserBabel)(this.config.originalBabelTransformerPath, args);
521
+ const imports = [];
522
+ const requireSpecifiers = [];
523
+ const recordDiagnostics = [];
524
+ for (const dependency of (0, import_metroResolver.moduleSpecifiersFromAst)(compiled.result.ast)) {
525
+ if (!dependency.isESMImport) requireSpecifiers.push(dependency.specifier);
526
+ try {
527
+ const resolution = this.#resolver.resolve(path, dependency, options.platform);
528
+ if (!resolution) continue;
529
+ imports.push({
530
+ specifier: resolution.specifier,
531
+ resolvedId: (0, import_compiler_core.resolvedModuleId)(resolution.resolvedId),
532
+ external: resolution.external
533
+ });
534
+ } catch (error) {
535
+ recordDiagnostics.push((0, import_diagnostics.metroDiagnostic)("metro/resolve-failed", `Failed to resolve ${dependency.specifier} from ${path}: ${error instanceof Error ? error.message : String(error)}`, {
536
+ moduleId: path,
537
+ dependency: dependency.specifier
538
+ }));
539
+ }
540
+ }
541
+ for (const diagnostic of recordDiagnostics) {
542
+ diagnostics.push(diagnostic);
543
+ this.#report(diagnostic);
544
+ }
545
+ if (cache && key) {
546
+ await cache.write(key, {
547
+ schemaVersion: METRO_RECORD_CACHE_VERSION,
548
+ sourceHash,
549
+ imports,
550
+ requireSpecifiers,
551
+ diagnostics: recordDiagnostics
552
+ });
553
+ }
554
+ return {
555
+ input: {
556
+ id,
557
+ source,
558
+ imports
559
+ },
560
+ sourceHash,
561
+ requireSpecifiers
562
+ };
563
+ }
564
+ #babelOptions(options) {
565
+ const transformer = this.config.transformer ?? {};
566
+ return {
567
+ ...options.transform,
568
+ dev: options.dev,
569
+ hot: options.hot,
570
+ platform: options.platform,
571
+ projectRoot: this.config.projectRoot,
572
+ enableBabelRCLookup: transformer.enableBabelRCLookup ?? true,
573
+ enableBabelRuntime: transformer.enableBabelRuntime ?? true,
574
+ hermesParser: transformer.hermesParser ?? false,
575
+ publicPath: transformer.publicPath ?? "/assets"
576
+ };
577
+ }
578
+ #babelArgs(filename, src, options) {
579
+ return {
580
+ filename,
581
+ src,
582
+ plugins: [],
583
+ options: this.#babelOptions(options)
584
+ };
585
+ }
586
+ async #addDependency(id, options, diagnostics, visiting = /* @__PURE__ */ new Set()) {
587
+ if (this.#records.has(id) || visiting.has(id)) return;
588
+ visiting.add(id);
589
+ try {
590
+ const record = await this.#compileRecord(id, options, diagnostics);
591
+ for (const dependency of record.input.imports) {
592
+ if (!dependency.external && (0, import_metroResolver.isCompilerSourceFile)(dependency.resolvedId)) {
593
+ await this.#addDependency(dependency.resolvedId, options, diagnostics, visiting);
594
+ }
595
+ }
596
+ this.#records.set(id, record);
597
+ const invalidation = this.#graph?.updateModule(record.input);
598
+ for (const affected of invalidation?.invalidatedIds ?? [id]) {
599
+ await this.#refreshEntry(affected);
600
+ }
601
+ if (this.config.watch !== false && this.#scanOptions && retainsLiveGraph(this.#scanOptions)) {
602
+ this.#watchModule(id);
603
+ }
604
+ } finally {
605
+ visiting.delete(id);
606
+ }
607
+ }
608
+ async #refreshEntry(id) {
609
+ const graph = this.#graph;
610
+ const host = this.#host;
611
+ const registry = this.#registry;
612
+ const record = this.#records.get(id);
613
+ if (!graph || !host || !registry || !record || !this.#scanOptions || !this.#projectGeneration) {
614
+ return;
615
+ }
616
+ const target = compilerTarget(this.#scanOptions.platform);
617
+ const materialized = (0, import_compiler_core.materializeModule)(graph, id);
618
+ await this.#discovery.prepare(materialized, registry, ({ id: moduleId }) => import_static.default.evaluateComponentModule({
619
+ ...this.config.tamaguiOptions,
620
+ platform: target
621
+ }, moduleId));
622
+ const plan = (0, import_compiler_core.lowerModule)({
623
+ module: materialized,
624
+ source: record.input.source,
625
+ target,
626
+ host,
627
+ options: { projectGeneration: this.#projectGeneration }
628
+ });
629
+ const zeroPlan = this.#zeroPlanFor(id, record.input.source, plan);
630
+ this.#entries.set(id, this.#entryFor(id, record, zeroPlan ?? plan));
631
+ }
632
+ /**
633
+ * One plan becomes one cache entry the same way whether the plan was just
634
+ * lowered or read back off disk, so a restored build reports exactly the
635
+ * diagnostics a fresh one did.
636
+ */
637
+ #entryFor(id, record, plan) {
638
+ return {
639
+ schemaVersion: import_compilerCache.METRO_COMPILER_CACHE_VERSION,
640
+ moduleId: id,
641
+ sourceHash: record.sourceHash,
642
+ plan,
643
+ diagnostics: plan.diagnostics.map(({ code, message, dependencyId, span, component }) => {
644
+ const { line, column } = import_static.default.offsetToLineColumn(record.input.source, span.start);
645
+ return (0, import_diagnostics.metroDiagnostic)(code.startsWith("linked/") ? "metro/resolve-failed" : "metro/transform-failed", message, {
646
+ moduleId: id,
647
+ dependency: dependencyId,
648
+ span,
649
+ line,
650
+ column,
651
+ component
652
+ });
653
+ })
654
+ };
655
+ }
656
+ /**
657
+ * Both per-file caches for this scan. A project with no content stamp gets
658
+ * neither: a stamp that cannot see a config change would serve styles built
659
+ * against the old config, so the answer is no cache rather than a partial one.
660
+ *
661
+ * Zero builds opt out of the plan cache because a zero plan is produced
662
+ * alongside side effects that do not travel in the plan - the CSS artifact,
663
+ * the bridge manifest, the violation list - so replaying one module's plan
664
+ * without them would emit an artifact missing its rules.
665
+ */
666
+ #installCaches(options, project, projectSourcesHash) {
667
+ const platform = options.platform ?? "default";
668
+ const root = (0, import_compiler_core.defaultPlanCacheRoot)(this.config.projectRoot, platform);
669
+ this.#recordCache = new import_compiler_core.JsonFileCache((0, import_node_path.join)(root, "records"), METRO_RECORD_CACHE_VERSION);
670
+ this.#recordCacheIdentity = (0, import_compiler_core.contentHash)((0, import_compiler_core.stableStringify)({
671
+ schema: METRO_RECORD_CACHE_VERSION,
672
+ resolver: this.#resolver.version,
673
+ babel: (0, import_babel.userBabelCacheKey)(this.config.originalBabelTransformerPath),
674
+ projectSourcesHash,
675
+ platform,
676
+ transform: this.#babelOptions(options)
677
+ }));
678
+ const stamp = project.cacheStamp;
679
+ const usePlanCache = typeof stamp === "string" && stamp !== "" && !this.config.zero;
680
+ this.#planCache = usePlanCache ? new import_compiler_core.ModulePlanCache((0, import_node_path.join)(root, "plans")) : null;
681
+ this.#planCacheStamp = usePlanCache ? stamp : null;
682
+ }
683
+ /**
684
+ * Fills `#entries` from disk for every module whose whole compile input is
685
+ * unchanged, and returns the ids that still have to be compiled. This is the
686
+ * per-file property: one edited module leaves every other module's entry
687
+ * valid, where the plan manifest would have discarded all of them.
688
+ */
689
+ async #restorePlans(options) {
690
+ this.#planKeys.clear();
691
+ const cache = this.#planCache;
692
+ const stamp = this.#planCacheStamp;
693
+ if (!cache || !stamp) return [...this.#records.keys()].sort(compareCodeUnits);
694
+ const target = compilerTarget(options.platform);
695
+ const identity = {
696
+ stamp,
697
+ target,
698
+ structuralPassHash: `${target}-noop-v1`
699
+ };
700
+ const nodes = /* @__PURE__ */ new Map();
701
+ const lookup = (id) => {
702
+ let node = nodes.get(id);
703
+ if (node === void 0) {
704
+ const record = this.#records.get(id);
705
+ node = record ? (0, import_compiler_core.moduleClosureNode)(record.input, { includeExternal: true }) : this.#externalClosure(id);
706
+ nodes.set(id, node);
707
+ }
708
+ return node;
709
+ };
710
+ const memo = /* @__PURE__ */ new Map();
711
+ const unplanned = [];
712
+ for (const id of [...this.#records.keys()].sort(compareCodeUnits)) {
713
+ const record = this.#records.get(id);
714
+ const digest = (0, import_compiler_core.moduleClosureDigest)(id, lookup, memo);
715
+ const key = digest && (0, import_compiler_core.planCacheKey)(identity, id, digest);
716
+ const entry = key && digest ? await cache.read(key, id, digest) : null;
717
+ if (entry) {
718
+ this.#entries.set(id, this.#entryFor(id, record, entry.plan));
719
+ continue;
720
+ }
721
+ if (key && digest) this.#planKeys.set(id, {
722
+ key,
723
+ digest
724
+ });
725
+ unplanned.push(id);
726
+ }
727
+ return unplanned;
728
+ }
729
+ async #storePlans(ids) {
730
+ const cache = this.#planCache;
731
+ if (!cache) return;
732
+ const pending = ids.flatMap((id) => {
733
+ const entry = this.#entries.get(id);
734
+ const key = this.#planKeys.get(id);
735
+ return entry && key ? [{
736
+ id,
737
+ entry,
738
+ key
739
+ }] : [];
740
+ });
741
+ for (let index = 0; index < pending.length; index += 32) {
742
+ await Promise.all(pending.slice(index, index + 32).map(({ id, entry, key }) => cache.write(key.key, {
743
+ schemaVersion: import_compiler_core.PLAN_CACHE_SCHEMA_VERSION,
744
+ moduleId: id,
745
+ closureDigest: key.digest,
746
+ plan: entry.plan
747
+ })));
748
+ }
749
+ }
750
+ /** Modules reachable from the bundle's entry, over the frontend's own graph. */
751
+ #reachableFrom(roots) {
752
+ const reached = /* @__PURE__ */ new Set();
753
+ const queue = [...roots];
754
+ while (queue.length) {
755
+ const id = queue.pop();
756
+ if (reached.has(id)) continue;
757
+ reached.add(id);
758
+ for (const dependency of this.#records.get(id)?.input.imports ?? []) {
759
+ if (!dependency.external) queue.push(dependency.resolvedId);
760
+ }
761
+ }
762
+ return reached;
763
+ }
764
+ /**
765
+ * The zero transform for one module, returning a plan whose edits also carry
766
+ * the static Theme lowering, the island bridge, and reference erasure.
767
+ */
768
+ #zeroPlanFor(id, source, plan) {
769
+ const zero = this.config.zero;
770
+ const config = this.#tamaguiConfig;
771
+ if (!zero || !config) return null;
772
+ if (zero.islandBuild) {
773
+ zero.artifact.setIslandModuleCSS(zero.islandBuild, id, plan.css);
774
+ return null;
775
+ }
776
+ if (this.#zeroEntryGraph && !this.#zeroEntryGraph.has(id)) return null;
777
+ const relativePath = (0, import_node_path.relative)(this.config.projectRoot, id);
778
+ if (relativePath === "" || relativePath.startsWith("..") || relativePath.split(/[\\/]/).includes("node_modules")) {
779
+ return null;
780
+ }
781
+ const result = import_static.default.transformZeroModule({
782
+ mode: zero.isEnforcing ? "enforce" : "report",
783
+ id,
784
+ root: this.config.projectRoot,
785
+ source,
786
+ plan,
787
+ config,
788
+ isTamaguiSpecifier: import_compiler_core.isTamaguiSpecifier,
789
+ resolveIslandLoader: (specifier) => {
790
+ const islandId = zero.loaderIds.get((0, import_zeroRuntime.zeroModuleKey)((0, import_node_path.resolve)(id, "..", specifier)));
791
+ return islandId ? { islandId } : null;
792
+ },
793
+ resolveIslandModule: (specifier) => zero.islandModuleIds.get((0, import_zeroRuntime.zeroModuleKey)((0, import_node_path.resolve)(id, "..", specifier))) ?? null
794
+ });
795
+ zero.transformed.add(id);
796
+ if (result.erased.exports.length) {
797
+ zero.erasedExports.set(id, result.erased.exports);
798
+ }
799
+ for (const violation of result.violations) {
800
+ const { line, column } = import_static.default.offsetToLineColumn(source, violation.span.start);
801
+ zero.violations.push({
802
+ file: relativePath,
803
+ line,
804
+ column,
805
+ rule: violation.rule,
806
+ code: violation.code,
807
+ component: violation.component,
808
+ message: violation.message
809
+ });
810
+ }
811
+ if (result.violations.length || !zero.isEnforcing) return null;
812
+ import_static.default.mergeIslandBridges(zero.bridges, result.bridges);
813
+ for (const [identifier, rules] of result.bridgeCSS) {
814
+ zero.artifact.setBridgeRules(identifier, rules);
815
+ }
816
+ zero.artifact.setZeroModuleCSS(id, plan.css);
817
+ return {
818
+ ...plan,
819
+ edits: [...plan.edits, ...result.edits]
820
+ };
821
+ }
822
+ async #publish(platform) {
823
+ const cache = new import_compilerCache.MetroCompilerCache(this.cacheRootFor(platform));
824
+ const generation = await cache.publish(platform, [...this.#entries.values()], this.#scanOptionsHash ?? "");
825
+ const zero = this.config.zero;
826
+ if (zero && !zero.islandBuild) {
827
+ await cache.publishZeroCSS({
828
+ schemaVersion: import_compilerCache.METRO_COMPILER_CACHE_VERSION,
829
+ generation,
830
+ configCSS: zero.configCSS,
831
+ zeroModuleCSS: Object.fromEntries(zero.artifact.zeroModuleEntries()),
832
+ bridgeCSS: Object.fromEntries(zero.artifact.bridgeEntries()),
833
+ bridges: Object.fromEntries(zero.bridges)
834
+ });
835
+ }
836
+ this.#publishedGeneration = generation;
837
+ return generation;
838
+ }
839
+ /**
840
+ * Restores the zero build's CSS side effects from the sidecar published with
841
+ * this plan generation. Returns false when there is nothing trustworthy to
842
+ * restore, which sends the caller to a full scan.
843
+ */
844
+ async #rehydrateZeroCSS(cache, generation) {
845
+ const zero = this.config.zero;
846
+ if (!zero || zero.islandBuild) return true;
847
+ const sidecar = await cache.readZeroCSS(generation);
848
+ if (!sidecar) return false;
849
+ zero.artifact.clearGraphs();
850
+ zero.bridges.clear();
851
+ zero.violations.length = 0;
852
+ zero.configCSS = sidecar.configCSS;
853
+ for (const [moduleId, css] of Object.entries(sidecar.zeroModuleCSS)) {
854
+ zero.artifact.setZeroModuleCSS(moduleId, css);
855
+ }
856
+ for (const [bridgeId, css] of Object.entries(sidecar.bridgeCSS)) {
857
+ zero.artifact.setBridgeRules(bridgeId, css);
858
+ }
859
+ for (const [islandId, bridges] of Object.entries(sidecar.bridges)) {
860
+ zero.bridges.set(islandId, bridges);
861
+ }
862
+ zero.plansRestoredFromCache = true;
863
+ return true;
864
+ }
865
+ #installWatchers() {
866
+ for (const id of this.#records.keys()) this.#watchModule(id);
867
+ }
868
+ #watchModule(id) {
869
+ if (this.#watchers.has(id)) return;
870
+ try {
871
+ const watcher = (0, import_node_fs.watch)(id, { persistent: false }, () => {
872
+ void this.updateFile(id);
873
+ });
874
+ watcher.unref();
875
+ this.#watchers.set(id, watcher);
876
+ } catch {}
877
+ }
878
+ #report(diagnostic) {
879
+ this.config.reportDiagnostic?.(diagnostic);
880
+ }
881
+ };
882
+ function describeMetroCompilerRoot(projectRoot, moduleId) {
883
+ const path = (0, import_node_path.relative)(projectRoot, moduleId);
884
+ return path.startsWith("..") ? (0, import_node_path.basename)(moduleId) : path;
885
+ }