@tamagui/metro-plugin 3.0.0-beta.669.1 → 3.0.0-beta.728.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.
@@ -1,11 +1,11 @@
1
1
  {
2
- "mappings": "AAOA,cAgBO,sBAMA;AACP,OAAO,YAA2C;AAClD,cAEE,sBAEK;AAOP,cAA6B,2BAA2B;AAOxD,cAA+B,+BAA+B;AAC9D,cAIO,2BACA;;;;;;;AAeP,OAAO,cAAM,6BAA6B;AAW1C,iBAAiB,oCAAoC,oBAAoB;CACvE;;CAEA,OAAO;CACP;CACA,cAAc;CACd,iBAAiB,QAAQ;CACzB,uBACE,QAAQ,gBACR,4BACG,QAAQ;CACb;CACA,oBAAoB,YAAY;;AAGlC,iBAAiB,6BAA6B,OAAO,gBAAgB;AAErE,iBAAiB,yBAAyB;CACxC;CACA;CACA;CACA;CACA,YAAY;;AAGd,iBAAiB,wBAAwB;CACvC;CACA;CACA,aAAa;;AAGf,iBAAiB,oBAAoB;CACnC;CACA;CACA;;AAuIF,OAAO,cAAM,sBAAsB;;CAqBrB,iBAAiB;CAA7B,YAAY,AAAS,QAAQ;CAM7B,IAAI;;;;;;CASJ,IAAI,qBAAqB;EACvB,OAAO;GAAE;GAAc;GAAgB;;EACvC,SAAS;GAAE;GAAc;GAAgB;;;CAS3C,aAAa;CAIb,KAAK,SAAS,2BAA2B,QAAQ;CAyLjD,iBAAiB,SAAS,2BAA2B,QAAQ;CAsD7D,AAAM,WAAW,eAAe,QAAQ;CA2FxC,SAAS;;AA+hBX,OAAO,iBAAS,0BAA0B,qBAAqB",
2
+ "mappings": "AAOA,cAiBO,sBAMA;AACP,OAAO,YAA2C;AAClD,cAEE,sBAEK;AAOP,cAA6B,2BAA2B;AAOxD,cAA+B,+BAA+B;AAC9D,cAIO,2BACA;;;;;;;AAeP,OAAO,cAAM,6BAA6B;AAW1C,iBAAiB,oCAAoC,oBAAoB;CACvE;;CAEA,OAAO;CACP;CACA,cAAc;CACd,iBAAiB,QAAQ;CACzB,uBACE,QAAQ,gBACR,4BACG,QAAQ;CACb;CACA,oBAAoB,YAAY;;AAGlC,iBAAiB,6BAA6B,OAAO,gBAAgB;AAErE,iBAAiB,yBAAyB;CACxC;CACA;CACA;CACA;CACA,YAAY;;AAGd,iBAAiB,wBAAwB;CACvC;CACA;CACA,aAAa;;AAGf,iBAAiB,oBAAoB;CACnC;CACA;CACA;;AAuIF,OAAO,cAAM,sBAAsB;;CAqBrB,iBAAiB;CAA7B,YAAY,AAAS,QAAQ;CAM7B,IAAI;;;;;;CASJ,IAAI,qBAAqB;EACvB,OAAO;GAAE;GAAc;GAAgB;;EACvC,SAAS;GAAE;GAAc;GAAgB;;;CAS3C,aAAa;CAIb,KAAK,SAAS,2BAA2B,QAAQ;CAyLjD,iBAAiB,SAAS,2BAA2B,QAAQ;CAsD7D,AAAM,WAAW,eAAe,QAAQ;CA2FxC,SAAS;;AA8hBX,OAAO,iBAAS,0BAA0B,qBAAqB",
3
3
  "names": [],
4
4
  "sources": [
5
5
  "src/frontend.ts"
6
6
  ],
7
7
  "version": 3,
8
8
  "sourcesContent": [
9
- "import { existsSync, watch, type FSWatcher } from 'node:fs'\nimport { readFile, readdir, realpath } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, join, relative, resolve, sep } from 'node:path'\n\nimport ignore, { type Ignore } from 'ignore'\n\nimport {\n JsonFileCache,\n ModulePlanCache,\n PLAN_CACHE_SCHEMA_VERSION,\n ProjectGraph,\n contentHash,\n defaultPlanCacheRoot,\n lowerModule,\n materializeModule,\n moduleClosureDigest,\n moduleClosureNode,\n planCacheKey,\n resolvedModuleId,\n stableStringify,\n yukuFactory,\n type CompilerLoweringHost,\n type CompilerTarget,\n type HostModuleInput,\n type HostResolvedImport,\n type LoweredModulePlan,\n type ModuleClosureNode,\n type ResolvedModuleId,\n} from '@tamagui/compiler-core'\nimport Static, { createTamaguiCompilerHost } from '@tamagui/static'\nimport type {\n IslandThemeBridge,\n TamaguiOptions,\n TamaguiProjectInfo,\n} from '@tamagui/static'\n\nimport {\n compileWithUserBabel,\n userBabelCacheKey,\n type MetroBabelTransformArgs,\n} from './babel'\nimport { zeroModuleKey, type MetroZeroController } from './zeroRuntime'\nimport {\n METRO_COMPILER_CACHE_VERSION,\n MetroCompilerCache,\n defaultMetroCompilerCacheRoot,\n type MetroCompilerCacheEntry,\n} from './compilerCache'\nimport { metroDiagnostic, type MetroCompilerDiagnostic } from './diagnostics'\nimport {\n createMetroCompilerResolver,\n isCompilerSourceFile,\n moduleSpecifiersFromAst,\n type MetroResolverConfig,\n} from './metroResolver'\n\ninterface CompiledRecord {\n input: HostModuleInput\n sourceHash: string\n /** Specifiers that reached the compiled output as require() calls instead of imports. */\n requireSpecifiers: string[]\n}\n\n/**\n * Metro runs the user's whole Babel transformer over every project source just\n * to read its import specifiers, which is the single most expensive step of the\n * prepass. The result is a pure function of the module's own bytes plus the\n * resolver and Babel identity, so it caches per file with no closure involved.\n */\nexport const METRO_RECORD_CACHE_VERSION = 1\n\ninterface CachedRecord {\n schemaVersion: typeof METRO_RECORD_CACHE_VERSION\n sourceHash: string\n imports: HostResolvedImport[]\n requireSpecifiers: string[]\n /** Resolve failures replayed on a hit, so a cached record reports what a fresh one did. */\n diagnostics: MetroCompilerDiagnostic[]\n}\n\nexport interface MetroCompilerFrontendConfig extends MetroResolverConfig {\n cacheRoot?: string\n /** Present only for an enforced zero-runtime web build. */\n zero?: MetroZeroController | null\n originalBabelTransformerPath: string\n transformer?: Record<string, any>\n tamaguiOptions?: Partial<TamaguiOptions>\n loadCompilerProject?: (\n target: CompilerTarget,\n platform: string | null\n ) => Promise<MetroCompilerProject>\n watch?: boolean\n reportDiagnostic?: (diagnostic: MetroCompilerDiagnostic) => void\n}\n\nexport interface MetroCompilerProject extends Static.CompilerProject {}\n\nexport interface MetroCompilerScanOptions {\n dev: boolean\n entryFiles: readonly string[]\n hot: boolean\n platform: string | null\n transform?: Record<string, any>\n}\n\nexport interface MetroCompilerGeneration {\n generation: string\n moduleIds: string[]\n diagnostics: MetroCompilerDiagnostic[]\n}\n\nexport interface MetroCompilerUpdate {\n changed: boolean\n affectedIds: string[]\n generation: string | null\n}\n\nfunction compareCodeUnits(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nconst requireFromFrontend = createRequire(\n typeof __filename === 'string' ? __filename : import.meta.url\n)\n\n// upgrading the compiler must invalidate published plans even when the Tamagui\n// config output is unchanged\nconst compilerImplementationVersions = (\n ['@tamagui/metro-plugin', '@tamagui/static', '@tamagui/compiler-core'] as const\n).map((packageName) => {\n const { version } = requireFromFrontend(`${packageName}/package.json`) as {\n version: string\n }\n return `${packageName}@${version}`\n})\n\nfunction scanOptionsHash(\n options: MetroCompilerScanOptions,\n projectGeneration: string,\n projectSourcesHash: string\n): string {\n return contentHash(JSON.stringify({ options, projectGeneration, projectSourcesHash }))\n}\n\n// Metro entries can live inside node_modules (expo-router's entry reaches app\n// source only through require.context), so reachability from the entry alone\n// discovers nothing there. Project source is walked directly and seeded into\n// the scan alongside the entry; imports then extend the graph outside the\n// project root (workspace packages) exactly as before.\n//\n// The walked list is both the seed set and the plan cache's options hash, so it\n// has to be authored source only. Build output is whatever the project already\n// declares as ignored, read with git's own rules: a directory-name list cannot\n// know that `dist-metro`, `out` or `public/assets` are output, and a sibling\n// bundler's content-hashed filenames then re-key the plan cache on every\n// unrelated rebuild, forcing Metro to rescan a project that never changed.\n// `node_modules` is skipped structurally instead, because that is the same\n// externality boundary the resolver draws and it must hold with or without a\n// declaration.\ninterface IgnoreScope {\n dir: string\n matcher: Ignore\n}\n\nconst speculativeWalkExcludedDirs = new Set([\n '__tests__',\n 'e2e',\n 'flows',\n 'plugins',\n 'screenshots',\n 'scripts',\n 'test',\n 'test-results',\n 'tests',\n])\n\nasync function walkProjectSources(root: string): Promise<string[]> {\n // git reads every .gitignore from the repository root down to the file, so an\n // app nested in a monorepo inherits the declarations made above it\n const inherited: string[] = []\n let ancestor = root\n while (!existsSync(join(ancestor, '.git'))) {\n const parent = dirname(ancestor)\n if (parent === ancestor) break\n inherited.unshift(parent)\n ancestor = parent\n }\n const rootScopes: IgnoreScope[] = []\n for (const dir of inherited) {\n const source = await readFile(join(dir, '.gitignore'), 'utf8').catch(() => null)\n if (source) rootScopes.push({ dir, matcher: ignore().add(source) })\n }\n\n const found: string[] = []\n const stack: { dir: string; scopes: IgnoreScope[] }[] = [\n { dir: root, scopes: rootScopes },\n ]\n while (stack.length) {\n const { dir, scopes } = stack.pop()!\n let entries\n try {\n entries = await readdir(dir, { withFileTypes: true })\n } catch {\n continue\n }\n let active = scopes\n if (entries.some((entry) => entry.isFile() && entry.name === '.gitignore')) {\n const source = await readFile(join(dir, '.gitignore'), 'utf8').catch(() => null)\n if (source) active = [...scopes, { dir, matcher: ignore().add(source) }]\n }\n for (const entry of entries) {\n if (entry.name.startsWith('.') || entry.name === 'node_modules') continue\n const isDirectory = entry.isDirectory()\n if (isDirectory && speculativeWalkExcludedDirs.has(entry.name)) continue\n if (!isDirectory && !(entry.isFile() && isCompilerSourceFile(entry.name))) continue\n if (\n !isDirectory &&\n (/(?:^|[-.])(?:probe|run|spec|tests?)(?:[-.]|$)/i.test(entry.name) ||\n /\\.(?:build|config|workspace)\\.[cm]?[jt]sx?$/.test(entry.name))\n ) {\n continue\n }\n const path = join(dir, entry.name)\n let ignored = false\n for (const scope of active) {\n const relativePath = relative(scope.dir, path)\n if (!relativePath || relativePath.startsWith('..')) continue\n const candidate = relativePath.split(sep).join('/') + (isDirectory ? '/' : '')\n if (scope.matcher.ignores(candidate)) {\n ignored = true\n break\n }\n }\n if (ignored) continue\n if (isDirectory) stack.push({ dir: path, scopes: active })\n else found.push(path)\n }\n }\n return found.sort(compareCodeUnits)\n}\n\nfunction compilerTarget(platform: string | null): CompilerTarget {\n return platform === 'web' ? 'web' : 'native'\n}\n\nfunction retainsLiveGraph(options: MetroCompilerScanOptions): boolean {\n return options.dev && options.hot\n}\n\nexport class MetroCompilerFrontend {\n readonly #cacheBaseRoot: string\n readonly #entries = new Map<ResolvedModuleId, MetroCompilerCacheEntry>()\n readonly #records = new Map<ResolvedModuleId, CompiledRecord>()\n readonly #watchers = new Map<ResolvedModuleId, FSWatcher>()\n readonly #resolver\n #graph: ProjectGraph | null = null\n #host: CompilerLoweringHost | null = null\n #projectGeneration: string | null = null\n #publishedGeneration: string | null = null\n #scanOptions: MetroCompilerScanOptions | null = null\n #scanOptionsHash: string | null = null\n #operationQueue: Promise<void> = Promise.resolve()\n #tamaguiConfig: TamaguiProjectInfo['tamaguiConfig'] | null = null\n #zeroEntryGraph: Set<ResolvedModuleId> | null = null\n readonly #planKeys = new Map<ResolvedModuleId, { key: string; digest: string }>()\n #recordCache: JsonFileCache | null = null\n #recordCacheIdentity: string | null = null\n #planCache: ModulePlanCache | null = null\n #planCacheStamp: string | null = null\n\n constructor(readonly config: MetroCompilerFrontendConfig) {\n this.#cacheBaseRoot =\n config.cacheRoot ?? defaultMetroCompilerCacheRoot(config.projectRoot)\n this.#resolver = createMetroCompilerResolver(config)\n }\n\n get metroResolverVersion(): string {\n return this.#resolver.version\n }\n\n /**\n * Per-file cache accounting for the last scan. The point of these caches is\n * that one edited module leaves every other module's entry valid, and this is\n * how that is observed rather than assumed.\n */\n get compileCacheStats(): {\n plans: { hits: number; misses: number; writes: number }\n records: { hits: number; misses: number; writes: number }\n } {\n const empty = { hits: 0, misses: 0, writes: 0 }\n return {\n plans: this.#planCache?.stats ?? empty,\n records: this.#recordCache?.stats ?? empty,\n }\n }\n\n cacheRootFor(platform: string | null): string {\n return join(this.#cacheBaseRoot, platform ?? 'default')\n }\n\n scan(options: MetroCompilerScanOptions): Promise<MetroCompilerGeneration> {\n return this.#enqueue(() => this.#scan(options))\n }\n\n async #scan(\n options: MetroCompilerScanOptions,\n preparedProject?: MetroCompilerProject,\n preparedProjectSources?: string[]\n ): Promise<MetroCompilerGeneration> {\n this.#scanOptions = options\n this.#publishedGeneration = null\n const diagnostics: MetroCompilerDiagnostic[] = []\n const entryRoots = (\n await Promise.all(\n options.entryFiles.map((path) => realpath(resolve(this.config.projectRoot, path)))\n )\n ).sort(compareCodeUnits)\n const compilerProject =\n preparedProject ??\n (await this.#loadCompilerProject(options, entryRoots[0], diagnostics))\n this.#projectGeneration = compilerProject.generation\n const projectSources =\n preparedProjectSources ?? (await walkProjectSources(this.config.projectRoot))\n const projectSourcesHash = contentHash(JSON.stringify(projectSources))\n this.#scanOptionsHash = scanOptionsHash(\n options,\n compilerProject.generation,\n projectSourcesHash\n )\n this.#installCaches(options, compilerProject, projectSourcesHash)\n const speculativeRoots = new Set<string>()\n for (const file of projectSources) {\n try {\n const id = await realpath(file)\n if (!entryRoots.includes(id)) speculativeRoots.add(id)\n } catch {}\n }\n const roots = [...new Set([...entryRoots, ...speculativeRoots])].sort(\n compareCodeUnits\n )\n const queue = [...roots]\n const queued = new Set(queue)\n for (const watcher of this.#watchers.values()) watcher.close()\n this.#watchers.clear()\n this.#records.clear()\n\n while (queue.length) {\n const path = queue.shift()!\n try {\n const record = await this.#compileRecord(path, options, diagnostics)\n this.#records.set(record.input.id, record)\n for (const dependency of record.input.imports) {\n if (\n dependency.external ||\n !isCompilerSourceFile(dependency.resolvedId) ||\n queued.has(dependency.resolvedId)\n ) {\n continue\n }\n queued.add(dependency.resolvedId)\n queue.push(dependency.resolvedId)\n }\n } catch (error) {\n // walk-seeded files are speculative: nothing proved the bundle needs\n // them, so a compile failure is not a build diagnostic. If the bundle\n // does include one, the transformer's plan-miss warning still fires.\n if (speculativeRoots.has(path)) continue\n const diagnostic = metroDiagnostic(\n 'metro/transform-failed',\n `Failed to compile ${path}: ${error instanceof Error ? error.message : String(error)}`,\n { moduleId: path }\n )\n diagnostics.push(diagnostic)\n this.#report(diagnostic)\n }\n }\n\n if (\n !compilerProject.projectInfo.tamaguiConfig ||\n !compilerProject.projectInfo.components\n ) {\n throw new Error('Metro compiler project has no Tamagui config or components')\n }\n this.#tamaguiConfig = compilerProject.projectInfo.tamaguiConfig\n this.#entries.clear()\n const unplanned = await this.#restorePlans(options)\n const zero = this.config.zero\n // a scan that restores everything builds no graph, so the previous scan's\n // graph must not survive as this scan's answer\n this.#graph = null\n this.#host = null\n // Nothing left to compile and no live session to serve means the analyzer\n // graph is never read, so it is never built. Parsing and linking every\n // project source is the other half of the prepass cost.\n if (unplanned.length || retainsLiveGraph(options)) {\n this.#graph = new ProjectGraph(yukuFactory, {\n modules: [...this.#records.values()].map(({ input }) => input),\n })\n this.#host = createTamaguiCompilerHost({\n target: compilerTarget(options.platform),\n tamaguiConfig: compilerProject.projectInfo.tamaguiConfig,\n components: compilerProject.projectInfo.components,\n componentModules: compilerProject.componentModules.map(({ moduleName, id }) => ({\n moduleName,\n resolvedId: id,\n })),\n disablePartialExtraction: compilerProject.disablePartialExtraction,\n experimentalNativeFastPath: compilerProject.experimentalNativeFastPath,\n zeroRuntime: compilerProject.zeroRuntime,\n })\n if (zero) {\n if (zero.isEnforcing) {\n Static.assertZeroConfigDrivers(compilerProject.projectInfo.tamaguiConfig)\n }\n zero.plansRestoredFromCache = false\n zero.configCSS = compilerProject.projectInfo.tamaguiConfig.getCSS?.() ?? ''\n zero.artifact.clearGraphs()\n zero.bridges.clear()\n zero.violations.length = 0\n zero.transformed.clear()\n zero.erasedExports.clear()\n // The zero contract applies to an ENTRY GRAPH. Metro's frontend plans\n // every project source by directory walk, so a config module, a control\n // fixture, or another entry's page would otherwise be judged against a\n // contract they are not part of.\n this.#zeroEntryGraph = this.#reachableFrom(entryRoots.map(resolvedModuleId))\n }\n for (const id of unplanned) this.#refreshEntry(id)\n await this.#storePlans(unplanned)\n }\n if (zero) {\n // Written in both modes and before the failure, so `report` and `enforce`\n // emit the identical list and only their exit differs.\n Static.writeZeroViolationReport(zero.resolved.outDir, 'metro-zero', {\n integration: 'metro-web',\n mode: zero.isEnforcing ? 'enforce' : 'report',\n violations: zero.violations,\n })\n if (zero.isEnforcing && zero.violations.length) {\n throw new Error(Static.formatZeroViolations(zero.violations))\n }\n }\n const totalFound = [...this.#entries.values()].reduce(\n (sum, entry) => sum + entry.plan.stats.found,\n 0\n )\n if (this.#entries.size > 0 && totalFound === 0) {\n const componentNames = compilerProject.componentModules.map(\n ({ moduleName }) => moduleName\n )\n const cjsComponentImporters = [...this.#records.values()].filter((record) =>\n record.requireSpecifiers.some((specifier) =>\n componentNames.some(\n (name) => specifier === name || specifier.startsWith(`${name}/`)\n )\n )\n ).length\n if (cjsComponentImporters > 0) {\n const diagnostic = metroDiagnostic(\n 'metro/no-linked-components',\n `The Tamagui compiler linked 0 components across ${this.#entries.size} modules even though ` +\n `${cjsComponentImporters} module(s) reference ${componentNames.join(', ')} through require() calls. ` +\n `Metro compiled modules to CommonJS before the compiler could analyze them, so component ` +\n `imports cannot be linked and nothing will be optimized. Enable experimentalImportSupport ` +\n `in your transformer's getTransformOptions (Expo enables it by default) to restore ` +\n `Tamagui compilation.`\n )\n diagnostics.push(diagnostic)\n this.#report(diagnostic)\n }\n }\n const generation = await this.#publish(options.platform)\n const moduleIds = [...this.#records.keys()].sort(compareCodeUnits)\n if (this.config.watch !== false && retainsLiveGraph(options)) {\n this.#installWatchers()\n } else if (!retainsLiveGraph(options)) {\n this.#releaseGraph()\n }\n return {\n generation,\n moduleIds,\n diagnostics,\n }\n }\n\n ensureValidCache(options: MetroCompilerScanOptions): Promise<MetroCompilerGeneration> {\n return this.#enqueue(() => this.#ensureValidCache(options))\n }\n\n async #ensureValidCache(\n options: MetroCompilerScanOptions\n ): Promise<MetroCompilerGeneration> {\n const diagnostics: MetroCompilerDiagnostic[] = []\n const firstEntry = options.entryFiles[0]\n const importer = firstEntry\n ? await realpath(resolve(this.config.projectRoot, firstEntry))\n : this.config.projectRoot\n const compilerProject = await this.#loadCompilerProject(\n options,\n importer,\n diagnostics\n )\n const cache = new MetroCompilerCache(this.cacheRootFor(options.platform))\n const validation = await cache.validate()\n const projectSources = await walkProjectSources(this.config.projectRoot)\n const optionsHash = scanOptionsHash(\n options,\n compilerProject.generation,\n contentHash(JSON.stringify(projectSources))\n )\n if (\n validation.valid &&\n validation.generation &&\n validation.optionsHash === optionsHash &&\n (await this.#sourcesAreFresh(validation.sourceHashes)) &&\n ((!retainsLiveGraph(options) && !this.#graph) ||\n (this.#publishedGeneration && this.#scanOptionsHash === optionsHash)) &&\n // A zero build owns the one CSS artifact, and its contents are produced by\n // the scan. Reusing a published plan without restoring the artifact would\n // emit one missing every rule this process never collected, while still\n // deriving TAMAGUI_DID_OUTPUT_CSS from it. The sidecar carries exactly\n // those side effects; without it there is nothing safe to reuse.\n (await this.#rehydrateZeroCSS(cache, validation.generation))\n ) {\n this.#publishedGeneration = validation.generation\n this.#scanOptions = options\n this.#scanOptionsHash = optionsHash\n this.#projectGeneration = compilerProject.generation\n return {\n generation: validation.generation,\n moduleIds: validation.moduleIds,\n diagnostics,\n }\n }\n for (const diagnostic of validation.diagnostics) this.#report(diagnostic)\n await cache.discardManifest()\n return await this.#scan(options, compilerProject, projectSources)\n }\n\n async updateFile(path: string): Promise<MetroCompilerUpdate> {\n let result: MetroCompilerUpdate = {\n changed: false,\n affectedIds: [],\n generation: null,\n }\n return this.#enqueue(async () => {\n const graph = this.#graph\n const options = this.#scanOptions\n if (!graph || !options) return result\n let record: CompiledRecord\n const diagnostics: MetroCompilerDiagnostic[] = []\n try {\n record = await this.#compileRecord(path, options, diagnostics)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n const id = resolvedModuleId(resolve(path))\n const invalidation = graph.removeModule(id)\n this.#watchers.get(id)?.close()\n this.#watchers.delete(id)\n this.#records.delete(id)\n this.#entries.delete(id)\n for (const affected of invalidation.invalidatedIds) {\n if (affected !== id) this.#refreshEntry(affected)\n }\n const generation = await this.#publish(options.platform)\n result = {\n changed: invalidation.changed,\n affectedIds: invalidation.invalidatedIds,\n generation,\n }\n return result\n }\n const diagnostic = metroDiagnostic(\n 'metro/transform-failed',\n `Failed to update ${path}: ${error instanceof Error ? error.message : String(error)}`,\n { moduleId: path }\n )\n this.#report(diagnostic)\n return result\n }\n\n for (const dependency of record.input.imports) {\n if (\n dependency.external ||\n !isCompilerSourceFile(dependency.resolvedId) ||\n this.#records.has(dependency.resolvedId)\n ) {\n continue\n }\n await this.#addDependency(dependency.resolvedId, options, diagnostics)\n }\n this.#records.set(record.input.id, record)\n const invalidation = graph.updateModule(record.input)\n for (const affected of invalidation.invalidatedIds) this.#refreshEntry(affected)\n const generation = invalidation.changed\n ? await this.#publish(options.platform)\n : null\n result = {\n changed: invalidation.changed,\n affectedIds: invalidation.invalidatedIds,\n generation,\n }\n if (this.config.watch !== false && retainsLiveGraph(options)) {\n this.#watchModule(record.input.id)\n }\n return result\n })\n }\n\n /** A published plan only applies while every recorded module source is unchanged. */\n async #sourcesAreFresh(sourceHashes: Record<string, string>): Promise<boolean> {\n const checks = Object.entries(sourceHashes).map(async ([moduleId, sourceHash]) => {\n try {\n return contentHash(await readFile(moduleId, 'utf8')) === sourceHash\n } catch {\n return false\n }\n })\n return (await Promise.all(checks)).every(Boolean)\n }\n\n #enqueue<T>(operation: () => Promise<T>): Promise<T> {\n const queued = this.#operationQueue.then(operation)\n this.#operationQueue = queued.then(\n () => undefined,\n () => undefined\n )\n return queued\n }\n\n close(): Promise<void> {\n return this.#enqueue(async () => {\n this.#releaseGraph()\n })\n }\n\n #releaseGraph(): void {\n for (const watcher of this.#watchers.values()) watcher.close()\n this.#watchers.clear()\n this.#entries.clear()\n this.#records.clear()\n this.#planKeys.clear()\n this.#graph = null\n this.#host = null\n this.#projectGeneration = null\n }\n\n async #loadCompilerProject(\n options: MetroCompilerScanOptions,\n importer: string,\n diagnostics: MetroCompilerDiagnostic[]\n ): Promise<MetroCompilerProject> {\n const target = compilerTarget(options.platform)\n if (this.config.loadCompilerProject) {\n return await this.config.loadCompilerProject(target, options.platform)\n }\n return Static.loadCompilerProject({\n root: this.config.projectRoot,\n target,\n options: this.config.tamaguiOptions ?? {},\n hostVersions: compilerImplementationVersions,\n missingProjectMessage: 'Unable to load the Tamagui project for Metro compilation',\n generation: (projectInfo, componentModules, normalizedOptions) => {\n return contentHash(\n JSON.stringify({\n cacheVersion: METRO_COMPILER_CACHE_VERSION,\n compilerImplementationVersions,\n componentModules,\n configCss: projectInfo.tamaguiConfig?.getCSS?.() ?? '',\n disablePartialExtraction: !!normalizedOptions.disablePartialExtraction,\n experimentalNativeFastPath:\n target === 'native' &&\n normalizedOptions.experimental?.nativeFastPath === true,\n target,\n // the host's diagnostics are mode-aware, so a plan built in one mode is\n // not a plan the other mode may reuse\n zeroRuntime: !!this.config.zero,\n })\n )\n },\n resolveComponents: async (moduleNames) => {\n const componentModules: MetroCompilerProject['componentModules'] = []\n for (const moduleName of moduleNames) {\n try {\n const resolution = this.#resolver.resolve(\n importer,\n { specifier: moduleName, isESMImport: true },\n options.platform\n )\n if (!resolution) continue\n componentModules.push({ moduleName, id: resolution.resolvedId })\n } catch (error) {\n const diagnostic = metroDiagnostic(\n 'metro/resolve-failed',\n `Failed to resolve compiler component ${moduleName}: ${error instanceof Error ? error.message : String(error)}`,\n { moduleId: importer, dependency: moduleName }\n )\n diagnostics.push(diagnostic)\n this.#report(diagnostic)\n }\n }\n return componentModules\n },\n })\n }\n\n async #compileRecord(\n rawPath: string,\n options: MetroCompilerScanOptions,\n diagnostics: MetroCompilerDiagnostic[]\n ): Promise<CompiledRecord> {\n const path = await realpath(resolve(rawPath))\n const source = await readFile(path, 'utf8')\n const sourceHash = contentHash(source)\n const id = resolvedModuleId(path)\n const cache = this.#recordCache\n const identity = this.#recordCacheIdentity\n const key = cache && identity ? contentHash(`${identity}\\0${sourceHash}`) : null\n if (cache && key) {\n const cached = await cache.read(key, (value) => {\n const entry = value as CachedRecord | null\n return entry?.schemaVersion === METRO_RECORD_CACHE_VERSION &&\n entry.sourceHash === sourceHash &&\n Array.isArray(entry.imports) &&\n Array.isArray(entry.requireSpecifiers) &&\n Array.isArray(entry.diagnostics)\n ? entry\n : null\n })\n if (cached) {\n for (const diagnostic of cached.diagnostics) {\n diagnostics.push(diagnostic)\n this.#report(diagnostic)\n }\n return {\n input: { id, source, imports: cached.imports },\n sourceHash,\n requireSpecifiers: cached.requireSpecifiers,\n }\n }\n }\n\n const args = this.#babelArgs(path, source, options)\n const compiled = await compileWithUserBabel(\n this.config.originalBabelTransformerPath,\n args\n )\n const imports: HostResolvedImport[] = []\n const requireSpecifiers: string[] = []\n const recordDiagnostics: MetroCompilerDiagnostic[] = []\n for (const dependency of moduleSpecifiersFromAst(compiled.result.ast)) {\n if (!dependency.isESMImport) requireSpecifiers.push(dependency.specifier)\n try {\n const resolution = this.#resolver.resolve(path, dependency, options.platform)\n if (!resolution) continue\n imports.push({\n specifier: resolution.specifier,\n resolvedId: resolvedModuleId(resolution.resolvedId),\n external: resolution.external,\n })\n } catch (error) {\n recordDiagnostics.push(\n metroDiagnostic(\n 'metro/resolve-failed',\n `Failed to resolve ${dependency.specifier} from ${path}: ${error instanceof Error ? error.message : String(error)}`,\n { moduleId: path, dependency: dependency.specifier }\n )\n )\n }\n }\n for (const diagnostic of recordDiagnostics) {\n diagnostics.push(diagnostic)\n this.#report(diagnostic)\n }\n if (cache && key) {\n await cache.write(key, {\n schemaVersion: METRO_RECORD_CACHE_VERSION,\n sourceHash,\n imports,\n requireSpecifiers,\n diagnostics: recordDiagnostics,\n } satisfies CachedRecord)\n }\n return {\n // The graph and plans operate on raw source: workers apply plan edits to\n // the raw module before their own Babel pass, so plans never depend on\n // this process's Babel output matching the workers' byte for byte.\n input: { id, source, imports },\n sourceHash,\n requireSpecifiers,\n }\n }\n\n #babelOptions(options: MetroCompilerScanOptions): MetroBabelTransformArgs['options'] {\n const transformer = this.config.transformer ?? {}\n return {\n ...options.transform,\n dev: options.dev,\n hot: options.hot,\n platform: options.platform,\n projectRoot: this.config.projectRoot,\n enableBabelRCLookup: transformer.enableBabelRCLookup ?? true,\n enableBabelRuntime: transformer.enableBabelRuntime ?? true,\n hermesParser: transformer.hermesParser ?? false,\n publicPath: transformer.publicPath ?? '/assets',\n }\n }\n\n #babelArgs(\n filename: string,\n src: string,\n options: MetroCompilerScanOptions\n ): MetroBabelTransformArgs {\n return { filename, src, plugins: [], options: this.#babelOptions(options) }\n }\n\n async #addDependency(\n id: ResolvedModuleId,\n options: MetroCompilerScanOptions,\n diagnostics: MetroCompilerDiagnostic[],\n visiting = new Set<ResolvedModuleId>()\n ): Promise<void> {\n if (this.#records.has(id) || visiting.has(id)) return\n visiting.add(id)\n try {\n const record = await this.#compileRecord(id, options, diagnostics)\n for (const dependency of record.input.imports) {\n if (!dependency.external && isCompilerSourceFile(dependency.resolvedId)) {\n await this.#addDependency(dependency.resolvedId, options, diagnostics, visiting)\n }\n }\n this.#records.set(id, record)\n const invalidation = this.#graph?.updateModule(record.input)\n for (const affected of invalidation?.invalidatedIds ?? [id]) {\n this.#refreshEntry(affected)\n }\n if (\n this.config.watch !== false &&\n this.#scanOptions &&\n retainsLiveGraph(this.#scanOptions)\n ) {\n this.#watchModule(id)\n }\n } finally {\n visiting.delete(id)\n }\n }\n\n #refreshEntry(id: ResolvedModuleId): void {\n const graph = this.#graph\n const host = this.#host\n const record = this.#records.get(id)\n if (!graph || !host || !record || !this.#scanOptions || !this.#projectGeneration)\n return\n const target = compilerTarget(this.#scanOptions.platform)\n const plan = lowerModule({\n module: materializeModule(graph, id),\n source: record.input.source,\n target,\n host,\n options: { projectGeneration: this.#projectGeneration },\n })\n // Zero-mode reference erasure rides the same plan. Metro fixes a module's\n // dependencies at resolution time and does no export-level shaking, so the\n // plan a worker applies before Babel is the only point early enough to\n // remove an import from the graph.\n const zeroPlan = this.#zeroPlanFor(id, record.input.source, plan)\n this.#entries.set(id, this.#entryFor(id, record, zeroPlan ?? plan))\n }\n\n /**\n * One plan becomes one cache entry the same way whether the plan was just\n * lowered or read back off disk, so a restored build reports exactly the\n * diagnostics a fresh one did.\n */\n #entryFor(\n id: ResolvedModuleId,\n record: CompiledRecord,\n plan: LoweredModulePlan\n ): MetroCompilerCacheEntry {\n return {\n schemaVersion: METRO_COMPILER_CACHE_VERSION,\n moduleId: id,\n sourceHash: record.sourceHash,\n plan,\n diagnostics: plan.diagnostics.map(\n ({ code, message, dependencyId, span, component }) => {\n const { line, column } = Static.offsetToLineColumn(\n record.input.source,\n span.start\n )\n return metroDiagnostic(\n code.startsWith('linked/')\n ? 'metro/resolve-failed'\n : 'metro/transform-failed',\n message,\n { moduleId: id, dependency: dependencyId, span, line, column, component }\n )\n }\n ),\n }\n }\n\n /**\n * Both per-file caches for this scan. A project with no content stamp gets\n * neither: a stamp that cannot see a config change would serve styles built\n * against the old config, so the answer is no cache rather than a partial one.\n *\n * Zero builds opt out of the plan cache because a zero plan is produced\n * alongside side effects that do not travel in the plan - the CSS artifact,\n * the bridge manifest, the violation list - so replaying one module's plan\n * without them would emit an artifact missing its rules.\n */\n #installCaches(\n options: MetroCompilerScanOptions,\n project: MetroCompilerProject,\n projectSourcesHash: string\n ): void {\n const platform = options.platform ?? 'default'\n const root = defaultPlanCacheRoot(this.config.projectRoot, platform)\n this.#recordCache = new JsonFileCache(\n join(root, 'records'),\n METRO_RECORD_CACHE_VERSION\n )\n this.#recordCacheIdentity = contentHash(\n stableStringify({\n schema: METRO_RECORD_CACHE_VERSION,\n resolver: this.#resolver.version,\n babel: userBabelCacheKey(this.config.originalBabelTransformerPath),\n // resolutions depend on which files exist, so the walked source list is\n // part of a record's identity exactly as it is for the plan manifest\n projectSourcesHash,\n platform,\n transform: this.#babelOptions(options),\n })\n )\n const stamp = project.cacheStamp\n const usePlanCache = typeof stamp === 'string' && stamp !== '' && !this.config.zero\n this.#planCache = usePlanCache ? new ModulePlanCache(join(root, 'plans')) : null\n this.#planCacheStamp = usePlanCache ? stamp : null\n }\n\n /**\n * Fills `#entries` from disk for every module whose whole compile input is\n * unchanged, and returns the ids that still have to be compiled. This is the\n * per-file property: one edited module leaves every other module's entry\n * valid, where the plan manifest would have discarded all of them.\n */\n async #restorePlans(options: MetroCompilerScanOptions): Promise<ResolvedModuleId[]> {\n this.#planKeys.clear()\n const cache = this.#planCache\n const stamp = this.#planCacheStamp\n if (!cache || !stamp) return [...this.#records.keys()].sort(compareCodeUnits)\n const target = compilerTarget(options.platform)\n const identity = {\n stamp,\n target,\n structuralPassHash: `${target}-noop-v1`,\n }\n const nodes = new Map<ResolvedModuleId, ModuleClosureNode | null>()\n const lookup = (id: ResolvedModuleId): ModuleClosureNode | null => {\n let node = nodes.get(id)\n if (node === undefined) {\n const record = this.#records.get(id)\n node = record ? moduleClosureNode(record.input) : null\n nodes.set(id, node)\n }\n return node\n }\n const memo = new Map<ResolvedModuleId, string | null>()\n const unplanned: ResolvedModuleId[] = []\n for (const id of [...this.#records.keys()].sort(compareCodeUnits)) {\n const record = this.#records.get(id)!\n const digest = moduleClosureDigest(id, lookup, memo)\n const key = digest && planCacheKey(identity, id, digest)\n const entry = key && digest ? await cache.read(key, id, digest) : null\n if (entry) {\n this.#entries.set(id, this.#entryFor(id, record, entry.plan))\n continue\n }\n if (key && digest) this.#planKeys.set(id, { key, digest })\n unplanned.push(id)\n }\n return unplanned\n }\n\n async #storePlans(ids: readonly ResolvedModuleId[]): Promise<void> {\n const cache = this.#planCache\n if (!cache) return\n const pending = ids.flatMap((id) => {\n const entry = this.#entries.get(id)\n const key = this.#planKeys.get(id)\n return entry && key ? [{ id, entry, key }] : []\n })\n // a first build writes one file per module, and doing that serially costs\n // seconds on a real project\n for (let index = 0; index < pending.length; index += 32) {\n await Promise.all(\n pending.slice(index, index + 32).map(({ id, entry, key }) =>\n cache.write(key.key, {\n schemaVersion: PLAN_CACHE_SCHEMA_VERSION,\n moduleId: id,\n closureDigest: key.digest,\n plan: entry.plan,\n })\n )\n )\n }\n }\n\n /** Modules reachable from the bundle's entry, over the frontend's own graph. */\n #reachableFrom(roots: readonly ResolvedModuleId[]): Set<ResolvedModuleId> {\n const reached = new Set<ResolvedModuleId>()\n const queue = [...roots]\n while (queue.length) {\n const id = queue.pop()!\n if (reached.has(id)) continue\n reached.add(id)\n for (const dependency of this.#records.get(id)?.input.imports ?? []) {\n if (!dependency.external) queue.push(dependency.resolvedId)\n }\n }\n return reached\n }\n\n /**\n * The zero transform for one module, returning a plan whose edits also carry\n * the static Theme lowering, the island bridge, and reference erasure.\n */\n #zeroPlanFor(\n id: ResolvedModuleId,\n source: string,\n plan: ReturnType<typeof lowerModule>\n ): ReturnType<typeof lowerModule> | null {\n const zero = this.config.zero\n const config = this.#tamaguiConfig\n if (!zero || !config) return null\n\n // An island build is a full-runtime graph: it contributes its compiler\n // atomic CSS to the one artifact and is never erased or judged.\n if (zero.islandBuild) {\n zero.artifact.setIslandModuleCSS(zero.islandBuild, id, plan.css)\n return null\n }\n\n if (this.#zeroEntryGraph && !this.#zeroEntryGraph.has(id)) return null\n // only app-authored modules: a workspace dependency resolves outside\n // node_modules here, and erasing Tamagui's own re-exports would break it\n const relativePath = relative(this.config.projectRoot, id)\n if (\n relativePath === '' ||\n relativePath.startsWith('..') ||\n relativePath.split(/[\\\\/]/).includes('node_modules')\n ) {\n return null\n }\n\n const result = Static.transformZeroModule({\n mode: zero.isEnforcing ? 'enforce' : 'report',\n id,\n root: this.config.projectRoot,\n source,\n plan,\n config,\n isTamaguiSpecifier: (specifier) =>\n specifier === 'tamagui' || specifier.startsWith('@tamagui/'),\n resolveIslandLoader: (specifier) => {\n const islandId = zero.loaderIds.get(zeroModuleKey(resolve(id, '..', specifier)))\n return islandId ? { islandId } : null\n },\n resolveIslandModule: (specifier) =>\n zero.islandModuleIds.get(zeroModuleKey(resolve(id, '..', specifier))) ?? null,\n })\n\n zero.transformed.add(id)\n if (result.erased.exports.length) {\n zero.erasedExports.set(id, result.erased.exports)\n }\n for (const violation of result.violations) {\n const { line, column } = Static.offsetToLineColumn(source, violation.span.start)\n zero.violations.push({\n file: relativePath,\n line,\n column,\n rule: violation.rule,\n code: violation.code,\n component: violation.component,\n message: violation.message,\n })\n }\n if (result.violations.length || !zero.isEnforcing) return null\n\n Static.mergeIslandBridges(zero.bridges, result.bridges)\n for (const [identifier, rules] of result.bridgeCSS) {\n zero.artifact.setBridgeRules(identifier, rules)\n }\n zero.artifact.setZeroModuleCSS(id, plan.css)\n return { ...plan, edits: [...plan.edits, ...result.edits] }\n }\n\n async #publish(platform: string | null): Promise<string> {\n const cache = new MetroCompilerCache(this.cacheRootFor(platform))\n const generation = await cache.publish(\n platform,\n [...this.#entries.values()],\n this.#scanOptionsHash ?? ''\n )\n const zero = this.config.zero\n if (zero && !zero.islandBuild) {\n // the plans and the artifact are the same scan's output, so they are\n // published together or the warm path has nothing safe to reuse\n await cache.publishZeroCSS({\n schemaVersion: METRO_COMPILER_CACHE_VERSION,\n generation,\n configCSS: zero.configCSS,\n zeroModuleCSS: Object.fromEntries(zero.artifact.zeroModuleEntries()),\n bridgeCSS: Object.fromEntries(zero.artifact.bridgeEntries()),\n bridges: Object.fromEntries(zero.bridges),\n })\n }\n this.#publishedGeneration = generation\n return generation\n }\n\n /**\n * Restores the zero build's CSS side effects from the sidecar published with\n * this plan generation. Returns false when there is nothing trustworthy to\n * restore, which sends the caller to a full scan.\n */\n async #rehydrateZeroCSS(cache: MetroCompilerCache, generation: string) {\n const zero = this.config.zero\n if (!zero || zero.islandBuild) return true\n const sidecar = await cache.readZeroCSS(generation)\n if (!sidecar) return false\n zero.artifact.clearGraphs()\n zero.bridges.clear()\n zero.violations.length = 0\n zero.configCSS = sidecar.configCSS\n for (const [moduleId, css] of Object.entries(sidecar.zeroModuleCSS)) {\n zero.artifact.setZeroModuleCSS(moduleId, css)\n }\n for (const [bridgeId, css] of Object.entries(sidecar.bridgeCSS)) {\n zero.artifact.setBridgeRules(bridgeId, css)\n }\n for (const [islandId, bridges] of Object.entries(sidecar.bridges)) {\n zero.bridges.set(islandId, bridges as IslandThemeBridge[])\n }\n zero.plansRestoredFromCache = true\n return true\n }\n\n #installWatchers(): void {\n for (const id of this.#records.keys()) this.#watchModule(id)\n }\n\n #watchModule(id: ResolvedModuleId): void {\n if (this.#watchers.has(id)) return\n try {\n const watcher = watch(id, { persistent: false }, () => {\n void this.updateFile(id)\n })\n watcher.unref()\n this.#watchers.set(id, watcher)\n } catch {\n // A concurrent delete is handled by the importer's next invalidation.\n }\n }\n\n #report(diagnostic: MetroCompilerDiagnostic): void {\n this.config.reportDiagnostic?.(diagnostic)\n }\n}\n\nexport function describeMetroCompilerRoot(projectRoot: string, moduleId: string): string {\n const path = relative(projectRoot, moduleId)\n return path.startsWith('..') ? basename(moduleId) : path\n}\n"
9
+ "import { existsSync, watch, type FSWatcher } from 'node:fs'\nimport { readFile, readdir, realpath } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, join, relative, resolve, sep } from 'node:path'\n\nimport ignore, { type Ignore } from 'ignore'\n\nimport {\n JsonFileCache,\n ModulePlanCache,\n PLAN_CACHE_SCHEMA_VERSION,\n ProjectGraph,\n contentHash,\n defaultPlanCacheRoot,\n isTamaguiSpecifier,\n lowerModule,\n materializeModule,\n moduleClosureDigest,\n moduleClosureNode,\n planCacheKey,\n resolvedModuleId,\n stableStringify,\n yukuFactory,\n type CompilerLoweringHost,\n type CompilerTarget,\n type HostModuleInput,\n type HostResolvedImport,\n type LoweredModulePlan,\n type ModuleClosureNode,\n type ResolvedModuleId,\n} from '@tamagui/compiler-core'\nimport Static, { createTamaguiCompilerHost } from '@tamagui/static'\nimport type {\n IslandThemeBridge,\n TamaguiOptions,\n TamaguiProjectInfo,\n} from '@tamagui/static'\n\nimport {\n compileWithUserBabel,\n userBabelCacheKey,\n type MetroBabelTransformArgs,\n} from './babel'\nimport { zeroModuleKey, type MetroZeroController } from './zeroRuntime'\nimport {\n METRO_COMPILER_CACHE_VERSION,\n MetroCompilerCache,\n defaultMetroCompilerCacheRoot,\n type MetroCompilerCacheEntry,\n} from './compilerCache'\nimport { metroDiagnostic, type MetroCompilerDiagnostic } from './diagnostics'\nimport {\n createMetroCompilerResolver,\n isCompilerSourceFile,\n moduleSpecifiersFromAst,\n type MetroResolverConfig,\n} from './metroResolver'\n\ninterface CompiledRecord {\n input: HostModuleInput\n sourceHash: string\n /** Specifiers that reached the compiled output as require() calls instead of imports. */\n requireSpecifiers: string[]\n}\n\n/**\n * Metro runs the user's whole Babel transformer over every project source just\n * to read its import specifiers, which is the single most expensive step of the\n * prepass. The result is a pure function of the module's own bytes plus the\n * resolver and Babel identity, so it caches per file with no closure involved.\n */\nexport const METRO_RECORD_CACHE_VERSION = 1\n\ninterface CachedRecord {\n schemaVersion: typeof METRO_RECORD_CACHE_VERSION\n sourceHash: string\n imports: HostResolvedImport[]\n requireSpecifiers: string[]\n /** Resolve failures replayed on a hit, so a cached record reports what a fresh one did. */\n diagnostics: MetroCompilerDiagnostic[]\n}\n\nexport interface MetroCompilerFrontendConfig extends MetroResolverConfig {\n cacheRoot?: string\n /** Present only for an enforced zero-runtime web build. */\n zero?: MetroZeroController | null\n originalBabelTransformerPath: string\n transformer?: Record<string, any>\n tamaguiOptions?: Partial<TamaguiOptions>\n loadCompilerProject?: (\n target: CompilerTarget,\n platform: string | null\n ) => Promise<MetroCompilerProject>\n watch?: boolean\n reportDiagnostic?: (diagnostic: MetroCompilerDiagnostic) => void\n}\n\nexport interface MetroCompilerProject extends Static.CompilerProject {}\n\nexport interface MetroCompilerScanOptions {\n dev: boolean\n entryFiles: readonly string[]\n hot: boolean\n platform: string | null\n transform?: Record<string, any>\n}\n\nexport interface MetroCompilerGeneration {\n generation: string\n moduleIds: string[]\n diagnostics: MetroCompilerDiagnostic[]\n}\n\nexport interface MetroCompilerUpdate {\n changed: boolean\n affectedIds: string[]\n generation: string | null\n}\n\nfunction compareCodeUnits(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nconst requireFromFrontend = createRequire(\n typeof __filename === 'string' ? __filename : import.meta.url\n)\n\n// upgrading the compiler must invalidate published plans even when the Tamagui\n// config output is unchanged\nconst compilerImplementationVersions = (\n ['@tamagui/metro-plugin', '@tamagui/static', '@tamagui/compiler-core'] as const\n).map((packageName) => {\n const { version } = requireFromFrontend(`${packageName}/package.json`) as {\n version: string\n }\n return `${packageName}@${version}`\n})\n\nfunction scanOptionsHash(\n options: MetroCompilerScanOptions,\n projectGeneration: string,\n projectSourcesHash: string\n): string {\n return contentHash(JSON.stringify({ options, projectGeneration, projectSourcesHash }))\n}\n\n// Metro entries can live inside node_modules (expo-router's entry reaches app\n// source only through require.context), so reachability from the entry alone\n// discovers nothing there. Project source is walked directly and seeded into\n// the scan alongside the entry; imports then extend the graph outside the\n// project root (workspace packages) exactly as before.\n//\n// The walked list is both the seed set and the plan cache's options hash, so it\n// has to be authored source only. Build output is whatever the project already\n// declares as ignored, read with git's own rules: a directory-name list cannot\n// know that `dist-metro`, `out` or `public/assets` are output, and a sibling\n// bundler's content-hashed filenames then re-key the plan cache on every\n// unrelated rebuild, forcing Metro to rescan a project that never changed.\n// `node_modules` is skipped structurally instead, because that is the same\n// externality boundary the resolver draws and it must hold with or without a\n// declaration.\ninterface IgnoreScope {\n dir: string\n matcher: Ignore\n}\n\nconst speculativeWalkExcludedDirs = new Set([\n '__tests__',\n 'e2e',\n 'flows',\n 'plugins',\n 'screenshots',\n 'scripts',\n 'test',\n 'test-results',\n 'tests',\n])\n\nasync function walkProjectSources(root: string): Promise<string[]> {\n // git reads every .gitignore from the repository root down to the file, so an\n // app nested in a monorepo inherits the declarations made above it\n const inherited: string[] = []\n let ancestor = root\n while (!existsSync(join(ancestor, '.git'))) {\n const parent = dirname(ancestor)\n if (parent === ancestor) break\n inherited.unshift(parent)\n ancestor = parent\n }\n const rootScopes: IgnoreScope[] = []\n for (const dir of inherited) {\n const source = await readFile(join(dir, '.gitignore'), 'utf8').catch(() => null)\n if (source) rootScopes.push({ dir, matcher: ignore().add(source) })\n }\n\n const found: string[] = []\n const stack: { dir: string; scopes: IgnoreScope[] }[] = [\n { dir: root, scopes: rootScopes },\n ]\n while (stack.length) {\n const { dir, scopes } = stack.pop()!\n let entries\n try {\n entries = await readdir(dir, { withFileTypes: true })\n } catch {\n continue\n }\n let active = scopes\n if (entries.some((entry) => entry.isFile() && entry.name === '.gitignore')) {\n const source = await readFile(join(dir, '.gitignore'), 'utf8').catch(() => null)\n if (source) active = [...scopes, { dir, matcher: ignore().add(source) }]\n }\n for (const entry of entries) {\n if (entry.name.startsWith('.') || entry.name === 'node_modules') continue\n const isDirectory = entry.isDirectory()\n if (isDirectory && speculativeWalkExcludedDirs.has(entry.name)) continue\n if (!isDirectory && !(entry.isFile() && isCompilerSourceFile(entry.name))) continue\n if (\n !isDirectory &&\n (/(?:^|[-.])(?:probe|run|spec|tests?)(?:[-.]|$)/i.test(entry.name) ||\n /\\.(?:build|config|workspace)\\.[cm]?[jt]sx?$/.test(entry.name))\n ) {\n continue\n }\n const path = join(dir, entry.name)\n let ignored = false\n for (const scope of active) {\n const relativePath = relative(scope.dir, path)\n if (!relativePath || relativePath.startsWith('..')) continue\n const candidate = relativePath.split(sep).join('/') + (isDirectory ? '/' : '')\n if (scope.matcher.ignores(candidate)) {\n ignored = true\n break\n }\n }\n if (ignored) continue\n if (isDirectory) stack.push({ dir: path, scopes: active })\n else found.push(path)\n }\n }\n return found.sort(compareCodeUnits)\n}\n\nfunction compilerTarget(platform: string | null): CompilerTarget {\n return platform === 'web' ? 'web' : 'native'\n}\n\nfunction retainsLiveGraph(options: MetroCompilerScanOptions): boolean {\n return options.dev && options.hot\n}\n\nexport class MetroCompilerFrontend {\n readonly #cacheBaseRoot: string\n readonly #entries = new Map<ResolvedModuleId, MetroCompilerCacheEntry>()\n readonly #records = new Map<ResolvedModuleId, CompiledRecord>()\n readonly #watchers = new Map<ResolvedModuleId, FSWatcher>()\n readonly #resolver\n #graph: ProjectGraph | null = null\n #host: CompilerLoweringHost | null = null\n #projectGeneration: string | null = null\n #publishedGeneration: string | null = null\n #scanOptions: MetroCompilerScanOptions | null = null\n #scanOptionsHash: string | null = null\n #operationQueue: Promise<void> = Promise.resolve()\n #tamaguiConfig: TamaguiProjectInfo['tamaguiConfig'] | null = null\n #zeroEntryGraph: Set<ResolvedModuleId> | null = null\n readonly #planKeys = new Map<ResolvedModuleId, { key: string; digest: string }>()\n #recordCache: JsonFileCache | null = null\n #recordCacheIdentity: string | null = null\n #planCache: ModulePlanCache | null = null\n #planCacheStamp: string | null = null\n\n constructor(readonly config: MetroCompilerFrontendConfig) {\n this.#cacheBaseRoot =\n config.cacheRoot ?? defaultMetroCompilerCacheRoot(config.projectRoot)\n this.#resolver = createMetroCompilerResolver(config)\n }\n\n get metroResolverVersion(): string {\n return this.#resolver.version\n }\n\n /**\n * Per-file cache accounting for the last scan. The point of these caches is\n * that one edited module leaves every other module's entry valid, and this is\n * how that is observed rather than assumed.\n */\n get compileCacheStats(): {\n plans: { hits: number; misses: number; writes: number }\n records: { hits: number; misses: number; writes: number }\n } {\n const empty = { hits: 0, misses: 0, writes: 0 }\n return {\n plans: this.#planCache?.stats ?? empty,\n records: this.#recordCache?.stats ?? empty,\n }\n }\n\n cacheRootFor(platform: string | null): string {\n return join(this.#cacheBaseRoot, platform ?? 'default')\n }\n\n scan(options: MetroCompilerScanOptions): Promise<MetroCompilerGeneration> {\n return this.#enqueue(() => this.#scan(options))\n }\n\n async #scan(\n options: MetroCompilerScanOptions,\n preparedProject?: MetroCompilerProject,\n preparedProjectSources?: string[]\n ): Promise<MetroCompilerGeneration> {\n this.#scanOptions = options\n this.#publishedGeneration = null\n const diagnostics: MetroCompilerDiagnostic[] = []\n const entryRoots = (\n await Promise.all(\n options.entryFiles.map((path) => realpath(resolve(this.config.projectRoot, path)))\n )\n ).sort(compareCodeUnits)\n const compilerProject =\n preparedProject ??\n (await this.#loadCompilerProject(options, entryRoots[0], diagnostics))\n this.#projectGeneration = compilerProject.generation\n const projectSources =\n preparedProjectSources ?? (await walkProjectSources(this.config.projectRoot))\n const projectSourcesHash = contentHash(JSON.stringify(projectSources))\n this.#scanOptionsHash = scanOptionsHash(\n options,\n compilerProject.generation,\n projectSourcesHash\n )\n this.#installCaches(options, compilerProject, projectSourcesHash)\n const speculativeRoots = new Set<string>()\n for (const file of projectSources) {\n try {\n const id = await realpath(file)\n if (!entryRoots.includes(id)) speculativeRoots.add(id)\n } catch {}\n }\n const roots = [...new Set([...entryRoots, ...speculativeRoots])].sort(\n compareCodeUnits\n )\n const queue = [...roots]\n const queued = new Set(queue)\n for (const watcher of this.#watchers.values()) watcher.close()\n this.#watchers.clear()\n this.#records.clear()\n\n while (queue.length) {\n const path = queue.shift()!\n try {\n const record = await this.#compileRecord(path, options, diagnostics)\n this.#records.set(record.input.id, record)\n for (const dependency of record.input.imports) {\n if (\n dependency.external ||\n !isCompilerSourceFile(dependency.resolvedId) ||\n queued.has(dependency.resolvedId)\n ) {\n continue\n }\n queued.add(dependency.resolvedId)\n queue.push(dependency.resolvedId)\n }\n } catch (error) {\n // walk-seeded files are speculative: nothing proved the bundle needs\n // them, so a compile failure is not a build diagnostic. If the bundle\n // does include one, the transformer's plan-miss warning still fires.\n if (speculativeRoots.has(path)) continue\n const diagnostic = metroDiagnostic(\n 'metro/transform-failed',\n `Failed to compile ${path}: ${error instanceof Error ? error.message : String(error)}`,\n { moduleId: path }\n )\n diagnostics.push(diagnostic)\n this.#report(diagnostic)\n }\n }\n\n if (\n !compilerProject.projectInfo.tamaguiConfig ||\n !compilerProject.projectInfo.components\n ) {\n throw new Error('Metro compiler project has no Tamagui config or components')\n }\n this.#tamaguiConfig = compilerProject.projectInfo.tamaguiConfig\n this.#entries.clear()\n const unplanned = await this.#restorePlans(options)\n const zero = this.config.zero\n // a scan that restores everything builds no graph, so the previous scan's\n // graph must not survive as this scan's answer\n this.#graph = null\n this.#host = null\n // Nothing left to compile and no live session to serve means the analyzer\n // graph is never read, so it is never built. Parsing and linking every\n // project source is the other half of the prepass cost.\n if (unplanned.length || retainsLiveGraph(options)) {\n this.#graph = new ProjectGraph(yukuFactory, {\n modules: [...this.#records.values()].map(({ input }) => input),\n })\n this.#host = createTamaguiCompilerHost({\n target: compilerTarget(options.platform),\n tamaguiConfig: compilerProject.projectInfo.tamaguiConfig,\n components: compilerProject.projectInfo.components,\n componentModules: compilerProject.componentModules.map(({ moduleName, id }) => ({\n moduleName,\n resolvedId: id,\n })),\n disablePartialExtraction: compilerProject.disablePartialExtraction,\n experimentalNativeFastPath: compilerProject.experimentalNativeFastPath,\n zeroRuntime: compilerProject.zeroRuntime,\n })\n if (zero) {\n if (zero.isEnforcing) {\n Static.assertZeroConfigDrivers(compilerProject.projectInfo.tamaguiConfig)\n }\n zero.plansRestoredFromCache = false\n zero.configCSS = compilerProject.projectInfo.tamaguiConfig.getCSS?.() ?? ''\n zero.artifact.clearGraphs()\n zero.bridges.clear()\n zero.violations.length = 0\n zero.transformed.clear()\n zero.erasedExports.clear()\n // The zero contract applies to an ENTRY GRAPH. Metro's frontend plans\n // every project source by directory walk, so a config module, a control\n // fixture, or another entry's page would otherwise be judged against a\n // contract they are not part of.\n this.#zeroEntryGraph = this.#reachableFrom(entryRoots.map(resolvedModuleId))\n }\n for (const id of unplanned) this.#refreshEntry(id)\n await this.#storePlans(unplanned)\n }\n if (zero) {\n // Written in both modes and before the failure, so `report` and `enforce`\n // emit the identical list and only their exit differs.\n Static.writeZeroViolationReport(zero.resolved.outDir, 'metro-zero', {\n integration: 'metro-web',\n mode: zero.isEnforcing ? 'enforce' : 'report',\n violations: zero.violations,\n })\n if (zero.isEnforcing && zero.violations.length) {\n throw new Error(Static.formatZeroViolations(zero.violations))\n }\n }\n const totalFound = [...this.#entries.values()].reduce(\n (sum, entry) => sum + entry.plan.stats.found,\n 0\n )\n if (this.#entries.size > 0 && totalFound === 0) {\n const componentNames = compilerProject.componentModules.map(\n ({ moduleName }) => moduleName\n )\n const cjsComponentImporters = [...this.#records.values()].filter((record) =>\n record.requireSpecifiers.some((specifier) =>\n componentNames.some(\n (name) => specifier === name || specifier.startsWith(`${name}/`)\n )\n )\n ).length\n if (cjsComponentImporters > 0) {\n const diagnostic = metroDiagnostic(\n 'metro/no-linked-components',\n `The Tamagui compiler linked 0 components across ${this.#entries.size} modules even though ` +\n `${cjsComponentImporters} module(s) reference ${componentNames.join(', ')} through require() calls. ` +\n `Metro compiled modules to CommonJS before the compiler could analyze them, so component ` +\n `imports cannot be linked and nothing will be optimized. Enable experimentalImportSupport ` +\n `in your transformer's getTransformOptions (Expo enables it by default) to restore ` +\n `Tamagui compilation.`\n )\n diagnostics.push(diagnostic)\n this.#report(diagnostic)\n }\n }\n const generation = await this.#publish(options.platform)\n const moduleIds = [...this.#records.keys()].sort(compareCodeUnits)\n if (this.config.watch !== false && retainsLiveGraph(options)) {\n this.#installWatchers()\n } else if (!retainsLiveGraph(options)) {\n this.#releaseGraph()\n }\n return {\n generation,\n moduleIds,\n diagnostics,\n }\n }\n\n ensureValidCache(options: MetroCompilerScanOptions): Promise<MetroCompilerGeneration> {\n return this.#enqueue(() => this.#ensureValidCache(options))\n }\n\n async #ensureValidCache(\n options: MetroCompilerScanOptions\n ): Promise<MetroCompilerGeneration> {\n const diagnostics: MetroCompilerDiagnostic[] = []\n const firstEntry = options.entryFiles[0]\n const importer = firstEntry\n ? await realpath(resolve(this.config.projectRoot, firstEntry))\n : this.config.projectRoot\n const compilerProject = await this.#loadCompilerProject(\n options,\n importer,\n diagnostics\n )\n const cache = new MetroCompilerCache(this.cacheRootFor(options.platform))\n const validation = await cache.validate()\n const projectSources = await walkProjectSources(this.config.projectRoot)\n const optionsHash = scanOptionsHash(\n options,\n compilerProject.generation,\n contentHash(JSON.stringify(projectSources))\n )\n if (\n validation.valid &&\n validation.generation &&\n validation.optionsHash === optionsHash &&\n (await this.#sourcesAreFresh(validation.sourceHashes)) &&\n ((!retainsLiveGraph(options) && !this.#graph) ||\n (this.#publishedGeneration && this.#scanOptionsHash === optionsHash)) &&\n // A zero build owns the one CSS artifact, and its contents are produced by\n // the scan. Reusing a published plan without restoring the artifact would\n // emit one missing every rule this process never collected, while still\n // deriving TAMAGUI_DID_OUTPUT_CSS from it. The sidecar carries exactly\n // those side effects; without it there is nothing safe to reuse.\n (await this.#rehydrateZeroCSS(cache, validation.generation))\n ) {\n this.#publishedGeneration = validation.generation\n this.#scanOptions = options\n this.#scanOptionsHash = optionsHash\n this.#projectGeneration = compilerProject.generation\n return {\n generation: validation.generation,\n moduleIds: validation.moduleIds,\n diagnostics,\n }\n }\n for (const diagnostic of validation.diagnostics) this.#report(diagnostic)\n await cache.discardManifest()\n return await this.#scan(options, compilerProject, projectSources)\n }\n\n async updateFile(path: string): Promise<MetroCompilerUpdate> {\n let result: MetroCompilerUpdate = {\n changed: false,\n affectedIds: [],\n generation: null,\n }\n return this.#enqueue(async () => {\n const graph = this.#graph\n const options = this.#scanOptions\n if (!graph || !options) return result\n let record: CompiledRecord\n const diagnostics: MetroCompilerDiagnostic[] = []\n try {\n record = await this.#compileRecord(path, options, diagnostics)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n const id = resolvedModuleId(resolve(path))\n const invalidation = graph.removeModule(id)\n this.#watchers.get(id)?.close()\n this.#watchers.delete(id)\n this.#records.delete(id)\n this.#entries.delete(id)\n for (const affected of invalidation.invalidatedIds) {\n if (affected !== id) this.#refreshEntry(affected)\n }\n const generation = await this.#publish(options.platform)\n result = {\n changed: invalidation.changed,\n affectedIds: invalidation.invalidatedIds,\n generation,\n }\n return result\n }\n const diagnostic = metroDiagnostic(\n 'metro/transform-failed',\n `Failed to update ${path}: ${error instanceof Error ? error.message : String(error)}`,\n { moduleId: path }\n )\n this.#report(diagnostic)\n return result\n }\n\n for (const dependency of record.input.imports) {\n if (\n dependency.external ||\n !isCompilerSourceFile(dependency.resolvedId) ||\n this.#records.has(dependency.resolvedId)\n ) {\n continue\n }\n await this.#addDependency(dependency.resolvedId, options, diagnostics)\n }\n this.#records.set(record.input.id, record)\n const invalidation = graph.updateModule(record.input)\n for (const affected of invalidation.invalidatedIds) this.#refreshEntry(affected)\n const generation = invalidation.changed\n ? await this.#publish(options.platform)\n : null\n result = {\n changed: invalidation.changed,\n affectedIds: invalidation.invalidatedIds,\n generation,\n }\n if (this.config.watch !== false && retainsLiveGraph(options)) {\n this.#watchModule(record.input.id)\n }\n return result\n })\n }\n\n /** A published plan only applies while every recorded module source is unchanged. */\n async #sourcesAreFresh(sourceHashes: Record<string, string>): Promise<boolean> {\n const checks = Object.entries(sourceHashes).map(async ([moduleId, sourceHash]) => {\n try {\n return contentHash(await readFile(moduleId, 'utf8')) === sourceHash\n } catch {\n return false\n }\n })\n return (await Promise.all(checks)).every(Boolean)\n }\n\n #enqueue<T>(operation: () => Promise<T>): Promise<T> {\n const queued = this.#operationQueue.then(operation)\n this.#operationQueue = queued.then(\n () => undefined,\n () => undefined\n )\n return queued\n }\n\n close(): Promise<void> {\n return this.#enqueue(async () => {\n this.#releaseGraph()\n })\n }\n\n #releaseGraph(): void {\n for (const watcher of this.#watchers.values()) watcher.close()\n this.#watchers.clear()\n this.#entries.clear()\n this.#records.clear()\n this.#planKeys.clear()\n this.#graph = null\n this.#host = null\n this.#projectGeneration = null\n }\n\n async #loadCompilerProject(\n options: MetroCompilerScanOptions,\n importer: string,\n diagnostics: MetroCompilerDiagnostic[]\n ): Promise<MetroCompilerProject> {\n const target = compilerTarget(options.platform)\n if (this.config.loadCompilerProject) {\n return await this.config.loadCompilerProject(target, options.platform)\n }\n return Static.loadCompilerProject({\n root: this.config.projectRoot,\n target,\n options: this.config.tamaguiOptions ?? {},\n hostVersions: compilerImplementationVersions,\n missingProjectMessage: 'Unable to load the Tamagui project for Metro compilation',\n generation: (projectInfo, componentModules, normalizedOptions) => {\n return contentHash(\n JSON.stringify({\n cacheVersion: METRO_COMPILER_CACHE_VERSION,\n compilerImplementationVersions,\n componentModules,\n configCss: projectInfo.tamaguiConfig?.getCSS?.() ?? '',\n disablePartialExtraction: !!normalizedOptions.disablePartialExtraction,\n experimentalNativeFastPath:\n target === 'native' &&\n normalizedOptions.experimental?.nativeFastPath === true,\n target,\n // the host's diagnostics are mode-aware, so a plan built in one mode is\n // not a plan the other mode may reuse\n zeroRuntime: !!this.config.zero,\n })\n )\n },\n resolveComponents: async (moduleNames) => {\n const componentModules: MetroCompilerProject['componentModules'] = []\n for (const moduleName of moduleNames) {\n try {\n const resolution = this.#resolver.resolve(\n importer,\n { specifier: moduleName, isESMImport: true },\n options.platform\n )\n if (!resolution) continue\n componentModules.push({ moduleName, id: resolution.resolvedId })\n } catch (error) {\n const diagnostic = metroDiagnostic(\n 'metro/resolve-failed',\n `Failed to resolve compiler component ${moduleName}: ${error instanceof Error ? error.message : String(error)}`,\n { moduleId: importer, dependency: moduleName }\n )\n diagnostics.push(diagnostic)\n this.#report(diagnostic)\n }\n }\n return componentModules\n },\n })\n }\n\n async #compileRecord(\n rawPath: string,\n options: MetroCompilerScanOptions,\n diagnostics: MetroCompilerDiagnostic[]\n ): Promise<CompiledRecord> {\n const path = await realpath(resolve(rawPath))\n const source = await readFile(path, 'utf8')\n const sourceHash = contentHash(source)\n const id = resolvedModuleId(path)\n const cache = this.#recordCache\n const identity = this.#recordCacheIdentity\n const key = cache && identity ? contentHash(`${identity}\\0${sourceHash}`) : null\n if (cache && key) {\n const cached = await cache.read(key, (value) => {\n const entry = value as CachedRecord | null\n return entry?.schemaVersion === METRO_RECORD_CACHE_VERSION &&\n entry.sourceHash === sourceHash &&\n Array.isArray(entry.imports) &&\n Array.isArray(entry.requireSpecifiers) &&\n Array.isArray(entry.diagnostics)\n ? entry\n : null\n })\n if (cached) {\n for (const diagnostic of cached.diagnostics) {\n diagnostics.push(diagnostic)\n this.#report(diagnostic)\n }\n return {\n input: { id, source, imports: cached.imports },\n sourceHash,\n requireSpecifiers: cached.requireSpecifiers,\n }\n }\n }\n\n const args = this.#babelArgs(path, source, options)\n const compiled = await compileWithUserBabel(\n this.config.originalBabelTransformerPath,\n args\n )\n const imports: HostResolvedImport[] = []\n const requireSpecifiers: string[] = []\n const recordDiagnostics: MetroCompilerDiagnostic[] = []\n for (const dependency of moduleSpecifiersFromAst(compiled.result.ast)) {\n if (!dependency.isESMImport) requireSpecifiers.push(dependency.specifier)\n try {\n const resolution = this.#resolver.resolve(path, dependency, options.platform)\n if (!resolution) continue\n imports.push({\n specifier: resolution.specifier,\n resolvedId: resolvedModuleId(resolution.resolvedId),\n external: resolution.external,\n })\n } catch (error) {\n recordDiagnostics.push(\n metroDiagnostic(\n 'metro/resolve-failed',\n `Failed to resolve ${dependency.specifier} from ${path}: ${error instanceof Error ? error.message : String(error)}`,\n { moduleId: path, dependency: dependency.specifier }\n )\n )\n }\n }\n for (const diagnostic of recordDiagnostics) {\n diagnostics.push(diagnostic)\n this.#report(diagnostic)\n }\n if (cache && key) {\n await cache.write(key, {\n schemaVersion: METRO_RECORD_CACHE_VERSION,\n sourceHash,\n imports,\n requireSpecifiers,\n diagnostics: recordDiagnostics,\n } satisfies CachedRecord)\n }\n return {\n // The graph and plans operate on raw source: workers apply plan edits to\n // the raw module before their own Babel pass, so plans never depend on\n // this process's Babel output matching the workers' byte for byte.\n input: { id, source, imports },\n sourceHash,\n requireSpecifiers,\n }\n }\n\n #babelOptions(options: MetroCompilerScanOptions): MetroBabelTransformArgs['options'] {\n const transformer = this.config.transformer ?? {}\n return {\n ...options.transform,\n dev: options.dev,\n hot: options.hot,\n platform: options.platform,\n projectRoot: this.config.projectRoot,\n enableBabelRCLookup: transformer.enableBabelRCLookup ?? true,\n enableBabelRuntime: transformer.enableBabelRuntime ?? true,\n hermesParser: transformer.hermesParser ?? false,\n publicPath: transformer.publicPath ?? '/assets',\n }\n }\n\n #babelArgs(\n filename: string,\n src: string,\n options: MetroCompilerScanOptions\n ): MetroBabelTransformArgs {\n return { filename, src, plugins: [], options: this.#babelOptions(options) }\n }\n\n async #addDependency(\n id: ResolvedModuleId,\n options: MetroCompilerScanOptions,\n diagnostics: MetroCompilerDiagnostic[],\n visiting = new Set<ResolvedModuleId>()\n ): Promise<void> {\n if (this.#records.has(id) || visiting.has(id)) return\n visiting.add(id)\n try {\n const record = await this.#compileRecord(id, options, diagnostics)\n for (const dependency of record.input.imports) {\n if (!dependency.external && isCompilerSourceFile(dependency.resolvedId)) {\n await this.#addDependency(dependency.resolvedId, options, diagnostics, visiting)\n }\n }\n this.#records.set(id, record)\n const invalidation = this.#graph?.updateModule(record.input)\n for (const affected of invalidation?.invalidatedIds ?? [id]) {\n this.#refreshEntry(affected)\n }\n if (\n this.config.watch !== false &&\n this.#scanOptions &&\n retainsLiveGraph(this.#scanOptions)\n ) {\n this.#watchModule(id)\n }\n } finally {\n visiting.delete(id)\n }\n }\n\n #refreshEntry(id: ResolvedModuleId): void {\n const graph = this.#graph\n const host = this.#host\n const record = this.#records.get(id)\n if (!graph || !host || !record || !this.#scanOptions || !this.#projectGeneration)\n return\n const target = compilerTarget(this.#scanOptions.platform)\n const plan = lowerModule({\n module: materializeModule(graph, id),\n source: record.input.source,\n target,\n host,\n options: { projectGeneration: this.#projectGeneration },\n })\n // Zero-mode reference erasure rides the same plan. Metro fixes a module's\n // dependencies at resolution time and does no export-level shaking, so the\n // plan a worker applies before Babel is the only point early enough to\n // remove an import from the graph.\n const zeroPlan = this.#zeroPlanFor(id, record.input.source, plan)\n this.#entries.set(id, this.#entryFor(id, record, zeroPlan ?? plan))\n }\n\n /**\n * One plan becomes one cache entry the same way whether the plan was just\n * lowered or read back off disk, so a restored build reports exactly the\n * diagnostics a fresh one did.\n */\n #entryFor(\n id: ResolvedModuleId,\n record: CompiledRecord,\n plan: LoweredModulePlan\n ): MetroCompilerCacheEntry {\n return {\n schemaVersion: METRO_COMPILER_CACHE_VERSION,\n moduleId: id,\n sourceHash: record.sourceHash,\n plan,\n diagnostics: plan.diagnostics.map(\n ({ code, message, dependencyId, span, component }) => {\n const { line, column } = Static.offsetToLineColumn(\n record.input.source,\n span.start\n )\n return metroDiagnostic(\n code.startsWith('linked/')\n ? 'metro/resolve-failed'\n : 'metro/transform-failed',\n message,\n { moduleId: id, dependency: dependencyId, span, line, column, component }\n )\n }\n ),\n }\n }\n\n /**\n * Both per-file caches for this scan. A project with no content stamp gets\n * neither: a stamp that cannot see a config change would serve styles built\n * against the old config, so the answer is no cache rather than a partial one.\n *\n * Zero builds opt out of the plan cache because a zero plan is produced\n * alongside side effects that do not travel in the plan - the CSS artifact,\n * the bridge manifest, the violation list - so replaying one module's plan\n * without them would emit an artifact missing its rules.\n */\n #installCaches(\n options: MetroCompilerScanOptions,\n project: MetroCompilerProject,\n projectSourcesHash: string\n ): void {\n const platform = options.platform ?? 'default'\n const root = defaultPlanCacheRoot(this.config.projectRoot, platform)\n this.#recordCache = new JsonFileCache(\n join(root, 'records'),\n METRO_RECORD_CACHE_VERSION\n )\n this.#recordCacheIdentity = contentHash(\n stableStringify({\n schema: METRO_RECORD_CACHE_VERSION,\n resolver: this.#resolver.version,\n babel: userBabelCacheKey(this.config.originalBabelTransformerPath),\n // resolutions depend on which files exist, so the walked source list is\n // part of a record's identity exactly as it is for the plan manifest\n projectSourcesHash,\n platform,\n transform: this.#babelOptions(options),\n })\n )\n const stamp = project.cacheStamp\n const usePlanCache = typeof stamp === 'string' && stamp !== '' && !this.config.zero\n this.#planCache = usePlanCache ? new ModulePlanCache(join(root, 'plans')) : null\n this.#planCacheStamp = usePlanCache ? stamp : null\n }\n\n /**\n * Fills `#entries` from disk for every module whose whole compile input is\n * unchanged, and returns the ids that still have to be compiled. This is the\n * per-file property: one edited module leaves every other module's entry\n * valid, where the plan manifest would have discarded all of them.\n */\n async #restorePlans(options: MetroCompilerScanOptions): Promise<ResolvedModuleId[]> {\n this.#planKeys.clear()\n const cache = this.#planCache\n const stamp = this.#planCacheStamp\n if (!cache || !stamp) return [...this.#records.keys()].sort(compareCodeUnits)\n const target = compilerTarget(options.platform)\n const identity = {\n stamp,\n target,\n structuralPassHash: `${target}-noop-v1`,\n }\n const nodes = new Map<ResolvedModuleId, ModuleClosureNode | null>()\n const lookup = (id: ResolvedModuleId): ModuleClosureNode | null => {\n let node = nodes.get(id)\n if (node === undefined) {\n const record = this.#records.get(id)\n node = record ? moduleClosureNode(record.input) : null\n nodes.set(id, node)\n }\n return node\n }\n const memo = new Map<ResolvedModuleId, string | null>()\n const unplanned: ResolvedModuleId[] = []\n for (const id of [...this.#records.keys()].sort(compareCodeUnits)) {\n const record = this.#records.get(id)!\n const digest = moduleClosureDigest(id, lookup, memo)\n const key = digest && planCacheKey(identity, id, digest)\n const entry = key && digest ? await cache.read(key, id, digest) : null\n if (entry) {\n this.#entries.set(id, this.#entryFor(id, record, entry.plan))\n continue\n }\n if (key && digest) this.#planKeys.set(id, { key, digest })\n unplanned.push(id)\n }\n return unplanned\n }\n\n async #storePlans(ids: readonly ResolvedModuleId[]): Promise<void> {\n const cache = this.#planCache\n if (!cache) return\n const pending = ids.flatMap((id) => {\n const entry = this.#entries.get(id)\n const key = this.#planKeys.get(id)\n return entry && key ? [{ id, entry, key }] : []\n })\n // a first build writes one file per module, and doing that serially costs\n // seconds on a real project\n for (let index = 0; index < pending.length; index += 32) {\n await Promise.all(\n pending.slice(index, index + 32).map(({ id, entry, key }) =>\n cache.write(key.key, {\n schemaVersion: PLAN_CACHE_SCHEMA_VERSION,\n moduleId: id,\n closureDigest: key.digest,\n plan: entry.plan,\n })\n )\n )\n }\n }\n\n /** Modules reachable from the bundle's entry, over the frontend's own graph. */\n #reachableFrom(roots: readonly ResolvedModuleId[]): Set<ResolvedModuleId> {\n const reached = new Set<ResolvedModuleId>()\n const queue = [...roots]\n while (queue.length) {\n const id = queue.pop()!\n if (reached.has(id)) continue\n reached.add(id)\n for (const dependency of this.#records.get(id)?.input.imports ?? []) {\n if (!dependency.external) queue.push(dependency.resolvedId)\n }\n }\n return reached\n }\n\n /**\n * The zero transform for one module, returning a plan whose edits also carry\n * the static Theme lowering, the island bridge, and reference erasure.\n */\n #zeroPlanFor(\n id: ResolvedModuleId,\n source: string,\n plan: ReturnType<typeof lowerModule>\n ): ReturnType<typeof lowerModule> | null {\n const zero = this.config.zero\n const config = this.#tamaguiConfig\n if (!zero || !config) return null\n\n // An island build is a full-runtime graph: it contributes its compiler\n // atomic CSS to the one artifact and is never erased or judged.\n if (zero.islandBuild) {\n zero.artifact.setIslandModuleCSS(zero.islandBuild, id, plan.css)\n return null\n }\n\n if (this.#zeroEntryGraph && !this.#zeroEntryGraph.has(id)) return null\n // only app-authored modules: a workspace dependency resolves outside\n // node_modules here, and erasing Tamagui's own re-exports would break it\n const relativePath = relative(this.config.projectRoot, id)\n if (\n relativePath === '' ||\n relativePath.startsWith('..') ||\n relativePath.split(/[\\\\/]/).includes('node_modules')\n ) {\n return null\n }\n\n const result = Static.transformZeroModule({\n mode: zero.isEnforcing ? 'enforce' : 'report',\n id,\n root: this.config.projectRoot,\n source,\n plan,\n config,\n isTamaguiSpecifier,\n resolveIslandLoader: (specifier) => {\n const islandId = zero.loaderIds.get(zeroModuleKey(resolve(id, '..', specifier)))\n return islandId ? { islandId } : null\n },\n resolveIslandModule: (specifier) =>\n zero.islandModuleIds.get(zeroModuleKey(resolve(id, '..', specifier))) ?? null,\n })\n\n zero.transformed.add(id)\n if (result.erased.exports.length) {\n zero.erasedExports.set(id, result.erased.exports)\n }\n for (const violation of result.violations) {\n const { line, column } = Static.offsetToLineColumn(source, violation.span.start)\n zero.violations.push({\n file: relativePath,\n line,\n column,\n rule: violation.rule,\n code: violation.code,\n component: violation.component,\n message: violation.message,\n })\n }\n if (result.violations.length || !zero.isEnforcing) return null\n\n Static.mergeIslandBridges(zero.bridges, result.bridges)\n for (const [identifier, rules] of result.bridgeCSS) {\n zero.artifact.setBridgeRules(identifier, rules)\n }\n zero.artifact.setZeroModuleCSS(id, plan.css)\n return { ...plan, edits: [...plan.edits, ...result.edits] }\n }\n\n async #publish(platform: string | null): Promise<string> {\n const cache = new MetroCompilerCache(this.cacheRootFor(platform))\n const generation = await cache.publish(\n platform,\n [...this.#entries.values()],\n this.#scanOptionsHash ?? ''\n )\n const zero = this.config.zero\n if (zero && !zero.islandBuild) {\n // the plans and the artifact are the same scan's output, so they are\n // published together or the warm path has nothing safe to reuse\n await cache.publishZeroCSS({\n schemaVersion: METRO_COMPILER_CACHE_VERSION,\n generation,\n configCSS: zero.configCSS,\n zeroModuleCSS: Object.fromEntries(zero.artifact.zeroModuleEntries()),\n bridgeCSS: Object.fromEntries(zero.artifact.bridgeEntries()),\n bridges: Object.fromEntries(zero.bridges),\n })\n }\n this.#publishedGeneration = generation\n return generation\n }\n\n /**\n * Restores the zero build's CSS side effects from the sidecar published with\n * this plan generation. Returns false when there is nothing trustworthy to\n * restore, which sends the caller to a full scan.\n */\n async #rehydrateZeroCSS(cache: MetroCompilerCache, generation: string) {\n const zero = this.config.zero\n if (!zero || zero.islandBuild) return true\n const sidecar = await cache.readZeroCSS(generation)\n if (!sidecar) return false\n zero.artifact.clearGraphs()\n zero.bridges.clear()\n zero.violations.length = 0\n zero.configCSS = sidecar.configCSS\n for (const [moduleId, css] of Object.entries(sidecar.zeroModuleCSS)) {\n zero.artifact.setZeroModuleCSS(moduleId, css)\n }\n for (const [bridgeId, css] of Object.entries(sidecar.bridgeCSS)) {\n zero.artifact.setBridgeRules(bridgeId, css)\n }\n for (const [islandId, bridges] of Object.entries(sidecar.bridges)) {\n zero.bridges.set(islandId, bridges as IslandThemeBridge[])\n }\n zero.plansRestoredFromCache = true\n return true\n }\n\n #installWatchers(): void {\n for (const id of this.#records.keys()) this.#watchModule(id)\n }\n\n #watchModule(id: ResolvedModuleId): void {\n if (this.#watchers.has(id)) return\n try {\n const watcher = watch(id, { persistent: false }, () => {\n void this.updateFile(id)\n })\n watcher.unref()\n this.#watchers.set(id, watcher)\n } catch {\n // A concurrent delete is handled by the importer's next invalidation.\n }\n }\n\n #report(diagnostic: MetroCompilerDiagnostic): void {\n this.config.reportDiagnostic?.(diagnostic)\n }\n}\n\nexport function describeMetroCompilerRoot(projectRoot: string, moduleId: string): string {\n const path = relative(projectRoot, moduleId)\n return path.startsWith('..') ? basename(moduleId) : path\n}\n"
10
10
  ]
11
11
  }
