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