@tamagui/metro-plugin 2.7.7 → 3.0.0-beta.643.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.
- package/README.md +12 -0
- package/dist/cjs/babel.cjs +77 -0
- package/dist/cjs/compilerCache.cjs +237 -0
- package/dist/cjs/diagnostics.cjs +41 -0
- package/dist/cjs/frontend.cjs +870 -0
- package/dist/cjs/index.cjs +102 -0
- package/dist/cjs/lowering.cjs +109 -0
- package/dist/cjs/metroResolver.cjs +197 -0
- package/dist/cjs/transformOptions.cjs +35 -0
- package/dist/cjs/transformer.cjs +142 -0
- package/dist/cjs/zeroRuntime.cjs +140 -0
- package/dist/cjs/zeroSerializer.cjs +150 -0
- package/dist/esm/babel.mjs +52 -0
- package/dist/esm/babel.mjs.map +1 -0
- package/dist/esm/compilerCache.mjs +212 -0
- package/dist/esm/compilerCache.mjs.map +1 -0
- package/dist/esm/diagnostics.mjs +18 -0
- package/dist/esm/diagnostics.mjs.map +1 -0
- package/dist/esm/frontend.mjs +839 -0
- package/dist/esm/frontend.mjs.map +1 -0
- package/dist/esm/index.mjs +64 -22
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/lowering.mjs +89 -0
- package/dist/esm/lowering.mjs.map +1 -0
- package/dist/esm/metroResolver.mjs +173 -0
- package/dist/esm/metroResolver.mjs.map +1 -0
- package/dist/esm/transformOptions.mjs +14 -0
- package/dist/esm/transformOptions.mjs.map +1 -0
- package/dist/esm/transformer.mjs +119 -0
- package/dist/esm/transformer.mjs.map +1 -0
- package/dist/esm/zeroRuntime.mjs +105 -0
- package/dist/esm/zeroRuntime.mjs.map +1 -0
- package/dist/esm/zeroSerializer.mjs +123 -0
- package/dist/esm/zeroSerializer.mjs.map +1 -0
- package/package.json +33 -5
- package/src/babel.ts +87 -0
- package/src/compilerCache.ts +346 -0
- package/src/diagnostics.ts +47 -0
- package/src/frontend.ts +1178 -0
- package/src/index.ts +117 -14
- package/src/lowering.ts +136 -0
- package/src/metroResolver.ts +209 -0
- package/src/transformOptions.ts +36 -0
- package/src/transformer.ts +210 -0
- package/src/zeroRuntime.ts +212 -0
- package/src/zeroSerializer.ts +175 -0
- package/types/babel.d.ts +28 -0
- package/types/babel.d.ts.map +11 -0
- package/types/compilerCache.d.ts +63 -0
- package/types/compilerCache.d.ts.map +11 -0
- package/types/diagnostics.d.ts +16 -0
- package/types/diagnostics.d.ts.map +11 -0
- package/types/frontend.d.ts +73 -0
- package/types/frontend.d.ts.map +11 -0
- package/types/index.d.ts +49 -32
- package/types/index.d.ts.map +11 -1
- package/types/lowering.d.ts +20 -0
- package/types/lowering.d.ts.map +11 -0
- package/types/metroResolver.d.ts +21 -0
- package/types/metroResolver.d.ts.map +11 -0
- package/types/transformOptions.d.ts +13 -0
- package/types/transformOptions.d.ts.map +11 -0
- package/types/transformer.d.ts +26 -0
- package/types/transformer.d.ts.map +11 -0
- package/types/zeroRuntime.d.ts +75 -0
- package/types/zeroRuntime.d.ts.map +11 -0
- package/types/zeroSerializer.d.ts +6 -0
- package/types/zeroSerializer.d.ts.map +11 -0
- package/dist/cjs/index.js +0 -45
- package/dist/cjs/index.js.map +0 -6
- package/dist/esm/index.js +0 -25
- package/dist/esm/index.js.map +0 -1
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { LoweredModulePlan } from "@tamagui/compiler-core";
|
|
2
|
+
import { type MetroCompilerDiagnostic } from "./diagnostics";
|
|
3
|
+
export declare const METRO_COMPILER_CACHE_VERSION = 6;
|
|
4
|
+
export interface MetroCompilerCacheEntry {
|
|
5
|
+
schemaVersion: typeof METRO_COMPILER_CACHE_VERSION;
|
|
6
|
+
moduleId: string;
|
|
7
|
+
/** Hash of the raw on-disk module source the plan was generated from. */
|
|
8
|
+
sourceHash: string;
|
|
9
|
+
plan: LoweredModulePlan;
|
|
10
|
+
diagnostics: MetroCompilerDiagnostic[];
|
|
11
|
+
}
|
|
12
|
+
export interface MetroCompilerCacheValidation {
|
|
13
|
+
valid: boolean;
|
|
14
|
+
diagnostics: MetroCompilerDiagnostic[];
|
|
15
|
+
generation: string | null;
|
|
16
|
+
moduleIds: string[];
|
|
17
|
+
/** Raw module source hash by module id, for host freshness checks. */
|
|
18
|
+
sourceHashes: Record<string, string>;
|
|
19
|
+
optionsHash: string | null;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The zero build's CSS side effects, persisted beside the plan cache.
|
|
23
|
+
*
|
|
24
|
+
* A published plan generation and its artifact contents are the same fact
|
|
25
|
+
* observed twice: the scan produces both. Persisting only the plans means a
|
|
26
|
+
* warm build reuses them while emitting an artifact missing every rule it never
|
|
27
|
+
* collected, and still derives TAMAGUI_DID_OUTPUT_CSS from it. This is what lets
|
|
28
|
+
* the warm path skip the scan without that divergence.
|
|
29
|
+
*/
|
|
30
|
+
export interface MetroZeroCSSSidecar {
|
|
31
|
+
schemaVersion: typeof METRO_COMPILER_CACHE_VERSION;
|
|
32
|
+
generation: string;
|
|
33
|
+
configCSS: string;
|
|
34
|
+
/** Per-module compiler atomic CSS, by resolved module id. */
|
|
35
|
+
zeroModuleCSS: Record<string, string>;
|
|
36
|
+
/** Theme-bridge class rules, by bridge id. */
|
|
37
|
+
bridgeCSS: Record<string, string>;
|
|
38
|
+
/** The bridge manifest, by island id. */
|
|
39
|
+
bridges: Record<string, unknown[]>;
|
|
40
|
+
}
|
|
41
|
+
export declare class MetroCompilerCacheError extends Error {
|
|
42
|
+
readonly diagnostic: MetroCompilerDiagnostic;
|
|
43
|
+
constructor(diagnostic: MetroCompilerDiagnostic);
|
|
44
|
+
}
|
|
45
|
+
export declare function defaultMetroCompilerCacheRoot(projectRoot: string): string;
|
|
46
|
+
/**
|
|
47
|
+
* Filesystem handoff shared by the Metro main process and isolated transform workers.
|
|
48
|
+
* Immutable blobs are content addressed; a single manifest rename publishes a generation.
|
|
49
|
+
*/
|
|
50
|
+
export declare class MetroCompilerCache {
|
|
51
|
+
#private;
|
|
52
|
+
readonly root: string;
|
|
53
|
+
constructor(root: string);
|
|
54
|
+
publish(platform: string | null, entries: readonly MetroCompilerCacheEntry[], optionsHash: string): Promise<string>;
|
|
55
|
+
read(moduleId: string, rawSource: string, onMiss?: (reason: "no-entry" | "source-hash-mismatch", detail?: string) => void): Promise<MetroCompilerCacheEntry | null>;
|
|
56
|
+
validate(): Promise<MetroCompilerCacheValidation>;
|
|
57
|
+
discardManifest(): Promise<void>;
|
|
58
|
+
publishZeroCSS(sidecar: MetroZeroCSSSidecar): Promise<void>;
|
|
59
|
+
/** Null whenever the sidecar is absent or does not describe this generation. */
|
|
60
|
+
readZeroCSS(generation: string): Promise<MetroZeroCSSSidecar | null>;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
//# sourceMappingURL=compilerCache.d.ts.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"mappings": "AAUA,cAAc,yBAAyB;AAEvC,cAA+B,+BAA+B;AAE9D,OAAO,cAAM,+BAA+B;AAE5C,iBAAiB,wBAAwB;CACvC,sBAAsB;CACtB;;CAEA;CACA,MAAM;CACN,aAAa;;AAgBf,iBAAiB,6BAA6B;CAC5C;CACA,aAAa;CACb;CACA;;CAEA,cAAc;CACd;;;;;;;;;;;AAYF,iBAAiB,oBAAoB;CACnC,sBAAsB;CACtB;CACA;;CAEA,eAAe;;CAEf,WAAW;;CAEX,SAAS;;AAGX,OAAO,cAAM,gCAAgC,MAAM;CACrC,qBAAqB;CAAjC,YAAY,AAAS,YAAY;;AA+BnC,OAAO,iBAAS,8BAA8B;;;;;AAQ9C,OAAO,cAAM,mBAAmB;;CAIlB;CAAZ,YAAY,AAAS;CAKrB,AAAM,QACJ,yBACA,kBAAkB,2BAClB,sBACC;CAgDH,AAAM,KACJ,kBACA,mBACA,UAAU,QAAQ,aAAa,wBAAwB,2BACtD,QAAQ;CAmBX,AAAM,YAAY,QAAQ;CA2C1B,AAAM,mBAAmB;CAYzB,AAAM,eAAe,SAAS,sBAAsB;;CASpD,AAAM,YAAY,qBAAqB,QAAQ",
|
|
3
|
+
"names": [],
|
|
4
|
+
"sources": [
|
|
5
|
+
"src/compilerCache.ts"
|
|
6
|
+
],
|
|
7
|
+
"version": 3,
|
|
8
|
+
"sourcesContent": [
|
|
9
|
+
"import { randomBytes } from 'node:crypto'\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nimport {\n LOWERED_MODULE_PLAN_VERSION,\n contentHash,\n stableStringify,\n tamaguiCacheRoot,\n} from '@tamagui/compiler-core'\nimport type { LoweredModulePlan } from '@tamagui/compiler-core'\n\nimport { metroDiagnostic, type MetroCompilerDiagnostic } from './diagnostics'\n\nexport const METRO_COMPILER_CACHE_VERSION = 6\n\nexport interface MetroCompilerCacheEntry {\n schemaVersion: typeof METRO_COMPILER_CACHE_VERSION\n moduleId: string\n /** Hash of the raw on-disk module source the plan was generated from. */\n sourceHash: string\n plan: LoweredModulePlan\n diagnostics: MetroCompilerDiagnostic[]\n}\n\ninterface MetroCompilerCacheDescriptor {\n blobHash: string\n sourceHash: string\n}\n\ninterface MetroCompilerCacheManifest {\n schemaVersion: typeof METRO_COMPILER_CACHE_VERSION\n generation: string\n optionsHash: string\n platform: string | null\n entries: Record<string, MetroCompilerCacheDescriptor>\n}\n\nexport interface MetroCompilerCacheValidation {\n valid: boolean\n diagnostics: MetroCompilerDiagnostic[]\n generation: string | null\n moduleIds: string[]\n /** Raw module source hash by module id, for host freshness checks. */\n sourceHashes: Record<string, string>\n optionsHash: string | null\n}\n\n/**\n * The zero build's CSS side effects, persisted beside the plan cache.\n *\n * A published plan generation and its artifact contents are the same fact\n * observed twice: the scan produces both. Persisting only the plans means a\n * warm build reuses them while emitting an artifact missing every rule it never\n * collected, and still derives TAMAGUI_DID_OUTPUT_CSS from it. This is what lets\n * the warm path skip the scan without that divergence.\n */\nexport interface MetroZeroCSSSidecar {\n schemaVersion: typeof METRO_COMPILER_CACHE_VERSION\n generation: string\n configCSS: string\n /** Per-module compiler atomic CSS, by resolved module id. */\n zeroModuleCSS: Record<string, string>\n /** Theme-bridge class rules, by bridge id. */\n bridgeCSS: Record<string, string>\n /** The bridge manifest, by island id. */\n bridges: Record<string, unknown[]>\n}\n\nexport class MetroCompilerCacheError extends Error {\n constructor(readonly diagnostic: MetroCompilerDiagnostic) {\n super(diagnostic.message)\n this.name = 'MetroCompilerCacheError'\n }\n}\n\nfunction compareCodeUnits(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction stableEntries<T>(record: Record<string, T>): [string, T][] {\n return Object.entries(record).sort(([left], [right]) => compareCodeUnits(left, right))\n}\n\nfunction cacheCorrupt(message: string, moduleId?: string): MetroCompilerCacheError {\n return new MetroCompilerCacheError(\n metroDiagnostic('metro/cache-corrupt', message, { moduleId })\n )\n}\n\nfunction parseJson<T>(source: string, description: string, moduleId?: string): T {\n try {\n return JSON.parse(source) as T\n } catch (error) {\n throw cacheCorrupt(\n `${description} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`,\n moduleId\n )\n }\n}\n\nexport function defaultMetroCompilerCacheRoot(projectRoot: string): string {\n return join(tamaguiCacheRoot(projectRoot), 'metro-compiler')\n}\n\n/**\n * Filesystem handoff shared by the Metro main process and isolated transform workers.\n * Immutable blobs are content addressed; a single manifest rename publishes a generation.\n */\nexport class MetroCompilerCache {\n readonly #blobsDirectory: string\n readonly #manifestPath: string\n\n constructor(readonly root: string) {\n this.#blobsDirectory = join(root, `v${METRO_COMPILER_CACHE_VERSION}`, 'blobs')\n this.#manifestPath = join(root, `v${METRO_COMPILER_CACHE_VERSION}`, 'manifest.json')\n }\n\n async publish(\n platform: string | null,\n entries: readonly MetroCompilerCacheEntry[],\n optionsHash: string\n ): Promise<string> {\n await mkdir(this.#blobsDirectory, { recursive: true })\n const descriptors: Record<string, MetroCompilerCacheDescriptor> = {}\n\n for (const entry of [...entries].sort((left, right) =>\n compareCodeUnits(left.moduleId, right.moduleId)\n )) {\n if (entry.schemaVersion !== METRO_COMPILER_CACHE_VERSION) {\n throw new Error(`Cannot publish cache schema ${entry.schemaVersion}`)\n }\n const serialized = `${stableStringify(entry)}\\n`\n const blobHash = contentHash(serialized)\n const blobPath = join(this.#blobsDirectory, `${blobHash}.json`)\n try {\n await writeFile(blobPath, serialized, { encoding: 'utf8', flag: 'wx' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n const existing = await readFile(blobPath, 'utf8')\n if (contentHash(existing) !== blobHash) {\n const temporaryBlobPath = `${blobPath}.${process.pid}-${randomBytes(6).toString('hex')}.tmp`\n await writeFile(temporaryBlobPath, serialized, 'utf8')\n await rename(temporaryBlobPath, blobPath)\n }\n }\n descriptors[entry.moduleId] = {\n blobHash,\n sourceHash: entry.sourceHash,\n }\n }\n\n const generation = contentHash(stableStringify(descriptors))\n const manifest: MetroCompilerCacheManifest = {\n schemaVersion: METRO_COMPILER_CACHE_VERSION,\n generation,\n optionsHash,\n platform,\n entries: descriptors,\n }\n const manifestDirectory = join(this.root, `v${METRO_COMPILER_CACHE_VERSION}`)\n const temporaryPath = join(\n manifestDirectory,\n `.manifest-${process.pid}-${randomBytes(6).toString('hex')}.json`\n )\n await writeFile(temporaryPath, `${stableStringify(manifest)}\\n`, 'utf8')\n await rename(temporaryPath, this.#manifestPath)\n return generation\n }\n\n async read(\n moduleId: string,\n rawSource: string,\n onMiss?: (reason: 'no-entry' | 'source-hash-mismatch', detail?: string) => void\n ): Promise<MetroCompilerCacheEntry | null> {\n const manifest = await this.#readManifest()\n if (!manifest) return null\n const descriptor = manifest.entries[moduleId]\n if (!descriptor) {\n onMiss?.('no-entry')\n return null\n }\n const sourceHash = contentHash(rawSource)\n if (sourceHash !== descriptor.sourceHash) {\n onMiss?.(\n 'source-hash-mismatch',\n `worker ${sourceHash.slice(0, 12)} vs plan ${descriptor.sourceHash.slice(0, 12)}`\n )\n return null\n }\n return await this.#readBlob(moduleId, descriptor)\n }\n\n async validate(): Promise<MetroCompilerCacheValidation> {\n const diagnostics: MetroCompilerDiagnostic[] = []\n try {\n const manifest = await this.#readManifest()\n if (!manifest) {\n return {\n valid: false,\n diagnostics,\n generation: null,\n moduleIds: [],\n sourceHashes: {},\n optionsHash: null,\n }\n }\n const sourceHashes: Record<string, string> = {}\n for (const [moduleId, descriptor] of stableEntries(manifest.entries)) {\n await this.#readBlob(moduleId, descriptor)\n sourceHashes[moduleId] = descriptor.sourceHash\n }\n return {\n valid: true,\n diagnostics,\n generation: manifest.generation,\n moduleIds: Object.keys(manifest.entries).sort(compareCodeUnits),\n sourceHashes,\n optionsHash: manifest.optionsHash,\n }\n } catch (error) {\n if (error instanceof MetroCompilerCacheError) {\n diagnostics.push(error.diagnostic)\n return {\n valid: false,\n diagnostics,\n generation: null,\n moduleIds: [],\n sourceHashes: {},\n optionsHash: null,\n }\n }\n throw error\n }\n }\n\n async discardManifest(): Promise<void> {\n await rm(this.#manifestPath, { force: true })\n }\n\n #zeroSidecarPath(generation: string): string {\n return join(\n this.root,\n `v${METRO_COMPILER_CACHE_VERSION}`,\n `zero-${generation.slice(0, 32)}.json`\n )\n }\n\n async publishZeroCSS(sidecar: MetroZeroCSSSidecar): Promise<void> {\n await mkdir(join(this.root, `v${METRO_COMPILER_CACHE_VERSION}`), { recursive: true })\n const file = this.#zeroSidecarPath(sidecar.generation)\n const temporaryPath = `${file}.${process.pid}-${randomBytes(6).toString('hex')}.tmp`\n await writeFile(temporaryPath, `${stableStringify(sidecar)}\\n`, 'utf8')\n await rename(temporaryPath, file)\n }\n\n /** Null whenever the sidecar is absent or does not describe this generation. */\n async readZeroCSS(generation: string): Promise<MetroZeroCSSSidecar | null> {\n let source: string\n try {\n source = await readFile(this.#zeroSidecarPath(generation), 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw error\n }\n const sidecar = parseJson<MetroZeroCSSSidecar>(source, 'Zero CSS sidecar')\n if (\n sidecar.schemaVersion !== METRO_COMPILER_CACHE_VERSION ||\n sidecar.generation !== generation ||\n typeof sidecar.configCSS !== 'string' ||\n !sidecar.zeroModuleCSS ||\n typeof sidecar.zeroModuleCSS !== 'object' ||\n !sidecar.bridgeCSS ||\n typeof sidecar.bridgeCSS !== 'object' ||\n !sidecar.bridges ||\n typeof sidecar.bridges !== 'object'\n ) {\n return null\n }\n return sidecar\n }\n\n async #readManifest(): Promise<MetroCompilerCacheManifest | null> {\n let source: string\n try {\n source = await readFile(this.#manifestPath, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw error\n }\n const manifest = parseJson<MetroCompilerCacheManifest>(source, 'Cache manifest')\n if (\n manifest.schemaVersion !== METRO_COMPILER_CACHE_VERSION ||\n typeof manifest.generation !== 'string' ||\n typeof manifest.optionsHash !== 'string' ||\n !manifest.entries ||\n typeof manifest.entries !== 'object'\n ) {\n throw cacheCorrupt('Cache manifest has an unsupported schema')\n }\n return manifest\n }\n\n async #readBlob(\n moduleId: string,\n descriptor: MetroCompilerCacheDescriptor\n ): Promise<MetroCompilerCacheEntry> {\n const blobPath = join(this.#blobsDirectory, `${descriptor.blobHash}.json`)\n let source: string\n try {\n source = await readFile(blobPath, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw cacheCorrupt(`Cache blob ${descriptor.blobHash} is missing`, moduleId)\n }\n throw error\n }\n if (contentHash(source) !== descriptor.blobHash) {\n throw cacheCorrupt(`Cache blob ${descriptor.blobHash} failed its hash`, moduleId)\n }\n const entry = parseJson<MetroCompilerCacheEntry>(\n source,\n `Cache blob ${descriptor.blobHash}`,\n moduleId\n )\n if (\n entry.schemaVersion !== METRO_COMPILER_CACHE_VERSION ||\n entry.moduleId !== moduleId ||\n typeof entry.sourceHash !== 'string' ||\n entry.sourceHash !== descriptor.sourceHash ||\n !entry.plan ||\n entry.plan.version !== LOWERED_MODULE_PLAN_VERSION ||\n entry.plan.id !== moduleId ||\n entry.plan.sourceHash !== entry.sourceHash ||\n !Array.isArray(entry.plan.edits) ||\n !Array.isArray(entry.plan.diagnostics) ||\n !Array.isArray(entry.diagnostics)\n ) {\n throw cacheCorrupt(\n `Cache blob ${descriptor.blobHash} has invalid contents`,\n moduleId\n )\n }\n return entry\n }\n}\n"
|
|
10
|
+
]
|
|
11
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { SourceSpan } from "@tamagui/compiler-core";
|
|
2
|
+
export type MetroCompilerDiagnosticCode = "metro/cache-corrupt" | "metro/cache-stale" | "metro/no-linked-components" | "metro/plan-miss" | "metro/resolve-failed" | "metro/transform-failed";
|
|
3
|
+
export interface MetroCompilerDiagnostic {
|
|
4
|
+
code: MetroCompilerDiagnosticCode;
|
|
5
|
+
message: string;
|
|
6
|
+
moduleId?: string;
|
|
7
|
+
dependency?: string;
|
|
8
|
+
span?: SourceSpan;
|
|
9
|
+
line?: number;
|
|
10
|
+
column?: number;
|
|
11
|
+
component?: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function metroDiagnostic(code: MetroCompilerDiagnosticCode, message: string, details?: Omit<MetroCompilerDiagnostic, "code" | "message">): MetroCompilerDiagnostic;
|
|
14
|
+
export declare function formatMetroCompilerDiagnostic(diagnostic: MetroCompilerDiagnostic, projectRoot: string): string;
|
|
15
|
+
|
|
16
|
+
//# sourceMappingURL=diagnostics.d.ts.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"mappings": "AAEA,cAAc,kBAAkB;AAEhC,YAAY,8BACR,wBACA,sBACA,+BACA,oBACA,yBACA;AAEJ,iBAAiB,wBAAwB;CACvC,MAAM;CACN;CACA;CACA;CACA,OAAO;CACP;CACA;CACA;;AAGF,OAAO,iBAAS,gBACd,MAAM,6BACN,iBACA,UAAS,KAAK,yBAAyB,SAAS,aAC/C;AAIH,OAAO,iBAAS,8BACd,YAAY,yBACZ",
|
|
3
|
+
"names": [],
|
|
4
|
+
"sources": [
|
|
5
|
+
"src/diagnostics.ts"
|
|
6
|
+
],
|
|
7
|
+
"version": 3,
|
|
8
|
+
"sourcesContent": [
|
|
9
|
+
"import { isAbsolute, relative } from 'node:path'\n\nimport type { SourceSpan } from '@tamagui/compiler-core'\n\nexport type MetroCompilerDiagnosticCode =\n | 'metro/cache-corrupt'\n | 'metro/cache-stale'\n | 'metro/no-linked-components'\n | 'metro/plan-miss'\n | 'metro/resolve-failed'\n | 'metro/transform-failed'\n\nexport interface MetroCompilerDiagnostic {\n code: MetroCompilerDiagnosticCode\n message: string\n moduleId?: string\n dependency?: string\n span?: SourceSpan\n line?: number\n column?: number\n component?: string\n}\n\nexport function metroDiagnostic(\n code: MetroCompilerDiagnosticCode,\n message: string,\n details: Omit<MetroCompilerDiagnostic, 'code' | 'message'> = {}\n): MetroCompilerDiagnostic {\n return { code, message, ...details }\n}\n\nexport function formatMetroCompilerDiagnostic(\n diagnostic: MetroCompilerDiagnostic,\n projectRoot: string\n): string {\n const sourceId = diagnostic.span?.id ?? diagnostic.moduleId\n const file = sourceId\n ? isAbsolute(sourceId)\n ? relative(projectRoot, sourceId) || '.'\n : sourceId\n : null\n const location =\n file && diagnostic.line != null && diagnostic.column != null\n ? `${file}:${diagnostic.line}:${diagnostic.column}: `\n : ''\n return `[@tamagui/metro-plugin] ${location}${diagnostic.code}: ${diagnostic.message}`\n}\n"
|
|
10
|
+
]
|
|
11
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { type CompilerTarget } from "@tamagui/compiler-core";
|
|
2
|
+
import Static from "@tamagui/static";
|
|
3
|
+
import type { TamaguiOptions } from "@tamagui/static";
|
|
4
|
+
import { type MetroZeroController } from "./zeroRuntime";
|
|
5
|
+
import { type MetroCompilerDiagnostic } from "./diagnostics";
|
|
6
|
+
import { type MetroResolverConfig } from "./metroResolver";
|
|
7
|
+
/**
|
|
8
|
+
* Metro runs the user's whole Babel transformer over every project source just
|
|
9
|
+
* to read its import specifiers, which is the single most expensive step of the
|
|
10
|
+
* prepass. The result is a pure function of the module's own bytes plus the
|
|
11
|
+
* resolver and Babel identity, so it caches per file with no closure involved.
|
|
12
|
+
*/
|
|
13
|
+
export declare const METRO_RECORD_CACHE_VERSION = 1;
|
|
14
|
+
export interface MetroCompilerFrontendConfig extends MetroResolverConfig {
|
|
15
|
+
cacheRoot?: string;
|
|
16
|
+
/** Present only for an enforced zero-runtime web build. */
|
|
17
|
+
zero?: MetroZeroController | null;
|
|
18
|
+
originalBabelTransformerPath: string;
|
|
19
|
+
transformer?: Record<string, any>;
|
|
20
|
+
tamaguiOptions?: Partial<TamaguiOptions>;
|
|
21
|
+
loadCompilerProject?: (target: CompilerTarget, platform: string | null) => Promise<MetroCompilerProject>;
|
|
22
|
+
watch?: boolean;
|
|
23
|
+
reportDiagnostic?: (diagnostic: MetroCompilerDiagnostic) => void;
|
|
24
|
+
}
|
|
25
|
+
export interface MetroCompilerProject extends Static.CompilerProject {}
|
|
26
|
+
export interface MetroCompilerScanOptions {
|
|
27
|
+
dev: boolean;
|
|
28
|
+
entryFiles: readonly string[];
|
|
29
|
+
hot: boolean;
|
|
30
|
+
platform: string | null;
|
|
31
|
+
transform?: Record<string, any>;
|
|
32
|
+
}
|
|
33
|
+
export interface MetroCompilerGeneration {
|
|
34
|
+
generation: string;
|
|
35
|
+
moduleIds: string[];
|
|
36
|
+
diagnostics: MetroCompilerDiagnostic[];
|
|
37
|
+
}
|
|
38
|
+
export interface MetroCompilerUpdate {
|
|
39
|
+
changed: boolean;
|
|
40
|
+
affectedIds: string[];
|
|
41
|
+
generation: string | null;
|
|
42
|
+
}
|
|
43
|
+
export declare class MetroCompilerFrontend {
|
|
44
|
+
#private;
|
|
45
|
+
readonly config: MetroCompilerFrontendConfig;
|
|
46
|
+
constructor(config: MetroCompilerFrontendConfig);
|
|
47
|
+
get metroResolverVersion(): string;
|
|
48
|
+
/**
|
|
49
|
+
* Per-file cache accounting for the last scan. The point of these caches is
|
|
50
|
+
* that one edited module leaves every other module's entry valid, and this is
|
|
51
|
+
* how that is observed rather than assumed.
|
|
52
|
+
*/
|
|
53
|
+
get compileCacheStats(): {
|
|
54
|
+
plans: {
|
|
55
|
+
hits: number;
|
|
56
|
+
misses: number;
|
|
57
|
+
writes: number;
|
|
58
|
+
};
|
|
59
|
+
records: {
|
|
60
|
+
hits: number;
|
|
61
|
+
misses: number;
|
|
62
|
+
writes: number;
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
cacheRootFor(platform: string | null): string;
|
|
66
|
+
scan(options: MetroCompilerScanOptions): Promise<MetroCompilerGeneration>;
|
|
67
|
+
ensureValidCache(options: MetroCompilerScanOptions): Promise<MetroCompilerGeneration>;
|
|
68
|
+
updateFile(path: string): Promise<MetroCompilerUpdate>;
|
|
69
|
+
close(): Promise<void>;
|
|
70
|
+
}
|
|
71
|
+
export declare function describeMetroCompilerRoot(projectRoot: string, moduleId: string): string;
|
|
72
|
+
|
|
73
|
+
//# sourceMappingURL=frontend.d.ts.map
|
|
@@ -0,0 +1,11 @@
|
|
|
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",
|
|
3
|
+
"names": [],
|
|
4
|
+
"sources": [
|
|
5
|
+
"src/frontend.ts"
|
|
6
|
+
],
|
|
7
|
+
"version": 3,
|
|
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"
|
|
10
|
+
]
|
|
11
|
+
}
|
package/types/index.d.ts
CHANGED
|
@@ -1,39 +1,56 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { TamaguiOptions } from "@tamagui/static";
|
|
2
|
+
import { MetroCompilerFrontend } from "./frontend";
|
|
2
3
|
export type MetroTamaguiOptions = TamaguiOptions & {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
/** Override the ignored on-disk handoff used by Metro transform workers. */
|
|
5
|
+
compilerCacheRoot?: string;
|
|
6
|
+
/**
|
|
7
|
+
* Set by the zero-runtime island bundle request. An island is a second Metro
|
|
8
|
+
* bundle with `TAMAGUI_RUNTIME='full'` and its own entry, so this invocation
|
|
9
|
+
* keeps the full runtime and only contributes its CSS fragment.
|
|
10
|
+
*/
|
|
11
|
+
zeroIslandBuild?: string;
|
|
12
|
+
/**
|
|
13
|
+
* Directory the zero CSS artifact and island bundles are published from,
|
|
14
|
+
* relative to the project root.
|
|
15
|
+
*
|
|
16
|
+
* @default 'public'
|
|
17
|
+
*/
|
|
18
|
+
zeroPublicDir?: string;
|
|
7
19
|
};
|
|
8
20
|
type MetroConfigInput = {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
21
|
+
projectRoot?: string;
|
|
22
|
+
resolver?: any;
|
|
23
|
+
transformer?: any;
|
|
24
|
+
transformerPath?: string;
|
|
25
|
+
[key: string]: any;
|
|
13
26
|
};
|
|
27
|
+
export declare function getMetroCompilerFrontend(metroConfig: MetroConfigInput): MetroCompilerFrontend | null;
|
|
14
28
|
/**
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
29
|
+
* Configure Metro for Tamagui.
|
|
30
|
+
*
|
|
31
|
+
* This is now a simplified wrapper that just ensures CSS is enabled and
|
|
32
|
+
* loads your Tamagui config. For CSS generation, use the CLI:
|
|
33
|
+
*
|
|
34
|
+
* 1. Create a `tamagui.build.ts` with `outputCSS` option
|
|
35
|
+
* 2. Run `tamagui generate` before your build
|
|
36
|
+
* 3. Import the generated CSS in your app's layout
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```js
|
|
40
|
+
* // metro.config.js
|
|
41
|
+
* const { getDefaultConfig } = require('expo/metro-config')
|
|
42
|
+
* const { withTamagui } = require('@tamagui/metro-plugin')
|
|
43
|
+
*
|
|
44
|
+
* const config = getDefaultConfig(__dirname, { isCSSEnabled: true })
|
|
45
|
+
* module.exports = withTamagui(config, {
|
|
46
|
+
* components: ['tamagui'],
|
|
47
|
+
* config: './tamagui.config.ts',
|
|
48
|
+
* })
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
37
51
|
export declare function withTamagui(metroConfig: MetroConfigInput, optionsIn?: MetroTamaguiOptions): MetroConfigInput;
|
|
38
|
-
export {};
|
|
52
|
+
export { METRO_COMPILER_CACHE_VERSION, MetroCompilerCache, MetroCompilerCacheError, defaultMetroCompilerCacheRoot } from "./compilerCache";
|
|
53
|
+
export type { MetroCompilerDiagnostic } from "./diagnostics";
|
|
54
|
+
export type { MetroCompilerGeneration, MetroCompilerScanOptions, MetroCompilerUpdate } from "./frontend";
|
|
55
|
+
|
|
39
56
|
//# sourceMappingURL=index.d.ts.map
|
package/types/index.d.ts.map
CHANGED
|
@@ -1 +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;AAmFH,SACE,8BACA,oBACA,yBACA,qCACK;AACP,cAAc,+BAA+B;AAC7C,cACE,yBACA,0BACA,2BACK",
|
|
3
|
+
"names": [],
|
|
4
|
+
"sources": [
|
|
5
|
+
"src/index.ts"
|
|
6
|
+
],
|
|
7
|
+
"version": 3,
|
|
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\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
|
+
]
|
|
11
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type LoweredModulePlan, type LoweredModuleStats } from "@tamagui/compiler-core";
|
|
2
|
+
import { type CompiledMetroModule, type MetroBabelTransformArgs } from "./babel";
|
|
3
|
+
export interface MetroCompilerLoweringResult {
|
|
4
|
+
applied: boolean;
|
|
5
|
+
diagnostics: LoweredModulePlan["diagnostics"];
|
|
6
|
+
sourceMapComposed: boolean;
|
|
7
|
+
stats: LoweredModuleStats;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Applies the cacheable E3 plan to the raw module source, then runs the user's
|
|
11
|
+
* Babel transformer once over the lowered source. Plans carry spans into raw
|
|
12
|
+
* source, so this process's Babel output never needs to match the planning
|
|
13
|
+
* process's byte for byte — Babel options can differ freely between them.
|
|
14
|
+
*/
|
|
15
|
+
export declare function applyMetroCompilerPlan(args: MetroBabelTransformArgs, plan: LoweredModulePlan, transformerPath: string): Promise<{
|
|
16
|
+
compiled: CompiledMetroModule;
|
|
17
|
+
lowering: MetroCompilerLoweringResult;
|
|
18
|
+
}>;
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=lowering.d.ts.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"mappings": "AAAA,cAGO,wBACA,0BACA;AAOP,cAEO,0BACA,+BACA;AAEP,iBAAiB,4BAA4B;CAC3C;CACA,aAAa,kBAAkB;CAC/B;CACA,OAAO;;;;;;;;AA4ET,OAAO,iBAAe,uBACpB,MAAM,yBACN,MAAM,mBACN,0BACC,QAAQ;CAAE,UAAU;CAAqB,UAAU",
|
|
3
|
+
"names": [],
|
|
4
|
+
"sources": [
|
|
5
|
+
"src/lowering.ts"
|
|
6
|
+
],
|
|
7
|
+
"version": 3,
|
|
8
|
+
"sourcesContent": [
|
|
9
|
+
"import {\n applyLoweredModule,\n resolvedModuleId,\n type LoweredModulePlan,\n type LoweredModuleStats,\n} from '@tamagui/compiler-core'\nimport {\n GREATEST_LOWER_BOUND,\n TraceMap,\n originalPositionFor,\n} from '@jridgewell/trace-mapping'\n\nimport {\n compileWithUserBabel,\n type CompiledMetroModule,\n type MetroBabelTransformArgs,\n} from './babel'\n\nexport interface MetroCompilerLoweringResult {\n applied: boolean\n diagnostics: LoweredModulePlan['diagnostics']\n sourceMapComposed: boolean\n stats: LoweredModuleStats\n}\n\ninterface Position {\n line: number\n column: number\n}\n\nfunction lineStarts(source: string): number[] {\n const starts = [0]\n for (let index = 0; index < source.length; index++) {\n if (source.charCodeAt(index) === 10) starts.push(index + 1)\n }\n return starts\n}\n\nfunction sourceIndex(starts: readonly number[], position: Position): number {\n return (starts[position.line - 1] ?? starts.at(-1) ?? 0) + position.column\n}\n\nfunction tracePosition(loweredMap: TraceMap, position: Position): Position | null {\n const original = originalPositionFor(loweredMap, {\n line: position.line,\n column: position.column,\n bias: GREATEST_LOWER_BOUND,\n })\n return original.line == null || original.column == null\n ? null\n : { line: original.line, column: original.column }\n}\n\nfunction remapAstLocations(\n ast: Record<string, any>,\n loweredMap: TraceMap,\n source: string,\n filename: string\n): void {\n const starts = lineStarts(source)\n const seen = new Set<object>()\n const visit = (value: unknown) => {\n if (!value || typeof value !== 'object' || seen.has(value as object)) return\n seen.add(value as object)\n if (Array.isArray(value)) {\n for (const child of value) visit(child)\n return\n }\n const node = value as Record<string, any>\n const loc = node.loc\n if (loc?.start && loc?.end) {\n const start = tracePosition(loweredMap, loc.start)\n const end = tracePosition(loweredMap, loc.end)\n if (start && end) {\n node.start = sourceIndex(starts, start)\n node.end = sourceIndex(starts, end)\n node.loc = {\n ...loc,\n start,\n end,\n filename,\n }\n }\n }\n for (const [key, child] of Object.entries(node)) {\n if (key === 'loc' || key === 'tokens') continue\n visit(child)\n }\n }\n visit(ast)\n}\n\n/**\n * Applies the cacheable E3 plan to the raw module source, then runs the user's\n * Babel transformer once over the lowered source. Plans carry spans into raw\n * source, so this process's Babel output never needs to match the planning\n * process's byte for byte — Babel options can differ freely between them.\n */\nexport async function applyMetroCompilerPlan(\n args: MetroBabelTransformArgs,\n plan: LoweredModulePlan,\n transformerPath: string\n): Promise<{ compiled: CompiledMetroModule; lowering: MetroCompilerLoweringResult }> {\n const output = applyLoweredModule(args.src, resolvedModuleId(args.filename), plan)\n if (!output.changed || !output.map) {\n return {\n compiled: await compileWithUserBabel(transformerPath, args),\n lowering: {\n applied: false,\n diagnostics: plan.diagnostics,\n sourceMapComposed: false,\n stats: plan.stats,\n },\n }\n }\n\n const compiled = await compileWithUserBabel(transformerPath, {\n ...args,\n src: output.code,\n })\n remapAstLocations(\n compiled.result.ast,\n new TraceMap(output.map as any),\n args.src,\n args.filename\n )\n return {\n compiled,\n lowering: {\n applied: true,\n diagnostics: plan.diagnostics,\n sourceMapComposed: true,\n stats: plan.stats,\n },\n }\n}\n"
|
|
10
|
+
]
|
|
11
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export interface MetroResolverConfig {
|
|
2
|
+
projectRoot: string;
|
|
3
|
+
resolver?: Record<string, any>;
|
|
4
|
+
}
|
|
5
|
+
export interface MetroResolvedDependency {
|
|
6
|
+
specifier: string;
|
|
7
|
+
resolvedId: string;
|
|
8
|
+
external: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface MetroModuleSpecifier {
|
|
11
|
+
specifier: string;
|
|
12
|
+
isESMImport: boolean;
|
|
13
|
+
}
|
|
14
|
+
export declare function moduleSpecifiersFromAst(ast: unknown): MetroModuleSpecifier[];
|
|
15
|
+
export declare function createMetroCompilerResolver(config: MetroResolverConfig): {
|
|
16
|
+
version: string;
|
|
17
|
+
resolve(importer: string, dependency: MetroModuleSpecifier, platform: string | null): MetroResolvedDependency | null;
|
|
18
|
+
};
|
|
19
|
+
export declare function isCompilerSourceFile(path: string): boolean;
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=metroResolver.d.ts.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"mappings": "AAIA,iBAAiB,oBAAoB;CACnC;CACA,WAAW;;AAGb,iBAAiB,wBAAwB;CACvC;CACA;CACA;;AAGF,iBAAiB,qBAAqB;CACpC;CACA;;AAuDF,OAAO,iBAAS,wBAAwB,eAAe;AA4CvD,OAAO,iBAAS,4BAA4B,QAAQ,sBAAsB;CACxE;CACA,QACE,kBACA,YAAY,sBACZ,0BACC;;AAoFL,OAAO,iBAAS,qBAAqB",
|
|
3
|
+
"names": [],
|
|
4
|
+
"sources": [
|
|
5
|
+
"src/metroResolver.ts"
|
|
6
|
+
],
|
|
7
|
+
"version": 3,
|
|
8
|
+
"sourcesContent": [
|
|
9
|
+
"import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { dirname, extname, isAbsolute, join, parse, relative, resolve } from 'node:path'\n\nexport interface MetroResolverConfig {\n projectRoot: string\n resolver?: Record<string, any>\n}\n\nexport interface MetroResolvedDependency {\n specifier: string\n resolvedId: string\n external: boolean\n}\n\nexport interface MetroModuleSpecifier {\n specifier: string\n isESMImport: boolean\n}\n\ntype MetroResolve = (\n context: Record<string, any>,\n specifier: string,\n platform: string | null\n) => { type: string; filePath?: string }\n\nfunction compareCodeUnits(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction findClosestPackage(path: string): {\n rootPath: string\n packageJson: Record<string, any>\n packageRelativePath: string\n} | null {\n let directory = existsSync(path) && statSync(path).isDirectory() ? path : dirname(path)\n const root = parse(directory).root\n while (true) {\n const packagePath = join(directory, 'package.json')\n if (existsSync(packagePath)) {\n try {\n return {\n rootPath: directory,\n packageJson: JSON.parse(readFileSync(packagePath, 'utf8')),\n packageRelativePath: relative(directory, path),\n }\n } catch {\n return null\n }\n }\n if (directory === root || directory.endsWith(`${join('node_modules')}`)) {\n return null\n }\n directory = dirname(directory)\n }\n}\n\nfunction lookup(projectRoot: string, path: string) {\n const absolutePath = isAbsolute(path) ? path : resolve(projectRoot, path)\n try {\n const stat = lstatSync(absolutePath)\n const realPath = realpathSync(absolutePath)\n return {\n exists: true as const,\n type: (stat.isDirectory() ? 'd' : 'f') as 'd' | 'f',\n realPath,\n }\n } catch {\n return { exists: false as const }\n }\n}\n\nexport function moduleSpecifiersFromAst(ast: unknown): MetroModuleSpecifier[] {\n const specifiers = new Map<string, boolean>()\n const seen = new Set<object>()\n\n function add(value: unknown, isESMImport: boolean): void {\n if (typeof value !== 'string') return\n specifiers.set(value, (specifiers.get(value) ?? false) || isESMImport)\n }\n\n function visit(value: unknown): void {\n if (!value || typeof value !== 'object') return\n if (seen.has(value)) return\n seen.add(value)\n if (Array.isArray(value)) {\n for (const child of value) visit(child)\n return\n }\n const node = value as Record<string, any>\n if (\n node.type === 'ImportDeclaration' ||\n node.type === 'ExportAllDeclaration' ||\n node.type === 'ExportNamedDeclaration'\n ) {\n add(node.source?.value, true)\n } else if (node.type === 'CallExpression') {\n const first = node.arguments?.[0]\n if (node.callee?.type === 'Import') {\n add(first?.value, true)\n } else if (node.callee?.type === 'Identifier' && node.callee.name === 'require') {\n add(first?.value, false)\n }\n }\n for (const [key, child] of Object.entries(node)) {\n if (key === 'loc' || key === 'comments' || key === 'tokens') continue\n visit(child)\n }\n }\n\n visit(ast)\n return [...specifiers]\n .sort(([left], [right]) => compareCodeUnits(left, right))\n .map(([specifier, isESMImport]) => ({ specifier, isESMImport }))\n}\n\nexport function createMetroCompilerResolver(config: MetroResolverConfig): {\n version: string\n resolve(\n importer: string,\n dependency: MetroModuleSpecifier,\n platform: string | null\n ): MetroResolvedDependency | null\n} {\n const requireFromProject = createRequire(join(config.projectRoot, 'package.json'))\n const resolverPackage = requireFromProject('metro-resolver/package.json') as {\n version: string\n }\n if (!resolverPackage.version.startsWith('0.84.')) {\n throw new Error(\n `@tamagui/metro-plugin requires the Metro 0.84 resolver contract, found ${resolverPackage.version}`\n )\n }\n const resolverModule = requireFromProject('metro-resolver')\n const metroResolve: MetroResolve = resolverModule.resolve\n const createDefaultContextModule = requireFromProject(\n 'metro-resolver/private/createDefaultContext'\n )\n const createDefaultContext =\n createDefaultContextModule.default ?? createDefaultContextModule\n const resolver = config.resolver ?? {}\n const fileSystemLookup = (path: string) => lookup(config.projectRoot, path)\n const getPackage = (packagePath: string) => {\n try {\n return JSON.parse(readFileSync(packagePath, 'utf8'))\n } catch {\n return null\n }\n }\n\n return {\n version: resolverPackage.version,\n resolve(importer, dependency, platform) {\n const dependencyDescriptor = {\n name: dependency.specifier,\n data: {\n asyncType: null,\n isESMImport: dependency.isESMImport,\n key: dependency.specifier,\n locs: [],\n },\n }\n const context = createDefaultContext(\n {\n allowHaste: false,\n assetExts: new Set(resolver.assetExts ?? []),\n customResolverOptions: {},\n dev: true,\n disableHierarchicalLookup: resolver.disableHierarchicalLookup ?? false,\n doesFileExist: (path: string) => fileSystemLookup(path).type === 'f',\n extraNodeModules: resolver.extraNodeModules ?? null,\n fileSystemLookup,\n getPackage,\n getPackageForModule: findClosestPackage,\n isESMImport: dependency.isESMImport,\n mainFields: resolver.resolverMainFields ?? ['react-native', 'browser', 'main'],\n nodeModulesPaths: resolver.nodeModulesPaths ?? [],\n originModulePath: importer,\n preferNativePlatform: true,\n projectRoot: config.projectRoot,\n resolveAsset: () => null,\n resolveHasteModule: () => null,\n resolveHastePackage: () => null,\n resolveRequest: resolver.resolveRequest ?? null,\n sourceExts: resolver.sourceExts ?? ['js', 'jsx', 'json', 'ts', 'tsx'],\n unstable_conditionNames: resolver.unstable_conditionNames ?? [],\n unstable_conditionsByPlatform: resolver.unstable_conditionsByPlatform ?? {},\n unstable_enablePackageExports: resolver.unstable_enablePackageExports ?? true,\n unstable_logWarning: (message: string) =>\n config.resolver?.unstable_logWarning?.(message),\n },\n dependencyDescriptor\n )\n const result = metroResolve(context, dependency.specifier, platform)\n if (result.type === 'empty') return null\n if (result.type !== 'sourceFile' || !result.filePath) return null\n const resolvedId = realpathSync(result.filePath)\n return {\n specifier: dependency.specifier,\n resolvedId,\n external: resolvedId.includes(`${join('node_modules')}`),\n }\n },\n }\n}\n\nexport function isCompilerSourceFile(path: string): boolean {\n return ['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx'].includes(extname(path))\n}\n"
|
|
10
|
+
]
|
|
11
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { MetroCompilerFrontend } from "./frontend";
|
|
2
|
+
export interface MetroGetTransformOptionsContext {
|
|
3
|
+
dev: boolean;
|
|
4
|
+
hot: boolean;
|
|
5
|
+
platform: string | null;
|
|
6
|
+
}
|
|
7
|
+
export type MetroGetTransformOptions = (this: unknown, entryFiles: string[], transformOptions: MetroGetTransformOptionsContext, getDependencies: (path: string) => Promise<string[]>) => Promise<{
|
|
8
|
+
transform?: Record<string, any>;
|
|
9
|
+
[key: string]: any;
|
|
10
|
+
}>;
|
|
11
|
+
export declare function composeMetroGetTransformOptions(frontend: Pick<MetroCompilerFrontend, "ensureValidCache">, userGetTransformOptions?: MetroGetTransformOptions): MetroGetTransformOptions;
|
|
12
|
+
|
|
13
|
+
//# sourceMappingURL=transformOptions.d.ts.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"mappings": "AAAA,cAAc,6BAA6B;AAE3C,iBAAiB,gCAAgC;CAC/C;CACA;CACA;;AAGF,YAAY,2CAEV,sBACA,kBAAkB,iCAClB,kBAAkB,iBAAiB,sBAChC,QAAQ;CAAE,YAAY;;;AAE3B,OAAO,iBAAS,gCACd,UAAU,KAAK,uBAAuB,qBACtC,0BAA0B,2BACzB",
|
|
3
|
+
"names": [],
|
|
4
|
+
"sources": [
|
|
5
|
+
"src/transformOptions.ts"
|
|
6
|
+
],
|
|
7
|
+
"version": 3,
|
|
8
|
+
"sourcesContent": [
|
|
9
|
+
"import type { MetroCompilerFrontend } from './frontend'\n\nexport interface MetroGetTransformOptionsContext {\n dev: boolean\n hot: boolean\n platform: string | null\n}\n\nexport type MetroGetTransformOptions = (\n this: unknown,\n entryFiles: string[],\n transformOptions: MetroGetTransformOptionsContext,\n getDependencies: (path: string) => Promise<string[]>\n) => Promise<{ transform?: Record<string, any>; [key: string]: any }>\n\nexport function composeMetroGetTransformOptions(\n frontend: Pick<MetroCompilerFrontend, 'ensureValidCache'>,\n userGetTransformOptions?: MetroGetTransformOptions\n): MetroGetTransformOptions {\n return async function (this: unknown, entryFiles, transformOptions, getDependencies) {\n const userOptions = userGetTransformOptions\n ? await userGetTransformOptions.call(\n this,\n entryFiles,\n transformOptions,\n getDependencies\n )\n : { transform: {} }\n await frontend.ensureValidCache({\n ...transformOptions,\n entryFiles,\n transform: userOptions.transform ?? {},\n })\n return userOptions\n }\n}\n"
|
|
10
|
+
]
|
|
11
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type MetroBabelTransformArgs, type MetroBabelTransformResult } from "./babel";
|
|
2
|
+
import { type MetroCompilerDiagnostic } from "./diagnostics";
|
|
3
|
+
import { type MetroCompilerLoweringResult } from "./lowering";
|
|
4
|
+
export interface MetroCompilerTransformerOptions {
|
|
5
|
+
cacheBaseRoot: string;
|
|
6
|
+
originalBabelTransformerPath: string;
|
|
7
|
+
projectRoot: string;
|
|
8
|
+
/**
|
|
9
|
+
* The integration-owned `TAMAGUI_RUNTIME` literal for this bundle request.
|
|
10
|
+
* Metro never reads an ambient value: the literal is decided by the build and
|
|
11
|
+
* inlined here so every guard is a constant.
|
|
12
|
+
*/
|
|
13
|
+
runtimeLiteral?: "full" | "zero";
|
|
14
|
+
}
|
|
15
|
+
export interface MetroCompilerTransformMetadata {
|
|
16
|
+
cacheHit: boolean;
|
|
17
|
+
diagnostics: MetroCompilerDiagnostic[];
|
|
18
|
+
lowering?: MetroCompilerLoweringResult;
|
|
19
|
+
}
|
|
20
|
+
export declare function createMetroCompilerTransformer(config: MetroCompilerTransformerOptions): {
|
|
21
|
+
transform(args: MetroBabelTransformArgs): Promise<MetroBabelTransformResult>;
|
|
22
|
+
getCacheKey(): string;
|
|
23
|
+
};
|
|
24
|
+
export declare function writeMetroCompilerTransformerBridge(transformerFactoryPath: string, config: MetroCompilerTransformerOptions): string;
|
|
25
|
+
|
|
26
|
+
//# sourceMappingURL=transformer.d.ts.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
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
|
+
"names": [],
|
|
4
|
+
"sources": [
|
|
5
|
+
"src/transformer.ts"
|
|
6
|
+
],
|
|
7
|
+
"version": 3,
|
|
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}\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
|
+
]
|
|
11
|
+
}
|