@@ -1,11 +1,11 @@
1
1
  {
2
- "mappings": "AAIA,cAAc,sBAAsB;AAMpC,SAAS,6BAA6B;AAItC,YAAY,sBAAsB,iBAAiB;;CAEjD;;;;;;CAMA;;;;;;;CAOA;;KAIG,mBAAmB;CACtB;CACA;CACA;CACA;;;AAUF,OAAO,iBAAS,yBACd,aAAa,mBACZ;;;;;;;;;;;;;;;;;;;;;;;;AA2BH,OAAO,iBAAS,YACd,aAAa,kBACb,YAAY,sBACX;AAqFH,SACE,8BACA,oBACA,yBACA,qCACK;AACP,cAAc,+BAA+B;AAC7C,cACE,yBACA,0BACA,2BACK",
2
+ "mappings": "AAIA,cAAc,sBAAsB;AAMpC,SAAS,6BAA6B;AAItC,YAAY,sBAAsB,iBAAiB;;CAEjD;;;;;;CAMA;;;;;;;CAOA;;KAIG,mBAAmB;CACtB;CACA;CACA;CACA;;;AAUF,OAAO,iBAAS,yBACd,aAAa,mBACZ;;;;;;;;;;;;;;;;;;;;;;;;AA2BH,OAAO,iBAAS,YACd,aAAa,kBACb,YAAY,sBACX;AAmFH,SACE,8BACA,oBACA,yBACA,qCACK;AACP,cAAc,+BAA+B;AAC7C,cACE,yBACA,0BACA,2BACK",
3
3
  "names": [],
4
4
  "sources": [
5
5
  "src/index.ts"
6
6
  ],
7
7
  "version": 3,
8
8
  "sourcesContent": [
9
- "import { createRequire } from 'node:module'\nimport { isAbsolute, join } from 'node:path'\n\nimport Static from '@tamagui/static'\nimport type { TamaguiOptions } from '@tamagui/static'\n\nimport { defaultMetroCompilerCacheRoot } from './compilerCache'\nimport { applyMetroZeroRuntime } from './zeroSerializer'\nimport { createMetroZeroController } from './zeroRuntime'\nimport { formatMetroCompilerDiagnostic } from './diagnostics'\nimport { MetroCompilerFrontend } from './frontend'\nimport { writeMetroCompilerTransformerBridge } from './transformer'\nimport { composeMetroGetTransformOptions } from './transformOptions'\n\nexport type MetroTamaguiOptions = TamaguiOptions & {\n /** Override the ignored on-disk handoff used by Metro transform workers. */\n compilerCacheRoot?: string\n /**\n * Set by the zero-runtime island bundle request. An island is a second Metro\n * bundle with `TAMAGUI_RUNTIME='full'` and its own entry, so this invocation\n * keeps the full runtime and only contributes its CSS fragment.\n */\n zeroIslandBuild?: string\n /**\n * Directory the zero CSS artifact and island bundles are published from,\n * relative to the project root.\n *\n * @default 'public'\n */\n zeroPublicDir?: string\n}\n\n// Use a loose type for metro config to avoid version-specific type incompatibilities\ntype MetroConfigInput = {\n projectRoot?: string\n resolver?: any\n transformer?: any\n transformerPath?: string\n [key: string]: any\n}\n\nconst frontends = new WeakMap<object, MetroCompilerFrontend>()\nconst { loadTamaguiBuildConfigSync } = Static\nconst requireFromPlugin = createRequire(\n typeof __filename === 'string' ? __filename : import.meta.url\n)\n\nexport function getMetroCompilerFrontend(\n metroConfig: MetroConfigInput\n): MetroCompilerFrontend | null {\n return frontends.get(metroConfig) ?? null\n}\n\n/**\n * Configure Metro for Tamagui.\n *\n * This is now a simplified wrapper that just ensures CSS is enabled and\n * loads your Tamagui config. For CSS generation, use the CLI:\n *\n * 1. Create a `tamagui.build.ts` with `outputCSS` option\n * 2. Run `tamagui generate` before your build\n * 3. Import the generated CSS in your app's layout\n *\n * @example\n * ```js\n * // metro.config.js\n * const { getDefaultConfig } = require('expo/metro-config')\n * const { withTamagui } = require('@tamagui/metro-plugin')\n *\n * const config = getDefaultConfig(__dirname, { isCSSEnabled: true })\n * module.exports = withTamagui(config, {\n * components: ['tamagui'],\n * config: './tamagui.config.ts',\n * })\n * ```\n */\nexport function withTamagui(\n metroConfig: MetroConfigInput,\n optionsIn?: MetroTamaguiOptions\n): MetroConfigInput {\n const {\n compilerCacheRoot,\n zeroIslandBuild,\n zeroPublicDir = 'public',\n ...tamaguiOptionsIn\n } = optionsIn || {}\n\n const options = loadTamaguiBuildConfigSync(tamaguiOptionsIn)\n const webRuntimeFeatures = Static.resolveWebRuntimeFeatureLiterals(options)\n\n // Ensure CSS files can be resolved\n metroConfig.resolver = {\n ...(metroConfig.resolver as any),\n sourceExts: [...new Set([...(metroConfig.resolver?.sourceExts || []), 'css'])],\n }\n\n // Store tamagui options for potential use by other tools\n metroConfig.transformer = {\n ...metroConfig.transformer,\n tamagui: options,\n }\n\n const zeroProjectRoot = metroConfig.projectRoot ?? process.cwd()\n const zero = createMetroZeroController(\n options,\n zeroProjectRoot,\n zeroIslandBuild ?? null,\n zeroPublicDir\n )\n\n // `report` runs the analysis through the frontend and changes nothing else,\n // so it never installs the serializer that owns the artifact and the gate.\n if (zero?.isEnforcing) {\n applyMetroZeroRuntime(metroConfig, zero)\n }\n\n if (!options.disable) {\n const projectRoot = metroConfig.projectRoot ?? process.cwd()\n const requireFromProject = createRequire(join(projectRoot, 'package.json'))\n // getDefaultConfig sets this to the bare specifier 'metro-babel-transformer',\n // and createRequire needs an absolute path, so resolve either shape here\n const configuredBabelTransformerPath =\n metroConfig.transformer.babelTransformerPath ?? 'metro-babel-transformer'\n const originalBabelTransformerPath = isAbsolute(configuredBabelTransformerPath)\n ? configuredBabelTransformerPath\n : requireFromProject.resolve(configuredBabelTransformerPath)\n const cacheBaseRoot = compilerCacheRoot ?? defaultMetroCompilerCacheRoot(projectRoot)\n const frontend = new MetroCompilerFrontend({\n projectRoot,\n resolver: metroConfig.resolver,\n transformer: metroConfig.transformer,\n tamaguiOptions: options,\n originalBabelTransformerPath,\n cacheRoot: cacheBaseRoot,\n zero,\n reportDiagnostic(diagnostic) {\n console.warn(formatMetroCompilerDiagnostic(diagnostic, projectRoot))\n },\n })\n const transformerFactoryPath = requireFromPlugin.resolve(\n '@tamagui/metro-plugin/transformer'\n )\n metroConfig.transformer.babelTransformerPath = writeMetroCompilerTransformerBridge(\n transformerFactoryPath,\n {\n cacheBaseRoot,\n originalBabelTransformerPath,\n projectRoot,\n // an integration-owned literal, never an ambient shell value\n runtimeLiteral: zero?.isEnforcing && !zero.islandBuild ? 'zero' : 'full',\n webRuntimeFeatures,\n }\n )\n const userGetTransformOptions = metroConfig.transformer.getTransformOptions\n metroConfig.transformer.getTransformOptions = composeMetroGetTransformOptions(\n frontend,\n userGetTransformOptions\n )\n frontends.set(metroConfig, frontend)\n }\n\n return metroConfig\n}\n\nexport {\n METRO_COMPILER_CACHE_VERSION,\n MetroCompilerCache,\n MetroCompilerCacheError,\n defaultMetroCompilerCacheRoot,\n} from './compilerCache'\nexport type { MetroCompilerDiagnostic } from './diagnostics'\nexport type {\n MetroCompilerGeneration,\n MetroCompilerScanOptions,\n MetroCompilerUpdate,\n} from './frontend'\n"
9
+ "import { createRequire } from 'node:module'\nimport { isAbsolute, join } from 'node:path'\n\nimport Static from '@tamagui/static'\nimport type { TamaguiOptions } from '@tamagui/static'\n\nimport { defaultMetroCompilerCacheRoot } from './compilerCache'\nimport { applyMetroZeroRuntime } from './zeroSerializer'\nimport { createMetroZeroController } from './zeroRuntime'\nimport { formatMetroCompilerDiagnostic } from './diagnostics'\nimport { MetroCompilerFrontend } from './frontend'\nimport { writeMetroCompilerTransformerBridge } from './transformer'\nimport { composeMetroGetTransformOptions } from './transformOptions'\n\nexport type MetroTamaguiOptions = TamaguiOptions & {\n /** Override the ignored on-disk handoff used by Metro transform workers. */\n compilerCacheRoot?: string\n /**\n * Set by the zero-runtime island bundle request. An island is a second Metro\n * bundle with `TAMAGUI_RUNTIME='full'` and its own entry, so this invocation\n * keeps the full runtime and only contributes its CSS fragment.\n */\n zeroIslandBuild?: string\n /**\n * Directory the zero CSS artifact and island bundles are published from,\n * relative to the project root.\n *\n * @default 'public'\n */\n zeroPublicDir?: string\n}\n\n// Use a loose type for metro config to avoid version-specific type incompatibilities\ntype MetroConfigInput = {\n projectRoot?: string\n resolver?: any\n transformer?: any\n transformerPath?: string\n [key: string]: any\n}\n\nconst frontends = new WeakMap<object, MetroCompilerFrontend>()\nconst { loadTamaguiBuildConfigSync } = Static\nconst requireFromPlugin = createRequire(\n typeof __filename === 'string' ? __filename : import.meta.url\n)\n\nexport function getMetroCompilerFrontend(\n metroConfig: MetroConfigInput\n): MetroCompilerFrontend | null {\n return frontends.get(metroConfig) ?? null\n}\n\n/**\n * Configure Metro for Tamagui.\n *\n * This is now a simplified wrapper that just ensures CSS is enabled and\n * loads your Tamagui config. For CSS generation, use the CLI:\n *\n * 1. Create a `tamagui.build.ts` with `outputCSS` option\n * 2. Run `tamagui generate` before your build\n * 3. Import the generated CSS in your app's layout\n *\n * @example\n * ```js\n * // metro.config.js\n * const { getDefaultConfig } = require('expo/metro-config')\n * const { withTamagui } = require('@tamagui/metro-plugin')\n *\n * const config = getDefaultConfig(__dirname, { isCSSEnabled: true })\n * module.exports = withTamagui(config, {\n * components: ['tamagui'],\n * config: './tamagui.config.ts',\n * })\n * ```\n */\nexport function withTamagui(\n metroConfig: MetroConfigInput,\n optionsIn?: MetroTamaguiOptions\n): MetroConfigInput {\n const {\n compilerCacheRoot,\n zeroIslandBuild,\n zeroPublicDir = 'public',\n ...tamaguiOptionsIn\n } = optionsIn || {}\n\n const options = loadTamaguiBuildConfigSync(tamaguiOptionsIn)\n\n // Ensure CSS files can be resolved\n metroConfig.resolver = {\n ...(metroConfig.resolver as any),\n sourceExts: [...new Set([...(metroConfig.resolver?.sourceExts || []), 'css'])],\n }\n\n // Store tamagui options for potential use by other tools\n metroConfig.transformer = {\n ...metroConfig.transformer,\n tamagui: options,\n }\n\n const zeroProjectRoot = metroConfig.projectRoot ?? process.cwd()\n const zero = createMetroZeroController(\n options,\n zeroProjectRoot,\n zeroIslandBuild ?? null,\n zeroPublicDir\n )\n\n // `report` runs the analysis through the frontend and changes nothing else,\n // so it never installs the serializer that owns the artifact and the gate.\n if (zero?.isEnforcing) {\n applyMetroZeroRuntime(metroConfig, zero)\n }\n\n if (!options.disable) {\n const projectRoot = metroConfig.projectRoot ?? process.cwd()\n const requireFromProject = createRequire(join(projectRoot, 'package.json'))\n // getDefaultConfig sets this to the bare specifier 'metro-babel-transformer',\n // and createRequire needs an absolute path, so resolve either shape here\n const configuredBabelTransformerPath =\n metroConfig.transformer.babelTransformerPath ?? 'metro-babel-transformer'\n const originalBabelTransformerPath = isAbsolute(configuredBabelTransformerPath)\n ? configuredBabelTransformerPath\n : requireFromProject.resolve(configuredBabelTransformerPath)\n const cacheBaseRoot = compilerCacheRoot ?? defaultMetroCompilerCacheRoot(projectRoot)\n const frontend = new MetroCompilerFrontend({\n projectRoot,\n resolver: metroConfig.resolver,\n transformer: metroConfig.transformer,\n tamaguiOptions: options,\n originalBabelTransformerPath,\n cacheRoot: cacheBaseRoot,\n zero,\n reportDiagnostic(diagnostic) {\n console.warn(formatMetroCompilerDiagnostic(diagnostic, projectRoot))\n },\n })\n const transformerFactoryPath = requireFromPlugin.resolve(\n '@tamagui/metro-plugin/transformer'\n )\n metroConfig.transformer.babelTransformerPath = writeMetroCompilerTransformerBridge(\n transformerFactoryPath,\n {\n cacheBaseRoot,\n originalBabelTransformerPath,\n projectRoot,\n // an integration-owned literal, never an ambient shell value\n runtimeLiteral: zero?.isEnforcing && !zero.islandBuild ? 'zero' : 'full',\n }\n )\n const userGetTransformOptions = metroConfig.transformer.getTransformOptions\n metroConfig.transformer.getTransformOptions = composeMetroGetTransformOptions(\n frontend,\n userGetTransformOptions\n )\n frontends.set(metroConfig, frontend)\n }\n\n return metroConfig\n}\n\nexport {\n METRO_COMPILER_CACHE_VERSION,\n MetroCompilerCache,\n MetroCompilerCacheError,\n defaultMetroCompilerCacheRoot,\n} from './compilerCache'\nexport type { MetroCompilerDiagnostic } from './diagnostics'\nexport type {\n MetroCompilerGeneration,\n MetroCompilerScanOptions,\n MetroCompilerUpdate,\n} from './frontend'\n"
10
10
  ]
11
11
  }
@@ -11,11 +11,6 @@ export interface MetroCompilerTransformerOptions {
11
11
  * inlined here so every guard is a constant.
12
12
  */
13
13
  runtimeLiteral?: "full" | "zero";
14
- webRuntimeFeatures?: {
15
- inlineThemeValues: "enabled" | "disabled";
16
- styleValueGrammar: "enabled" | "disabled";
17
- safeArea: "enabled" | "disabled";
18
- };
19
14
  }
20
15
  export interface MetroCompilerTransformMetadata {
21
16
  cacheHit: boolean;
@@ -1,11 +1,11 @@
1
1
  {
2
- "mappings": "AAIA,cAGO,8BACA,iCACA;AAMP,cAGO,+BACA;AAEP,cAAsC,mCAAmC;AAEzE,iBAAiB,gCAAgC;CAC/C;CACA;CACA;;;;;;CAMA,iBAAiB,SAAS;CAC1B,qBAAqB;EACnB,mBAAmB,YAAY;EAC/B,mBAAmB,YAAY;EAC/B,UAAU,YAAY;;;AAI1B,iBAAiB,+BAA+B;CAC9C;CACA,aAAa;CACb,WAAW;;AAGb,OAAO,iBAAS,+BAA+B,QAAQ,kCAAkC;CACvF,UAAU,MAAM,0BAA0B,QAAQ;CAClD;;AA4KF,OAAO,iBAAS,oCACd,gCACA,QAAQ",
2
+ "mappings": "AAIA,cAGO,8BACA,iCACA;AAMP,cAGO,+BACA;AAEP,cAAsC,mCAAmC;AAEzE,iBAAiB,gCAAgC;CAC/C;CACA;CACA;;;;;;CAMA,iBAAiB,SAAS;;AAG5B,iBAAiB,+BAA+B;CAC9C;CACA,aAAa;CACb,WAAW;;AAGb,OAAO,iBAAS,+BAA+B,QAAQ,kCAAkC;CACvF,UAAU,MAAM,0BAA0B,QAAQ;CAClD;;AAkJF,OAAO,iBAAS,oCACd,gCACA,QAAQ",
3
3
  "names": [],
4
4
  "sources": [
5
5
  "src/transformer.ts"
6
6
  ],
7
7
  "version": 3,
8
8
  "sourcesContent": [
9
- "import { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync, realpathSync, renameSync, writeFileSync } from 'node:fs'\nimport { isAbsolute, join, resolve } from 'node:path'\n\nimport {\n compileWithUserBabel,\n userBabelCacheKey,\n type MetroBabelTransformArgs,\n type MetroBabelTransformResult,\n} from './babel'\nimport {\n METRO_COMPILER_CACHE_VERSION,\n MetroCompilerCache,\n MetroCompilerCacheError,\n} from './compilerCache'\nimport {\n formatMetroCompilerDiagnostic,\n metroDiagnostic,\n type MetroCompilerDiagnostic,\n} from './diagnostics'\nimport { isCompilerSourceFile } from './metroResolver'\nimport { applyMetroCompilerPlan, type MetroCompilerLoweringResult } from './lowering'\n\nexport interface MetroCompilerTransformerOptions {\n cacheBaseRoot: string\n originalBabelTransformerPath: string\n projectRoot: string\n /**\n * The integration-owned `TAMAGUI_RUNTIME` literal for this bundle request.\n * Metro never reads an ambient value: the literal is decided by the build and\n * inlined here so every guard is a constant.\n */\n runtimeLiteral?: 'full' | 'zero'\n webRuntimeFeatures?: {\n inlineThemeValues: 'enabled' | 'disabled'\n styleValueGrammar: 'enabled' | 'disabled'\n safeArea: 'enabled' | 'disabled'\n }\n}\n\nexport interface MetroCompilerTransformMetadata {\n cacheHit: boolean\n diagnostics: MetroCompilerDiagnostic[]\n lowering?: MetroCompilerLoweringResult\n}\n\nexport function createMetroCompilerTransformer(config: MetroCompilerTransformerOptions): {\n transform(args: MetroBabelTransformArgs): Promise<MetroBabelTransformResult>\n getCacheKey(): string\n} {\n // Metro hands workers project-relative filenames while the compiler cache is\n // keyed by absolute realpaths (the frontend realpaths every module). Resolve\n // to the same form or every plan lookup silently misses and the whole build\n // ships unlowered.\n const moduleIdCache = new Map<string, string>()\n const missWarned = new Set<string>()\n function cacheModuleId(filename: string): string {\n let id = moduleIdCache.get(filename)\n if (!id) {\n const absolute = isAbsolute(filename)\n ? filename\n : resolve(config.projectRoot, filename)\n try {\n id = realpathSync(absolute)\n } catch {\n id = absolute\n }\n moduleIdCache.set(filename, id)\n }\n return id\n }\n // Metro also transforms modules the frontend can never plan: bundler-injected\n // polyfills, virtual modules, and node_modules (external by design). A miss\n // is only a lowering defect for a file the frontend's project graph would\n // have crawled.\n function planEligible(moduleId: string): boolean {\n return (\n isCompilerSourceFile(moduleId) &&\n !moduleId.includes(`${join('node_modules')}`) &&\n existsSync(moduleId)\n )\n }\n // Replaces only the integration-owned exact process.env member expressions.\n // Metro has no define mechanism, so this is the transform-level equivalent.\n const runtimeLiteral = config.runtimeLiteral ?? 'full'\n const inlineRuntimeLiterals = (platform: string, { types }: { types: any }) => {\n const enabledFeatures = {\n inlineThemeValues: 'enabled',\n styleValueGrammar: 'enabled',\n safeArea: 'enabled',\n } as const\n const features =\n platform === 'web'\n ? { ...enabledFeatures, ...config.webRuntimeFeatures }\n : enabledFeatures\n const featureByName: Record<string, string> = {\n TAMAGUI_RUNTIME_INLINE_THEME_VALUES: features.inlineThemeValues,\n TAMAGUI_RUNTIME_STYLE_VALUE_GRAMMAR: features.styleValueGrammar,\n TAMAGUI_RUNTIME_SAFE_AREA: features.safeArea,\n }\n return {\n visitor: {\n MemberExpression(nodePath: any) {\n const node = nodePath.node\n if (\n node.computed ||\n !types.isMemberExpression(node.object) ||\n node.object.computed ||\n !types.isIdentifier(node.object.object, { name: 'process' }) ||\n !types.isIdentifier(node.object.property, { name: 'env' })\n ) {\n return\n }\n const name = types.isIdentifier(node.property) ? node.property.name : ''\n if (name === 'TAMAGUI_RUNTIME') {\n nodePath.replaceWith(types.stringLiteral(runtimeLiteral))\n return\n }\n const literal = featureByName[name]\n if (literal) nodePath.replaceWith(types.stringLiteral(literal))\n },\n },\n }\n }\n\n return {\n async transform(argsIn) {\n const platform =\n typeof argsIn.options.platform === 'string' ? argsIn.options.platform : 'default'\n const args = {\n ...argsIn,\n plugins: [\n ...(argsIn.plugins ?? []),\n (babel: { types: any }) => inlineRuntimeLiterals(platform, babel),\n ],\n }\n const cache = new MetroCompilerCache(join(config.cacheBaseRoot, platform))\n let tamagui: MetroCompilerTransformMetadata = {\n cacheHit: false,\n diagnostics: [],\n }\n const moduleId = cacheModuleId(args.filename)\n try {\n // a manifest exists exactly when the frontend planned this build, so a\n // lookup miss on a plannable file is a lowering defect (unlowered\n // output), never routine — surface it instead of silently shipping\n // runtime-path modules\n const entry = await cache.read(moduleId, args.src, (reason, detail) => {\n if (missWarned.has(moduleId) || !planEligible(moduleId)) return\n missWarned.add(moduleId)\n const diagnostic = metroDiagnostic(\n 'metro/plan-miss',\n `Lowering plan lookup missed for ${moduleId} (${reason}${detail ? `: ${detail}` : ''}); module ships unlowered`,\n { moduleId }\n )\n tamagui.diagnostics.push(diagnostic)\n console.warn(formatMetroCompilerDiagnostic(diagnostic, config.projectRoot))\n })\n if (entry) {\n try {\n const lowered = await applyMetroCompilerPlan(\n { ...args, filename: moduleId },\n entry.plan,\n config.originalBabelTransformerPath\n )\n return {\n ...lowered.compiled.result,\n metadata: {\n ...lowered.compiled.result.metadata,\n tamagui: {\n cacheHit: true,\n diagnostics: entry.diagnostics,\n lowering: lowered.lowering,\n },\n },\n }\n } catch (error) {\n const diagnostic = metroDiagnostic(\n 'metro/cache-corrupt',\n `Cached lowering plan for ${args.filename} could not be applied: ${error instanceof Error ? error.message : String(error)}`,\n { moduleId }\n )\n tamagui = {\n cacheHit: true,\n diagnostics: [...entry.diagnostics, diagnostic],\n }\n console.warn(formatMetroCompilerDiagnostic(diagnostic, config.projectRoot))\n }\n }\n } catch (error) {\n if (!(error instanceof MetroCompilerCacheError)) throw error\n tamagui.diagnostics.push(error.diagnostic)\n console.warn(formatMetroCompilerDiagnostic(error.diagnostic, config.projectRoot))\n }\n const compiled = await compileWithUserBabel(\n config.originalBabelTransformerPath,\n args\n )\n return {\n ...compiled.result,\n metadata: {\n ...compiled.result.metadata,\n tamagui,\n },\n }\n },\n getCacheKey() {\n return createHash('sha256')\n .update(`tamagui-metro-compiler-v${METRO_COMPILER_CACHE_VERSION}`)\n .update('\\0')\n .update(runtimeLiteral)\n .update('\\0')\n .update(JSON.stringify(config.webRuntimeFeatures ?? {}))\n .update('\\0')\n .update(userBabelCacheKey(config.originalBabelTransformerPath))\n .digest('hex')\n },\n }\n}\n\nexport function writeMetroCompilerTransformerBridge(\n transformerFactoryPath: string,\n config: MetroCompilerTransformerOptions\n): string {\n const serializedConfig = JSON.stringify(config)\n const bridgeHash = createHash('sha256')\n .update(transformerFactoryPath)\n .update('\\0')\n .update(serializedConfig)\n .digest('hex')\n const directory = join(config.cacheBaseRoot, 'bridge')\n const bridgePath = join(directory, `${bridgeHash}.cjs`)\n const temporaryPath = `${bridgePath}.${process.pid}.tmp`\n const source = `'use strict'\\nmodule.exports = require(${JSON.stringify(\n transformerFactoryPath\n )}).createMetroCompilerTransformer(${serializedConfig})\\n`\n mkdirSync(directory, { recursive: true })\n writeFileSync(temporaryPath, source, 'utf8')\n renameSync(temporaryPath, bridgePath)\n return bridgePath\n}\n"
9
+ "import { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync, realpathSync, renameSync, writeFileSync } from 'node:fs'\nimport { isAbsolute, join, resolve } from 'node:path'\n\nimport {\n compileWithUserBabel,\n userBabelCacheKey,\n type MetroBabelTransformArgs,\n type MetroBabelTransformResult,\n} from './babel'\nimport {\n METRO_COMPILER_CACHE_VERSION,\n MetroCompilerCache,\n MetroCompilerCacheError,\n} from './compilerCache'\nimport {\n formatMetroCompilerDiagnostic,\n metroDiagnostic,\n type MetroCompilerDiagnostic,\n} from './diagnostics'\nimport { isCompilerSourceFile } from './metroResolver'\nimport { applyMetroCompilerPlan, type MetroCompilerLoweringResult } from './lowering'\n\nexport interface MetroCompilerTransformerOptions {\n cacheBaseRoot: string\n originalBabelTransformerPath: string\n projectRoot: string\n /**\n * The integration-owned `TAMAGUI_RUNTIME` literal for this bundle request.\n * Metro never reads an ambient value: the literal is decided by the build and\n * inlined here so every guard is a constant.\n */\n runtimeLiteral?: 'full' | 'zero'\n}\n\nexport interface MetroCompilerTransformMetadata {\n cacheHit: boolean\n diagnostics: MetroCompilerDiagnostic[]\n lowering?: MetroCompilerLoweringResult\n}\n\nexport function createMetroCompilerTransformer(config: MetroCompilerTransformerOptions): {\n transform(args: MetroBabelTransformArgs): Promise<MetroBabelTransformResult>\n getCacheKey(): string\n} {\n // Metro hands workers project-relative filenames while the compiler cache is\n // keyed by absolute realpaths (the frontend realpaths every module). Resolve\n // to the same form or every plan lookup silently misses and the whole build\n // ships unlowered.\n const moduleIdCache = new Map<string, string>()\n const missWarned = new Set<string>()\n function cacheModuleId(filename: string): string {\n let id = moduleIdCache.get(filename)\n if (!id) {\n const absolute = isAbsolute(filename)\n ? filename\n : resolve(config.projectRoot, filename)\n try {\n id = realpathSync(absolute)\n } catch {\n id = absolute\n }\n moduleIdCache.set(filename, id)\n }\n return id\n }\n // Metro also transforms modules the frontend can never plan: bundler-injected\n // polyfills, virtual modules, and node_modules (external by design). A miss\n // is only a lowering defect for a file the frontend's project graph would\n // have crawled.\n function planEligible(moduleId: string): boolean {\n return (\n isCompilerSourceFile(moduleId) &&\n !moduleId.includes(`${join('node_modules')}`) &&\n existsSync(moduleId)\n )\n }\n // Replaces only the exact member expression `process.env.TAMAGUI_RUNTIME`.\n // Metro has no define mechanism, so this is the transform-level equivalent.\n const runtimeLiteral = config.runtimeLiteral ?? 'full'\n const inlineRuntimeLiteral = ({ types }: { types: any }) => ({\n visitor: {\n MemberExpression(nodePath: any) {\n const node = nodePath.node\n if (\n node.computed ||\n !types.isIdentifier(node.property, { name: 'TAMAGUI_RUNTIME' }) ||\n !types.isMemberExpression(node.object) ||\n node.object.computed ||\n !types.isIdentifier(node.object.object, { name: 'process' }) ||\n !types.isIdentifier(node.object.property, { name: 'env' })\n ) {\n return\n }\n nodePath.replaceWith(types.stringLiteral(runtimeLiteral))\n },\n },\n })\n\n return {\n async transform(argsIn) {\n const args = {\n ...argsIn,\n plugins: [...(argsIn.plugins ?? []), inlineRuntimeLiteral],\n }\n const platform =\n typeof args.options.platform === 'string' ? args.options.platform : 'default'\n const cache = new MetroCompilerCache(join(config.cacheBaseRoot, platform))\n let tamagui: MetroCompilerTransformMetadata = {\n cacheHit: false,\n diagnostics: [],\n }\n const moduleId = cacheModuleId(args.filename)\n try {\n // a manifest exists exactly when the frontend planned this build, so a\n // lookup miss on a plannable file is a lowering defect (unlowered\n // output), never routine — surface it instead of silently shipping\n // runtime-path modules\n const entry = await cache.read(moduleId, args.src, (reason, detail) => {\n if (missWarned.has(moduleId) || !planEligible(moduleId)) return\n missWarned.add(moduleId)\n const diagnostic = metroDiagnostic(\n 'metro/plan-miss',\n `Lowering plan lookup missed for ${moduleId} (${reason}${detail ? `: ${detail}` : ''}); module ships unlowered`,\n { moduleId }\n )\n tamagui.diagnostics.push(diagnostic)\n console.warn(formatMetroCompilerDiagnostic(diagnostic, config.projectRoot))\n })\n if (entry) {\n try {\n const lowered = await applyMetroCompilerPlan(\n { ...args, filename: moduleId },\n entry.plan,\n config.originalBabelTransformerPath\n )\n return {\n ...lowered.compiled.result,\n metadata: {\n ...lowered.compiled.result.metadata,\n tamagui: {\n cacheHit: true,\n diagnostics: entry.diagnostics,\n lowering: lowered.lowering,\n },\n },\n }\n } catch (error) {\n const diagnostic = metroDiagnostic(\n 'metro/cache-corrupt',\n `Cached lowering plan for ${args.filename} could not be applied: ${error instanceof Error ? error.message : String(error)}`,\n { moduleId }\n )\n tamagui = {\n cacheHit: true,\n diagnostics: [...entry.diagnostics, diagnostic],\n }\n console.warn(formatMetroCompilerDiagnostic(diagnostic, config.projectRoot))\n }\n }\n } catch (error) {\n if (!(error instanceof MetroCompilerCacheError)) throw error\n tamagui.diagnostics.push(error.diagnostic)\n console.warn(formatMetroCompilerDiagnostic(error.diagnostic, config.projectRoot))\n }\n const compiled = await compileWithUserBabel(\n config.originalBabelTransformerPath,\n args\n )\n return {\n ...compiled.result,\n metadata: {\n ...compiled.result.metadata,\n tamagui,\n },\n }\n },\n getCacheKey() {\n return createHash('sha256')\n .update(`tamagui-metro-compiler-v${METRO_COMPILER_CACHE_VERSION}`)\n .update('\\0')\n .update(runtimeLiteral)\n .update('\\0')\n .update(userBabelCacheKey(config.originalBabelTransformerPath))\n .digest('hex')\n },\n }\n}\n\nexport function writeMetroCompilerTransformerBridge(\n transformerFactoryPath: string,\n config: MetroCompilerTransformerOptions\n): string {\n const serializedConfig = JSON.stringify(config)\n const bridgeHash = createHash('sha256')\n .update(transformerFactoryPath)\n .update('\\0')\n .update(serializedConfig)\n .digest('hex')\n const directory = join(config.cacheBaseRoot, 'bridge')\n const bridgePath = join(directory, `${bridgeHash}.cjs`)\n const temporaryPath = `${bridgePath}.${process.pid}.tmp`\n const source = `'use strict'\\nmodule.exports = require(${JSON.stringify(\n transformerFactoryPath\n )}).createMetroCompilerTransformer(${serializedConfig})\\n`\n mkdirSync(directory, { recursive: true })\n writeFileSync(temporaryPath, source, 'utf8')\n renameSync(temporaryPath, bridgePath)\n return bridgePath\n}\n"
10
10
  ]
11
11
  }