rnwind 0.0.3 → 0.0.5
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/lib/cjs/core/normalize-classname.cjs +25 -0
- package/lib/cjs/core/normalize-classname.cjs.map +1 -0
- package/lib/cjs/core/normalize-classname.d.ts +10 -0
- package/lib/cjs/core/style-builder/build-style.cjs +258 -58
- package/lib/cjs/core/style-builder/build-style.cjs.map +1 -1
- package/lib/cjs/core/style-builder/build-style.d.ts +6 -1
- package/lib/cjs/core/style-builder/union-builder.cjs +37 -3
- package/lib/cjs/core/style-builder/union-builder.cjs.map +1 -1
- package/lib/cjs/core/style-builder/union-builder.d.ts +21 -1
- package/lib/cjs/metro/css-imports.cjs +81 -0
- package/lib/cjs/metro/css-imports.cjs.map +1 -0
- package/lib/cjs/metro/css-imports.d.ts +8 -0
- package/lib/cjs/metro/dts.cjs +7 -16
- package/lib/cjs/metro/dts.cjs.map +1 -1
- package/lib/cjs/metro/dts.d.ts +2 -4
- package/lib/cjs/metro/state.cjs +38 -86
- package/lib/cjs/metro/state.cjs.map +1 -1
- package/lib/cjs/metro/state.d.ts +8 -25
- package/lib/cjs/metro/transformer.cjs +193 -34
- package/lib/cjs/metro/transformer.cjs.map +1 -1
- package/lib/cjs/metro/with-config.cjs +2 -2
- package/lib/cjs/metro/with-config.cjs.map +1 -1
- package/lib/cjs/metro/with-config.d.ts +11 -26
- package/lib/cjs/metro/wrap-imports.cjs +273 -0
- package/lib/cjs/metro/wrap-imports.cjs.map +1 -0
- package/lib/cjs/metro/wrap-imports.d.ts +26 -0
- package/lib/cjs/runtime/components/rnwind-provider.cjs +0 -17
- package/lib/cjs/runtime/components/rnwind-provider.cjs.map +1 -1
- package/lib/cjs/runtime/components/rnwind-provider.d.ts +0 -14
- package/lib/cjs/runtime/hooks/use-css.cjs +16 -10
- package/lib/cjs/runtime/hooks/use-css.cjs.map +1 -1
- package/lib/cjs/runtime/hooks/use-css.d.ts +15 -9
- package/lib/cjs/runtime/index.cjs +11 -13
- package/lib/cjs/runtime/index.cjs.map +1 -1
- package/lib/cjs/runtime/index.d.ts +4 -9
- package/lib/cjs/runtime/lookup-css.cjs +10 -0
- package/lib/cjs/runtime/lookup-css.cjs.map +1 -1
- package/lib/cjs/runtime/lookup-css.d.ts +7 -0
- package/lib/cjs/runtime/resolve.cjs +348 -0
- package/lib/cjs/runtime/resolve.cjs.map +1 -0
- package/lib/cjs/runtime/resolve.d.ts +61 -0
- package/lib/cjs/runtime/wrap.cjs +254 -0
- package/lib/cjs/runtime/wrap.cjs.map +1 -0
- package/lib/cjs/runtime/wrap.d.ts +37 -0
- package/lib/cjs/testing/index.cjs +81 -50
- package/lib/cjs/testing/index.cjs.map +1 -1
- package/lib/esm/core/normalize-classname.d.ts +10 -0
- package/lib/esm/core/normalize-classname.mjs +23 -0
- package/lib/esm/core/normalize-classname.mjs.map +1 -0
- package/lib/esm/core/style-builder/build-style.d.ts +6 -1
- package/lib/esm/core/style-builder/build-style.mjs +258 -58
- package/lib/esm/core/style-builder/build-style.mjs.map +1 -1
- package/lib/esm/core/style-builder/union-builder.d.ts +21 -1
- package/lib/esm/core/style-builder/union-builder.mjs +37 -3
- package/lib/esm/core/style-builder/union-builder.mjs.map +1 -1
- package/lib/esm/metro/css-imports.d.ts +8 -0
- package/lib/esm/metro/css-imports.mjs +79 -0
- package/lib/esm/metro/css-imports.mjs.map +1 -0
- package/lib/esm/metro/dts.d.ts +2 -4
- package/lib/esm/metro/dts.mjs +7 -16
- package/lib/esm/metro/dts.mjs.map +1 -1
- package/lib/esm/metro/state.d.ts +8 -25
- package/lib/esm/metro/state.mjs +39 -85
- package/lib/esm/metro/state.mjs.map +1 -1
- package/lib/esm/metro/transformer.mjs +194 -35
- package/lib/esm/metro/transformer.mjs.map +1 -1
- package/lib/esm/metro/with-config.d.ts +11 -26
- package/lib/esm/metro/with-config.mjs +2 -2
- package/lib/esm/metro/with-config.mjs.map +1 -1
- package/lib/esm/metro/wrap-imports.d.ts +26 -0
- package/lib/esm/metro/wrap-imports.mjs +250 -0
- package/lib/esm/metro/wrap-imports.mjs.map +1 -0
- package/lib/esm/runtime/components/rnwind-provider.d.ts +0 -14
- package/lib/esm/runtime/components/rnwind-provider.mjs +1 -17
- package/lib/esm/runtime/components/rnwind-provider.mjs.map +1 -1
- package/lib/esm/runtime/hooks/use-css.d.ts +15 -9
- package/lib/esm/runtime/hooks/use-css.mjs +16 -10
- package/lib/esm/runtime/hooks/use-css.mjs.map +1 -1
- package/lib/esm/runtime/index.d.ts +4 -9
- package/lib/esm/runtime/index.mjs +4 -4
- package/lib/esm/runtime/index.mjs.map +1 -1
- package/lib/esm/runtime/lookup-css.d.ts +7 -0
- package/lib/esm/runtime/lookup-css.mjs +10 -1
- package/lib/esm/runtime/lookup-css.mjs.map +1 -1
- package/lib/esm/runtime/resolve.d.ts +61 -0
- package/lib/esm/runtime/resolve.mjs +341 -0
- package/lib/esm/runtime/resolve.mjs.map +1 -0
- package/lib/esm/runtime/wrap.d.ts +37 -0
- package/lib/esm/runtime/wrap.mjs +251 -0
- package/lib/esm/runtime/wrap.mjs.map +1 -0
- package/lib/esm/testing/index.mjs +84 -53
- package/lib/esm/testing/index.mjs.map +1 -1
- package/package.json +2 -1
- package/src/core/normalize-classname.ts +19 -0
- package/src/core/style-builder/build-style.ts +286 -55
- package/src/core/style-builder/union-builder.ts +36 -3
- package/src/metro/css-imports.ts +75 -0
- package/src/metro/dts.ts +7 -19
- package/src/metro/state.ts +38 -83
- package/src/metro/transformer.ts +190 -34
- package/src/metro/with-config.ts +13 -28
- package/src/metro/wrap-imports.ts +260 -0
- package/src/runtime/components/rnwind-provider.tsx +0 -17
- package/src/runtime/hooks/use-css.ts +17 -11
- package/src/runtime/index.ts +3 -26
- package/src/runtime/lookup-css.ts +10 -0
- package/src/runtime/resolve.ts +381 -0
- package/src/runtime/wrap.tsx +267 -0
- package/src/testing/index.ts +106 -56
- package/lib/cjs/core/parser/text-truncate.cjs +0 -78
- package/lib/cjs/core/parser/text-truncate.cjs.map +0 -1
- package/lib/cjs/metro/transform-ast.cjs +0 -1472
- package/lib/cjs/metro/transform-ast.cjs.map +0 -1
- package/lib/cjs/metro/transform-ast.d.ts +0 -88
- package/lib/cjs/runtime/haptics.cjs +0 -113
- package/lib/cjs/runtime/haptics.cjs.map +0 -1
- package/lib/cjs/runtime/haptics.d.ts +0 -48
- package/lib/cjs/runtime/interactive-box.cjs +0 -35
- package/lib/cjs/runtime/interactive-box.cjs.map +0 -1
- package/lib/cjs/runtime/interactive-box.d.ts +0 -40
- package/lib/esm/core/parser/text-truncate.mjs +0 -75
- package/lib/esm/core/parser/text-truncate.mjs.map +0 -1
- package/lib/esm/metro/transform-ast.d.ts +0 -88
- package/lib/esm/metro/transform-ast.mjs +0 -1451
- package/lib/esm/metro/transform-ast.mjs.map +0 -1
- package/lib/esm/runtime/haptics.d.ts +0 -48
- package/lib/esm/runtime/haptics.mjs +0 -110
- package/lib/esm/runtime/haptics.mjs.map +0 -1
- package/lib/esm/runtime/interactive-box.d.ts +0 -40
- package/lib/esm/runtime/interactive-box.mjs +0 -33
- package/lib/esm/runtime/interactive-box.mjs.map +0 -1
- package/src/metro/transform-ast.ts +0 -1729
- package/src/runtime/haptics.ts +0 -120
- package/src/runtime/interactive-box.tsx +0 -57
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transformer.cjs","sources":["../../../../src/metro/transformer.ts"],"sourcesContent":["import type { File } from '@babel/types'\nimport * as t from '@babel/types'\nimport { parse } from '@babel/parser'\nimport generate from '@babel/generator'\nimport { createHash } from 'node:crypto'\nimport { realpathSync } from 'node:fs'\nimport { transformAst } from './transform-ast'\nimport { getClassNamePrefixes, getHostComponents, getHostSources, getRnwindCacheKey, getRnwindState, onThemeChange } from './state'\nimport { STYLE_SPECIFIERS, THEME_SIGNATURE_MODULE } from './resolver'\nimport { filterUnknownClassCandidates } from './warn-unknown-classes'\n\n/** The shape of the upstream module we delegate parsing/babel work to. */\ninterface UpstreamTransformer {\n transform: (args: BabelTransformerArgs) => Promise<BabelTransformerResult> | BabelTransformerResult\n}\n\n/** Env var that points at the upstream `babelTransformerPath` we override. */\nconst UPSTREAM_ENV = 'RNWIND_UPSTREAM_TRANSFORMER'\n\n/** Cached upstream module — required once, reused across every transform call. */\nlet cachedUpstream: UpstreamTransformer | null = null\n\nconst generateModule = (generate as unknown as { default?: typeof generate }).default ?? generate\n\n/**\n * Parse user source with the broad plugin set (Flow + JSX + TypeScript\n * + class properties). Permissive on purpose so we don't reject any\n * file the upstream could have handled. Returns `null` when parse\n * fails — caller falls back to the raw source string.\n * @param source Source text.\n * @returns Parsed AST, or null on parse failure.\n */\nfunction parseUserSource(source: string): File | null {\n try {\n return parse(source, {\n sourceType: 'unambiguous',\n allowReturnOutsideFunction: true,\n allowImportExportEverywhere: true,\n plugins: ['typescript', 'jsx'],\n }) as unknown as File\n } catch {\n try {\n return parse(source, {\n sourceType: 'unambiguous',\n allowReturnOutsideFunction: true,\n allowImportExportEverywhere: true,\n plugins: ['flow', 'jsx'],\n }) as unknown as File\n } catch {\n return null\n }\n }\n}\n\n/**\n * Print Tailwind-shaped candidates oxide picked up but the parser\n * could NOT compile — typo, missing custom utility, or class not in\n * the user's theme. Filtering by candidates that ALSO appear inside a\n * `className=\"…\"` literal eliminates false positives from imports,\n * comments, and JSX prop values.\n * @param source Original source text — searched for className literals.\n * @param candidates Every candidate oxide surfaced from the source.\n * @param atoms Successfully resolved atoms (keys are class names).\n * @param filename Source path, prefixed onto the warning.\n */\nfunction warnUnknownClasses(\n source: string,\n candidates: readonly string[],\n atoms: ReadonlyMap<string, unknown>,\n filename: string,\n): void {\n const atomNames = new Set(atoms.keys())\n const unknown = filterUnknownClassCandidates(source, candidates, atomNames)\n if (unknown.length === 0) return\n // eslint-disable-next-line no-console\n console.warn(`rnwind: unknown class${unknown.length > 1 ? 'es' : ''} in ${filename}: ${unknown.join(', ')}`)\n}\n\n/**\n * Extract the bare extension for oxide / internal switches.\n * @param filename Absolute path.\n * @returns Extension without the leading dot (`tsx` / `ts` / `js` / `jsx`).\n */\nfunction extensionOf(filename: string): string {\n const index = filename.lastIndexOf('.')\n if (index === -1) return 'tsx'\n return filename.slice(index + 1)\n}\n\n/**\n * Read the project root Metro hands us per-transform. Falls back to\n * `process.cwd()` only when the upstream harness doesn't set it (unit\n * tests, standalone). Metro's production pipeline always sets it.\n * @param args Metro transformer args.\n * @returns Absolute project root.\n */\nfunction projectRootOf(args: BabelTransformerArgs): string {\n const fromOptions = args.options?.projectRoot\n if (typeof fromOptions === 'string' && fromOptions.length > 0) return fromOptions\n return process.cwd()\n}\n\n/**\n * Whether a `.css` filename is the user's theme entry (the file\n * `withRnwindConfig` pointed us at via `RNWIND_CSS_ENTRY_FILE`).\n * Only the theme CSS should trigger a scheme rebuild — unrelated CSS\n * files in the project stay invisible to rnwind.\n * @param filename Absolute CSS path.\n * @returns Whether the file is the configured theme entry.\n */\nfunction isThemeCssEntry(filename: string): boolean {\n const cssEntry = process.env.RNWIND_CSS_ENTRY_FILE\n return typeof cssEntry === 'string' && cssEntry.length > 0 && cssEntry === filename\n}\n\n/**\n * Parse + run rnwind's JSX rewrite + regenerate source code. When\n * parsing or transformation fails, fall back to the original source —\n * we don't want a transient parse error to crash Metro for a file the\n * upstream might handle fine.\n * @param args Metro args; `src` is the original source text.\n * @returns Rewritten source text (with `className=` rewrites applied).\n */\nasync function rewriteSource(args: BabelTransformerArgs): Promise<string> {\n const ast = parseUserSource(args.src)\n if (!ast) return args.src\n\n const state = getRnwindState(projectRootOf(args))\n const extension = extensionOf(args.filename)\n const parsed = await state.parser.parseAtoms({ content: args.src, extension })\n\n warnUnknownClasses(args.src, parsed.candidates, parsed.atoms, args.filename)\n\n const classNamePrefixes = getClassNamePrefixes()\n const hostSources = getHostSources()\n const hostComponents = getHostComponents()\n if (parsed.atoms.size === 0) {\n state.builder.dropFile(args.filename)\n await state.builder.writeSchemes()\n transformAst(ast, {\n styleSpecifiers: [],\n gradientAtoms: parsed.gradientAtoms,\n hapticAtoms: parsed.hapticAtoms,\n classNamePrefixes,\n hostSources,\n hostComponents,\n })\n injectThemeSignatureImport(ast)\n return generateModule(ast).code\n }\n\n const { changed } = await state.builder.recordFile(args.filename, parsed.atoms, parsed.keyframes)\n if (changed) await state.builder.writeSchemes()\n\n transformAst(ast, {\n styleSpecifiers: STYLE_SPECIFIERS as unknown as readonly string[],\n gradientAtoms: parsed.gradientAtoms,\n hapticAtoms: parsed.hapticAtoms,\n classNamePrefixes,\n hostSources,\n hostComponents,\n })\n injectThemeSignatureImport(ast)\n return generateModule(ast).code\n}\n\n/**\n * Prepend `import 'rnwind/__generated/theme-signature'` to every\n * rnwind-transformed file. The resolver maps that specifier to the\n * user's theme CSS so Metro's dependency graph carries a real edge\n * from this JS file to the CSS. When the user edits `global.css`,\n * the CSS module's SHA1 changes, and Metro invalidates every JS file\n * holding this import — forcing them to re-transform with the new\n * theme. The `.css` branch in {@link transform} returns an empty\n * `export {}` module so the runtime cost is one extra `require()`.\n * @param ast Babel File AST to mutate in place.\n */\nfunction injectThemeSignatureImport(ast: File): void {\n const declaration = t.importDeclaration([], t.stringLiteral(THEME_SIGNATURE_MODULE))\n ast.program.body.unshift(declaration)\n}\n\n/**\n * Read the upstream transformer's `getCacheKey()` so our cache-key\n * contribution composes with — rather than replaces — whatever the\n * host framework wants to mix in.\n * @returns Upstream cache key, or `null` when no upstream exposes one.\n */\nfunction loadUpstreamCacheKey(): string | null {\n const upstream = loadUpstream() as (UpstreamTransformer & { getCacheKey?: () => string }) | null\n if (!upstream) return null\n try {\n return typeof upstream.getCacheKey === 'function' ? upstream.getCacheKey() : null\n } catch {\n return null\n }\n}\n\n/**\n * Invoke the upstream `babelTransformerPath` Metro originally had\n * configured. The path is read from `RNWIND_UPSTREAM_TRANSFORMER`,\n * which `withRnwindConfig` sets at Metro startup. When the env var is\n * unset (unit tests, standalone use), fall back to a typescript+jsx\n * parse.\n * @param args Metro's per-file args.\n * @returns Upstream transform result containing the post-babel AST.\n */\nasync function runUpstream(args: BabelTransformerArgs): Promise<BabelTransformerResult> {\n if (args.ast && !process.env[UPSTREAM_ENV]) return { ast: args.ast }\n const upstream = loadUpstream()\n if (upstream) return await Promise.resolve(upstream.transform(args))\n if (args.ast) return { ast: args.ast }\n return { ast: parseSource(args.src) }\n}\n\n/**\n * Lazily require the upstream transformer module. Cached after first\n * load so per-file overhead is one cache lookup.\n * @returns Upstream module, or null when env is unset.\n */\nfunction loadUpstream(): UpstreamTransformer | null {\n if (cachedUpstream) return cachedUpstream\n const upstreamPath = process.env[UPSTREAM_ENV]\n if (!upstreamPath || upstreamPath.length === 0) return null\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n const required = require(upstreamPath) as UpstreamTransformer | { default?: UpstreamTransformer }\n const upstream = (required as { default?: UpstreamTransformer }).default ?? (required as UpstreamTransformer)\n if (typeof upstream.transform !== 'function') return null\n cachedUpstream = upstream\n return upstream\n } catch (error) {\n // eslint-disable-next-line no-console\n if (process.env.RNWIND_DEBUG) console.error('rnwind: failed to load upstream transformer:', error)\n return null\n }\n}\n\n/**\n * Cheap guard — the file has to look JS/TS, live outside `node_modules`,\n * and mention `className=` before we spend AST cycles on it.\n *\n * Symlink awareness: monorepo workspaces (yarn / pnpm / bun workspaces)\n * symlink each package into the consumer's `node_modules/<name>`, so a\n * file from `packages/ui/src/Foo.tsx` ends up reaching the transformer\n * as `<root>/node_modules/ui/src/Foo.tsx`. The naïve `/node_modules/`\n * check would skip every workspace UI file. We `realpath` the filename\n * once and only bail when the resolved real path is ALSO under\n * node_modules — true third-party installs.\n * @param args Metro args.\n * @returns Whether the file might need the rnwind pass.\n */\nfunction isRewriteCandidate(args: BabelTransformerArgs): boolean {\n if (!/\\.(?:tsx|ts|jsx|js)$/i.test(args.filename)) return false\n // Case-insensitive so `<prefix>ClassName=` (e.g. `contentContainerClassName=`)\n // — which has a capital `C` and so doesn't contain the lowercase\n // `className=` — still routes the file through the rewrite pass.\n if (!/classname=/i.test(args.src)) return false\n if (!args.filename.includes('/node_modules/')) return true\n // node_modules in path → could be a workspace symlink; resolve it.\n try {\n return !realpathSync(args.filename).includes('/node_modules/')\n } catch {\n // realpath failed (broken symlink, missing file). Fall back to skipping.\n return false\n }\n}\n\n/**\n * Fallback parse when no upstream is configured AND Metro didn't hand\n * us an AST. Used by unit tests and standalone setups.\n * @param source Source text.\n * @returns Parsed Babel File.\n */\nfunction parseSource(source: string): File {\n return parse(source, { sourceType: 'module', plugins: ['typescript', 'jsx'] }) as unknown as File\n}\n\n/** Metro's babel transformer signature. */\nexport interface BabelTransformerArgs {\n filename: string\n src: string\n options: { projectRoot?: string; [key: string]: unknown }\n ast?: File\n plugins?: readonly unknown[]\n}\n\n/** Return shape Metro expects from a babel transformer. */\nexport interface BabelTransformerResult {\n ast: File\n metadata?: unknown\n}\n\n/**\n * rnwind's Metro babel transformer. Two phases per source file:\n *\n * 1. **Pre-process the source string before handing it to the upstream\n * babel pipeline.** babel-preset-expo / React's JSX transform run\n * inside the upstream and convert `<View className=\"...\"/>` into\n * `React.createElement(View, {className})`. If we walked the AST\n * AFTER the upstream, there'd be no JSX attributes left to\n * rewrite. So we parse, run our pass, regenerate code, and feed\n * THAT to the upstream as `src`.\n * 2. **Delegate to the upstream `babelTransformerPath`** (Expo's\n * default handles Flow stripping, expo-router macros, etc.).\n *\n * Skip both phases when the file isn't a JS/TS source under user\n * code, or doesn't mention `className=` — hand straight to upstream.\n * @param args Metro's per-file args.\n * @returns Mutated AST + metadata.\n */\nexport async function transform(args: BabelTransformerArgs): Promise<BabelTransformerResult> {\n // Short-circuit `.css` inputs: the theme CSS is pulled into the dep\n // graph as a sentinel (see `THEME_SIGNATURE_MODULE` in resolver.ts)\n // so Metro watches it and invalidates importers on edit, but the\n // file's CSS syntax can't go through a JS babel transformer.\n //\n // When the CSS being transformed IS the user's theme entry, we\n // piggyback on Metro's own file-watcher: Metro calls us here on\n // every CSS save; we trigger `onThemeChange` to rebuild parser +\n // rewrite scheme files with the new values. Metro's dep graph then\n // HMRs the regenerated `common.style.js` to the running app.\n //\n // Emitting the CSS content hash in the fake JS output is what makes\n // Metro propagate invalidation to downstream importers — constant\n // `export {}` bytes would never look changed and Metro would skip\n // the chain.\n if (args.filename.endsWith('.css')) {\n if (isThemeCssEntry(args.filename)) {\n try {\n await onThemeChange(projectRootOf(args))\n } catch {\n // CSS edit happened outside a configured project (e.g. tests).\n }\n }\n const themeHash = createHash('sha256').update(args.src).digest('hex').slice(0, 16)\n const stub = `export const __rnwindThemeHash = ${JSON.stringify(themeHash)};\\n`\n return { ast: parse(stub, { sourceType: 'module' }) as unknown as File }\n }\n if (!isRewriteCandidate(args)) {\n if (/\\.(?:tsx|ts|jsx|js)$/i.test(args.filename) && !args.filename.includes('/node_modules/')) {\n try {\n getRnwindState(projectRootOf(args)).builder.dropFile(args.filename)\n } catch {\n // State not configured (e.g. test). Nothing to drop.\n }\n }\n return runUpstream(args)\n }\n\n const rewrittenSource = await rewriteSource(args)\n return runUpstream({ ...args, src: rewrittenSource, ast: undefined })\n}\n\n/**\n * Metro's babel-transformer contract: a `getCacheKey()` export is\n * sampled per-file and mixed into the transform cache key. Returning\n * a string that includes the theme CSS content hash invalidates every\n * cached transform on every CSS edit — so the bundle rebuilds with\n * the new theme automatically on the next request.\n * @returns Cache-key segment that includes rnwind's current theme hash.\n */\nexport function getCacheKey(): string {\n const upstreamKey = loadUpstreamCacheKey()\n const ownKey = getRnwindCacheKey()\n return upstreamKey ? `${upstreamKey}|${ownKey}` : ownKey\n}\n\n/** Test-only — drop the cached upstream so a new env var picks up next call. */\nexport function __resetUpstreamCache(): void {\n cachedUpstream = null\n}\n"],"names":["parse","filterUnknownClassCandidates","state","getRnwindState","getClassNamePrefixes","getHostSources","getHostComponents","transformAst","STYLE_SPECIFIERS","t","THEME_SIGNATURE_MODULE","realpathSync","onThemeChange","createHash","getRnwindCacheKey"],"mappings":";;;;;;;;;;;;;;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,CAAC,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,SAAS,EAAE,CAAC;AACvE;AAEA;;;;;;;AAOG;SACa,WAAW,GAAA;AACzB,IAAA,MAAM,WAAW,GAAG,oBAAoB,EAAE;AAC1C,IAAA,MAAM,MAAM,GAAGW,uBAAiB,EAAE;AAClC,IAAA,OAAO,WAAW,GAAG,CAAA,EAAG,WAAW,CAAA,CAAA,EAAI,MAAM,CAAA,CAAE,GAAG,MAAM;AAC1D;AAEA;SACgB,oBAAoB,GAAA;IAClC,cAAc,GAAG,IAAI;AACvB;;;;;;"}
|
|
1
|
+
{"version":3,"file":"transformer.cjs","sources":["../../../../src/metro/transformer.ts"],"sourcesContent":["import type { File } from '@babel/types'\nimport * as t from '@babel/types'\nimport { parse } from '@babel/parser'\nimport generate from '@babel/generator'\nimport { createHash } from 'node:crypto'\nimport { realpathSync } from 'node:fs'\nimport { getRnwindCacheKey, getRnwindState, getWrapModules, onThemeChange } from './state'\nimport { rewriteWrapImports } from './wrap-imports'\nimport { STYLE_SPECIFIERS, THEME_SIGNATURE_MODULE } from './resolver'\nimport { filterUnknownClassCandidates } from './warn-unknown-classes'\n\n/** The shape of the upstream module we delegate parsing/babel work to. */\ninterface UpstreamTransformer {\n transform: (args: BabelTransformerArgs) => Promise<BabelTransformerResult> | BabelTransformerResult\n}\n\n/** Env var that points at the upstream `babelTransformerPath` we override. */\nconst UPSTREAM_ENV = 'RNWIND_UPSTREAM_TRANSFORMER'\n\n/** Cached upstream module — required once, reused across every transform call. */\nlet cachedUpstream: UpstreamTransformer | null = null\n\nconst generateModule = (generate as unknown as { default?: typeof generate }).default ?? generate\n\n/**\n * Parse user source with the broad plugin set (Flow + JSX + TypeScript\n * + class properties). Permissive on purpose so we don't reject any\n * file the upstream could have handled. Returns `null` when parse\n * fails — caller falls back to the raw source string.\n * @param source Source text.\n * @returns Parsed AST, or null on parse failure.\n */\nfunction parseUserSource(source: string): File | null {\n try {\n return parse(source, {\n sourceType: 'unambiguous',\n allowReturnOutsideFunction: true,\n allowImportExportEverywhere: true,\n plugins: ['typescript', 'jsx'],\n }) as unknown as File\n } catch {\n try {\n return parse(source, {\n sourceType: 'unambiguous',\n allowReturnOutsideFunction: true,\n allowImportExportEverywhere: true,\n plugins: ['flow', 'jsx'],\n }) as unknown as File\n } catch {\n return null\n }\n }\n}\n\n/**\n * Print Tailwind-shaped candidates oxide picked up but the parser\n * could NOT compile — typo, missing custom utility, or class not in\n * the user's theme. Filtering by candidates that ALSO appear inside a\n * `className=\"…\"` literal eliminates false positives from imports,\n * comments, and JSX prop values.\n * @param source Original source text — searched for className literals.\n * @param candidates Every candidate oxide surfaced from the source.\n * @param atoms Successfully resolved atoms (keys are class names).\n * @param filename Source path, prefixed onto the warning.\n * @param features Feature-atom maps (gradient / haptic) — their names are\n * known classes even though they carry no RN style, so they're excluded\n * from the unknown-class warning.\n */\nfunction warnUnknownClasses(\n source: string,\n candidates: readonly string[],\n atoms: ReadonlyMap<string, unknown>,\n filename: string,\n features: ReadonlyArray<ReadonlyMap<string, unknown>> = [],\n): void {\n // Feature atoms (gradient / haptic) resolve to no RN style, so they're\n // absent from `atoms` — but they're NOT unknown. Fold their names into\n // the known set so `active:haptic-rigid` etc. don't warn at build time.\n const known = new Set(atoms.keys())\n for (const map of features) for (const name of map.keys()) known.add(name)\n const unknown = filterUnknownClassCandidates(source, candidates, known)\n if (unknown.length === 0) return\n // eslint-disable-next-line no-console\n console.warn(`rnwind: unknown class${unknown.length > 1 ? 'es' : ''} in ${filename}: ${unknown.join(', ')}`)\n}\n\n/**\n * Extract the bare extension for oxide / internal switches.\n * @param filename Absolute path.\n * @returns Extension without the leading dot (`tsx` / `ts` / `js` / `jsx`).\n */\nfunction extensionOf(filename: string): string {\n const index = filename.lastIndexOf('.')\n if (index === -1) return 'tsx'\n return filename.slice(index + 1)\n}\n\n/**\n * Read the project root Metro hands us per-transform. Falls back to\n * `process.cwd()` only when the upstream harness doesn't set it (unit\n * tests, standalone). Metro's production pipeline always sets it.\n * @param args Metro transformer args.\n * @returns Absolute project root.\n */\nfunction projectRootOf(args: BabelTransformerArgs): string {\n const fromOptions = args.options?.projectRoot\n if (typeof fromOptions === 'string' && fromOptions.length > 0) return fromOptions\n return process.cwd()\n}\n\n/**\n * Whether a `.css` filename is the user's theme entry (the file\n * `withRnwindConfig` pointed us at via `RNWIND_CSS_ENTRY_FILE`).\n * Only the theme CSS should trigger a scheme rebuild — unrelated CSS\n * files in the project stay invisible to rnwind.\n * @param filename Absolute CSS path.\n * @returns Whether the file is the configured theme entry.\n */\nfunction isThemeCssEntry(filename: string): boolean {\n const cssEntry = process.env.RNWIND_CSS_ENTRY_FILE\n return typeof cssEntry === 'string' && cssEntry.length > 0 && cssEntry === filename\n}\n\n/**\n * Wrap host imports + compile any className literals, then regenerate\n * source. Two paths:\n * - **className present**: oxide-scan the file, record its atoms into\n * the union, and inject the generated-style + theme-signature\n * side-effect imports so the runtime registries populate.\n * - **import-only** (a `{...rest}` forwarder or a leaf with no literal\n * `className=`): just wrap the host imports so a forwarded className\n * still resolves at render — no oxide scan, no injected imports.\n *\n * On parse failure, fall back to the original source — a transient parse\n * error shouldn't crash Metro for a file the upstream might handle fine.\n * @param args Metro args; `src` is the original source text.\n * @returns Rewritten source text.\n */\nasync function rewriteSource(args: BabelTransformerArgs): Promise<string> {\n const ast = parseUserSource(args.src)\n if (!ast) return args.src\n\n // Wrap host component imports so `<View className=…>` resolves at render\n // through the runtime `wrap` (works for literal, spread, and forwarded\n // classNames alike). No JSX is rewritten here.\n const wrapped = rewriteWrapImports(ast, getWrapModules())\n\n if (!/classname=/i.test(args.src)) {\n // Import-only file: nothing to compile. Drop any stale atom\n // contribution (className may have just been removed) and emit the\n // wrapped imports — or the untouched source when nothing wrapped.\n dropFileSafely(args.filename, projectRootOf(args))\n return wrapped ? generateModule(ast).code : args.src\n }\n\n const state = getRnwindState(projectRootOf(args))\n const extension = extensionOf(args.filename)\n const parsed = await state.parser.parseAtoms({ content: args.src, extension })\n\n warnUnknownClasses(args.src, parsed.candidates, parsed.atoms, args.filename, [parsed.gradientAtoms, parsed.hapticAtoms])\n\n if (parsed.atoms.size === 0) {\n state.builder.dropFile(args.filename)\n await state.builder.writeSchemes()\n injectThemeSignatureImport(ast)\n return generateModule(ast).code\n }\n\n const literals = collectClassNameLiterals(ast)\n const { changed } = await state.builder.recordFile(args.filename, parsed.atoms, parsed.keyframes, literals)\n if (changed) await state.builder.writeSchemes()\n\n injectSideEffectImports(ast, STYLE_SPECIFIERS)\n injectThemeSignatureImport(ast)\n return generateModule(ast).code\n}\n\n/**\n * Drop a file's union contribution, swallowing the \"state not configured\"\n * error unit tests hit when they call the transformer without\n * `configureRnwindState`.\n * @param filename Absolute source path.\n * @param projectRoot Project root for state lookup.\n */\nfunction dropFileSafely(filename: string, projectRoot: string): void {\n try {\n getRnwindState(projectRoot).builder.dropFile(filename)\n } catch {\n // State not configured (standalone/unit test). Nothing to drop.\n }\n}\n\n/**\n * Whether a JSX attribute names a className-style prop (`className` or\n * any `<prefix>ClassName`).\n * @param node JSX attribute node.\n * @returns True when the attribute is a className prop.\n */\nfunction isClassNameAttribute(node: t.JSXAttribute): boolean {\n if (!t.isJSXIdentifier(node.name)) return false\n const {name} = node.name\n return name === 'className' || name.endsWith('ClassName')\n}\n\n/**\n * Pull static string literals out of a className expression. Handles a\n * bare string, a no-substitution template, and the branches of a\n * ternary / `&&` (so `cond ? 'a' : 'b'` and `flag && 'x'` both register\n * their literals). Dynamic interpolations are skipped — they resolve via\n * the runtime atom path.\n * @param expr Expression inside a `className={...}` container.\n * @param out Accumulator for discovered literals.\n */\nfunction collectLiteralsFromExpression(expr: t.Expression | t.JSXEmptyExpression | null | undefined, out: string[]): void {\n if (!expr) return\n if (t.isStringLiteral(expr)) {\n out.push(expr.value)\n return\n }\n if (t.isTemplateLiteral(expr) && expr.expressions.length === 0 && expr.quasis.length === 1) {\n const cooked = expr.quasis[0]?.value.cooked\n if (typeof cooked === 'string') out.push(cooked)\n return\n }\n if (t.isConditionalExpression(expr)) {\n collectLiteralsFromExpression(expr.consequent, out)\n collectLiteralsFromExpression(expr.alternate, out)\n return\n }\n if (t.isLogicalExpression(expr)) {\n collectLiteralsFromExpression(expr.right as t.Expression, out)\n }\n}\n\n/** AST node keys the literal walk skips — position / comment metadata. */\nconst SKIP_WALK_KEYS = new Set(['type', 'loc', 'start', 'end', 'range', 'leadingComments', 'trailingComments', 'innerComments'])\n\n/**\n * Collect the static literals from one className JSX attribute into the\n * dedup accumulator.\n * @param attribute The (already className-matched) JSX attribute.\n * @param seen Dedup set of literals already collected.\n * @param out Ordered accumulator.\n */\nfunction collectAttributeLiterals(attribute: t.JSXAttribute, seen: Set<string>, out: string[]): void {\n const { value } = attribute\n const found: string[] = []\n if (t.isStringLiteral(value)) found.push(value.value)\n else if (t.isJSXExpressionContainer(value)) collectLiteralsFromExpression(value.expression, found)\n for (const literal of found) {\n if (seen.has(literal)) continue\n seen.add(literal)\n out.push(literal)\n }\n}\n\n/**\n * Walk the AST for every `className=` / `<prefix>ClassName=` literal so\n * the builder can pre-merge each into a per-scheme molecule. A generic\n * node walk (no scope build) keeps it cheap; only JSX attribute nodes do\n * any work.\n * @param ast Parsed Babel file.\n * @returns Distinct literal className strings, in first-seen order.\n */\nfunction collectClassNameLiterals(ast: File): readonly string[] {\n const out: string[] = []\n const seen = new Set<string>()\n const visit = (node: unknown): void => {\n if (!node || typeof node !== 'object') return\n if (Array.isArray(node)) {\n for (const child of node) visit(child)\n return\n }\n const typed = node as { type?: string; [key: string]: unknown }\n if (typeof typed.type !== 'string') return\n if (typed.type === 'JSXAttribute' && isClassNameAttribute(node as t.JSXAttribute)) {\n collectAttributeLiterals(node as t.JSXAttribute, seen, out)\n }\n for (const key in typed) {\n if (SKIP_WALK_KEYS.has(key)) continue\n visit(typed[key])\n }\n }\n visit(ast.program)\n return out\n}\n\n/**\n * Prepend side-effect imports (`import '<spec>'`) so the generated\n * per-scheme style + manifest modules load — registering this file's\n * atoms / molecules / features into the runtime registries the wrapper's\n * `resolve` reads.\n * @param ast Babel File AST to mutate in place.\n * @param specifiers Module specifiers to side-effect-import.\n */\nfunction injectSideEffectImports(ast: File, specifiers: readonly string[]): void {\n for (const specifier of specifiers) {\n ast.program.body.unshift(t.importDeclaration([], t.stringLiteral(specifier)))\n }\n}\n\n/**\n * Prepend `import 'rnwind/__generated/theme-signature'` to every\n * rnwind-transformed file. The resolver maps that specifier to the\n * user's theme CSS so Metro's dependency graph carries a real edge\n * from this JS file to the CSS. When the user edits `global.css`,\n * the CSS module's SHA1 changes, and Metro invalidates every JS file\n * holding this import — forcing them to re-transform with the new\n * theme. The `.css` branch in {@link transform} returns an empty\n * `export {}` module so the runtime cost is one extra `require()`.\n * @param ast Babel File AST to mutate in place.\n */\nfunction injectThemeSignatureImport(ast: File): void {\n const declaration = t.importDeclaration([], t.stringLiteral(THEME_SIGNATURE_MODULE))\n ast.program.body.unshift(declaration)\n}\n\n/**\n * Read the upstream transformer's `getCacheKey()` so our cache-key\n * contribution composes with — rather than replaces — whatever the\n * host framework wants to mix in.\n * @returns Upstream cache key, or `null` when no upstream exposes one.\n */\nfunction loadUpstreamCacheKey(): string | null {\n const upstream = loadUpstream() as (UpstreamTransformer & { getCacheKey?: () => string }) | null\n if (!upstream) return null\n try {\n return typeof upstream.getCacheKey === 'function' ? upstream.getCacheKey() : null\n } catch {\n return null\n }\n}\n\n/**\n * Invoke the upstream `babelTransformerPath` Metro originally had\n * configured. The path is read from `RNWIND_UPSTREAM_TRANSFORMER`,\n * which `withRnwindConfig` sets at Metro startup. When the env var is\n * unset (unit tests, standalone use), fall back to a typescript+jsx\n * parse.\n * @param args Metro's per-file args.\n * @returns Upstream transform result containing the post-babel AST.\n */\nasync function runUpstream(args: BabelTransformerArgs): Promise<BabelTransformerResult> {\n if (args.ast && !process.env[UPSTREAM_ENV]) return { ast: args.ast }\n const upstream = loadUpstream()\n if (upstream) return await Promise.resolve(upstream.transform(args))\n if (args.ast) return { ast: args.ast }\n return { ast: parseSource(args.src) }\n}\n\n/**\n * Lazily require the upstream transformer module. Cached after first\n * load so per-file overhead is one cache lookup.\n * @returns Upstream module, or null when env is unset.\n */\nfunction loadUpstream(): UpstreamTransformer | null {\n if (cachedUpstream) return cachedUpstream\n const upstreamPath = process.env[UPSTREAM_ENV]\n if (!upstreamPath || upstreamPath.length === 0) return null\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n const required = require(upstreamPath) as UpstreamTransformer | { default?: UpstreamTransformer }\n const upstream = (required as { default?: UpstreamTransformer }).default ?? (required as UpstreamTransformer)\n if (typeof upstream.transform !== 'function') return null\n cachedUpstream = upstream\n return upstream\n } catch (error) {\n // eslint-disable-next-line no-console\n if (process.env.RNWIND_DEBUG) console.error('rnwind: failed to load upstream transformer:', error)\n return null\n }\n}\n\n/**\n * Cheap guard — the file has to look JS/TS, live outside `node_modules`,\n * and mention `className=` before we spend AST cycles on it.\n *\n * Symlink awareness: monorepo workspaces (yarn / pnpm / bun workspaces)\n * symlink each package into the consumer's `node_modules/<name>`, so a\n * file from `packages/ui/src/Foo.tsx` ends up reaching the transformer\n * as `<root>/node_modules/ui/src/Foo.tsx`. The naïve `/node_modules/`\n * check would skip every workspace UI file. We `realpath` the filename\n * once and only bail when the resolved real path is ALSO under\n * node_modules — true third-party installs.\n * @param args Metro args.\n * @returns Whether the file might need the rnwind pass.\n */\nfunction isRewriteCandidate(args: BabelTransformerArgs): boolean {\n if (!/\\.(?:tsx|ts|jsx|js)$/i.test(args.filename)) return false\n // Process the file when it either:\n // - carries a `className=` / `<prefix>ClassName=` literal (case-\n // insensitive — `contentContainerClassName=` has a capital C), or\n // - spreads props (`{...rest}`) onto a host from a wrap-module, where a\n // forwarded className must still get its import wrapped (no literal\n // appears in this file). A style-less `<View/>` with neither is left\n // alone so it never pays for an unused wrapper.\n const hasClassName = /classname=/i.test(args.src)\n const isForwarder = /\\{\\s*\\.\\.\\./.test(args.src) && mentionsWrapModule(args.src)\n if (!hasClassName && !isForwarder) return false\n if (!args.filename.includes('/node_modules/')) return true\n // node_modules in path → could be a workspace symlink; resolve it.\n try {\n return !realpathSync(args.filename).includes('/node_modules/')\n } catch {\n // realpath failed (broken symlink, missing file). Fall back to skipping.\n return false\n }\n}\n\n/**\n * Cheap pre-parse check: does the source import from any configured\n * wrap-module? A quoted specifier match is enough — `rewriteWrapImports`\n * re-verifies precisely on the AST, so a false positive only costs a\n * no-op parse.\n * @param source Source text.\n * @returns True when a wrap-module specifier appears in the source.\n */\nfunction mentionsWrapModule(source: string): boolean {\n for (const moduleName of getWrapModules().keys()) {\n if (source.includes(`'${moduleName}'`) || source.includes(`\"${moduleName}\"`)) return true\n }\n return false\n}\n\n/**\n * Fallback parse when no upstream is configured AND Metro didn't hand\n * us an AST. Used by unit tests and standalone setups.\n * @param source Source text.\n * @returns Parsed Babel File.\n */\nfunction parseSource(source: string): File {\n return parse(source, { sourceType: 'module', plugins: ['typescript', 'jsx'] }) as unknown as File\n}\n\n/** Metro's babel transformer signature. */\nexport interface BabelTransformerArgs {\n filename: string\n src: string\n options: { projectRoot?: string; [key: string]: unknown }\n ast?: File\n plugins?: readonly unknown[]\n}\n\n/** Return shape Metro expects from a babel transformer. */\nexport interface BabelTransformerResult {\n ast: File\n metadata?: unknown\n}\n\n/**\n * rnwind's Metro babel transformer. Two phases per source file:\n *\n * 1. **Pre-process the source string before handing it to the upstream\n * babel pipeline.** babel-preset-expo / React's JSX transform run\n * inside the upstream and convert `<View className=\"...\"/>` into\n * `React.createElement(View, {className})`. If we walked the AST\n * AFTER the upstream, there'd be no JSX attributes left to\n * rewrite. So we parse, run our pass, regenerate code, and feed\n * THAT to the upstream as `src`.\n * 2. **Delegate to the upstream `babelTransformerPath`** (Expo's\n * default handles Flow stripping, expo-router macros, etc.).\n *\n * Skip both phases when the file isn't a JS/TS source under user\n * code, or doesn't mention `className=` — hand straight to upstream.\n * @param args Metro's per-file args.\n * @returns Mutated AST + metadata.\n */\nexport async function transform(args: BabelTransformerArgs): Promise<BabelTransformerResult> {\n // Short-circuit `.css` inputs: the theme CSS is pulled into the dep\n // graph as a sentinel (see `THEME_SIGNATURE_MODULE` in resolver.ts)\n // so Metro watches it and invalidates importers on edit, but the\n // file's CSS syntax can't go through a JS babel transformer.\n //\n // When the CSS being transformed IS the user's theme entry, we\n // piggyback on Metro's own file-watcher: Metro calls us here on\n // every CSS save; we trigger `onThemeChange` to rebuild parser +\n // rewrite scheme files with the new values. Metro's dep graph then\n // HMRs the regenerated `common.style.js` to the running app.\n //\n // Emitting the CSS content hash in the fake JS output is what makes\n // Metro propagate invalidation to downstream importers — constant\n // `export {}` bytes would never look changed and Metro would skip\n // the chain.\n if (args.filename.endsWith('.css')) {\n if (isThemeCssEntry(args.filename)) {\n try {\n await onThemeChange(projectRootOf(args))\n } catch {\n // CSS edit happened outside a configured project (e.g. tests).\n }\n }\n const themeHash = createHash('sha256').update(args.src).digest('hex').slice(0, 16)\n const stub = `export const __rnwindThemeHash = ${JSON.stringify(themeHash)};\\n`\n return { ast: parse(stub, { sourceType: 'module' }) as unknown as File }\n }\n if (!isRewriteCandidate(args)) {\n if (/\\.(?:tsx|ts|jsx|js)$/i.test(args.filename) && !args.filename.includes('/node_modules/')) {\n try {\n getRnwindState(projectRootOf(args)).builder.dropFile(args.filename)\n } catch {\n // State not configured (e.g. test). Nothing to drop.\n }\n }\n return runUpstream(args)\n }\n\n const rewrittenSource = await rewriteSource(args)\n return runUpstream({ ...args, src: rewrittenSource, ast: undefined })\n}\n\n/**\n * Metro's babel-transformer contract: a `getCacheKey()` export is\n * sampled per-file and mixed into the transform cache key. Returning\n * a string that includes the theme CSS content hash invalidates every\n * cached transform on every CSS edit — so the bundle rebuilds with\n * the new theme automatically on the next request.\n * @returns Cache-key segment that includes rnwind's current theme hash.\n */\nexport function getCacheKey(): string {\n const upstreamKey = loadUpstreamCacheKey()\n const ownKey = getRnwindCacheKey()\n return upstreamKey ? `${upstreamKey}|${ownKey}` : ownKey\n}\n\n/** Test-only — drop the cached upstream so a new env var picks up next call. */\nexport function __resetUpstreamCache(): void {\n cachedUpstream = null\n}\n"],"names":["parse","filterUnknownClassCandidates","rewriteWrapImports","getWrapModules","state","getRnwindState","STYLE_SPECIFIERS","t","THEME_SIGNATURE_MODULE","realpathSync","onThemeChange","createHash","getRnwindCacheKey"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA;AACA,MAAM,YAAY,GAAG,6BAA6B;AAElD;AACA,IAAI,cAAc,GAA+B,IAAI;AAErD,MAAM,cAAc,GAAI,QAAqD,CAAC,OAAO,IAAI,QAAQ;AAEjG;;;;;;;AAOG;AACH,SAAS,eAAe,CAAC,MAAc,EAAA;AACrC,IAAA,IAAI;QACF,OAAOA,YAAK,CAAC,MAAM,EAAE;AACnB,YAAA,UAAU,EAAE,aAAa;AACzB,YAAA,0BAA0B,EAAE,IAAI;AAChC,YAAA,2BAA2B,EAAE,IAAI;AACjC,YAAA,OAAO,EAAE,CAAC,YAAY,EAAE,KAAK,CAAC;AAC/B,SAAA,CAAoB;IACvB;AAAE,IAAA,MAAM;AACN,QAAA,IAAI;YACF,OAAOA,YAAK,CAAC,MAAM,EAAE;AACnB,gBAAA,UAAU,EAAE,aAAa;AACzB,gBAAA,0BAA0B,EAAE,IAAI;AAChC,gBAAA,2BAA2B,EAAE,IAAI;AACjC,gBAAA,OAAO,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC;AACzB,aAAA,CAAoB;QACvB;AAAE,QAAA,MAAM;AACN,YAAA,OAAO,IAAI;QACb;IACF;AACF;AAEA;;;;;;;;;;;;;AAaG;AACH,SAAS,kBAAkB,CACzB,MAAc,EACd,UAA6B,EAC7B,KAAmC,EACnC,QAAgB,EAChB,QAAA,GAAwD,EAAE,EAAA;;;;IAK1D,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;IACnC,KAAK,MAAM,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,CAAK;AAC/E,QAAA,OAAO,EAAE,GAAG,EAAEX,YAAK,CAAC,IAAI,EAAE,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAoB,EAAE;IAC1E;AACA,IAAA,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,EAAE;AAC7B,QAAA,IAAI,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,gBAAgB,CAAC,EAAE;AAC5F,YAAA,IAAI;AACF,gBAAAK,oBAAc,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC;YACrE;AAAE,YAAA,MAAM;;YAER;QACF;AACA,QAAA,OAAO,WAAW,CAAC,IAAI,CAAC;IAC1B;AAEA,IAAA,MAAM,eAAe,GAAG,MAAM,aAAa,CAAC,IAAI,CAAC;AACjD,IAAA,OAAO,WAAW,CAAC,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,SAAS,EAAE,CAAC;AACvE;AAEA;;;;;;;AAOG;SACa,WAAW,GAAA;AACzB,IAAA,MAAM,WAAW,GAAG,oBAAoB,EAAE;AAC1C,IAAA,MAAM,MAAM,GAAGO,uBAAiB,EAAE;AAClC,IAAA,OAAO,WAAW,GAAG,CAAA,EAAG,WAAW,CAAA,CAAA,EAAI,MAAM,CAAA,CAAE,GAAG,MAAM;AAC1D;AAEA;SACgB,oBAAoB,GAAA;IAClC,cAAc,GAAG,IAAI;AACvB;;;;;;"}
|
|
@@ -149,7 +149,7 @@ function withRnwindConfig(metroConfig, options) {
|
|
|
149
149
|
const cssEntry = path.isAbsolute(options.cssEntryFile) ? options.cssEntryFile : path.resolve(projectRoot, options.cssEntryFile);
|
|
150
150
|
node_fs.mkdirSync(cacheDir, { recursive: true });
|
|
151
151
|
const watchFolders = (metroConfig.watchFolders ?? []).filter((p) => typeof p === 'string' && p.length > 0);
|
|
152
|
-
state.configureRnwindState(cssEntry, cacheDir, watchFolders, options.
|
|
152
|
+
state.configureRnwindState(cssEntry, cacheDir, watchFolders, options.wrapModules);
|
|
153
153
|
// Warm the state eagerly (in the Metro master process) so oxide's
|
|
154
154
|
// Scanner walks every project source (and every monorepo
|
|
155
155
|
// watch-folder) ONCE and the manifest + scheme files hold the
|
|
@@ -182,7 +182,7 @@ function withRnwindConfig(metroConfig, options) {
|
|
|
182
182
|
if (options.dtsFile !== false) {
|
|
183
183
|
const dtsPath = options.dtsFile ?? path.resolve(projectRoot, 'rnwind-types.d.ts');
|
|
184
184
|
const schemes = discoverSchemes(cssEntry, projectRoot);
|
|
185
|
-
dts.writeDtsFile(dtsPath, schemes
|
|
185
|
+
dts.writeDtsFile(dtsPath, schemes);
|
|
186
186
|
}
|
|
187
187
|
// Watch the theme CSS. On edit, we rewrite scheme files AND touch
|
|
188
188
|
// mtime on every transformed source file so Metro invalidates them
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"with-config.cjs","sources":["../../../../src/metro/with-config.ts"],"sourcesContent":["import { existsSync, mkdirSync, utimesSync, watch as watchFile } from 'node:fs'\nimport path from 'node:path'\nimport { writeDtsFile } from './dts'\nimport { createRnwindResolver, type ResolveRequestFn } from './resolver'\nimport { configureRnwindState, getRnwindState, onThemeChange } from './state'\n\n/** Default cache directory at the project root. Visible for debugging. */\nconst DEFAULT_CACHE_DIR = '.rnwind'\n\n/**\n * Active CSS watcher — replaced (and the prior one closed) when\n * `withRnwindConfig` is called again (Metro restart, repeated init).\n * Only one watcher per process; no stacking.\n */\nlet activeCssWatcher: { cssPath: string; close: () => void } | null = null\n\n/**\n * Watch the theme CSS for edits. On change, rewrite the per-scheme\n * files with the fresh theme AND bump `mtime` on every source file\n * rnwind has transformed so far — Metro's own watcher sees those\n * mtime changes, invalidates the modules, and re-transforms them\n * against the new CSS on the next request. `getCacheKey()` alone is\n * NOT enough: Metro samples the cache key once per worker lifetime,\n * so edits during an already-running dev server don't propagate\n * without this explicit nudge.\n * @param cssPath Absolute path to the theme CSS to watch.\n * @param projectRoot Metro's project root (for `getRnwindState`).\n */\nfunction watchThemeCss(cssPath: string, projectRoot: string): void {\n if (activeCssWatcher?.cssPath === cssPath) return\n activeCssWatcher?.close()\n if (!existsSync(cssPath)) return\n let pending = false\n const watcher = watchFile(cssPath, { persistent: false }, () => {\n // Debounce: editors often emit 2-3 change events per save (atomic\n // rename dance, tmp files). Coalesce to ONE rebuild per microtask.\n if (pending) return\n pending = true\n queueMicrotask(async () => {\n pending = false\n try {\n await onThemeChange(projectRoot)\n touchRecordedFiles(projectRoot)\n } catch {\n // Invalidation is best-effort — never crash the dev server.\n }\n })\n })\n activeCssWatcher = { cssPath, close: () => watcher.close() }\n}\n\n/**\n * Bump the mtime on every file the builder has transformed. Metro's\n * file watcher keys on `mtime`, so this is what makes it invalidate\n * those modules and re-transform them.\n * @param projectRoot Metro's project root.\n */\nfunction touchRecordedFiles(projectRoot: string): void {\n const state = getRnwindState(projectRoot)\n const files = state.builder.recordedFiles()\n const now = new Date()\n for (const file of files) {\n try {\n if (existsSync(file)) utimesSync(file, now, now)\n } catch {\n // One file's stat failure shouldn't stop the others.\n }\n }\n}\n\n/**\n * Where the rnwind babel transformer lives — resolved relative to this\n * module so the path works from both the `src/` tree (tests) and the\n * built `lib/` output. Tries a few extensions because `require.resolve`\n * doesn't auto-find `.cjs` / `.mjs` from a bare specifier.\n * @returns Absolute path to the rnwind transformer module.\n */\nfunction transformerPath(): string {\n for (const candidate of ['./transformer.cjs', './transformer.mjs', './transformer.js', './transformer.ts', './transformer']) {\n try {\n return require.resolve(candidate)\n } catch {\n // try the next extension\n }\n }\n throw new Error('rnwind: could not resolve the metro transformer path')\n}\n\n/**\n * Resolve the effective cache directory, honoring a user override and\n * falling back to `<projectRoot>/.rnwind`.\n * @param projectRoot Anchor for relative paths.\n * @param override User-supplied option.\n * @returns Absolute cache directory.\n */\nfunction resolveCacheDir(projectRoot: string, override: string | undefined): string {\n if (!override || override.length === 0) return path.resolve(projectRoot, DEFAULT_CACHE_DIR)\n return path.isAbsolute(override) ? override : path.resolve(projectRoot, override)\n}\n\n/**\n * Read the theme CSS and extract `@variant <name>` blocks for the .d.ts\n * generator. Forces construction of `getRnwindState`, then reads\n * `parser.declaredSchemes` (populated synchronously at construction).\n * @param cssEntry Absolute path to theme CSS.\n * @param projectRoot\n * @returns Scheme names (empty when the theme has no variants; `'base'` is filtered).\n */\nfunction discoverSchemes(cssEntry: string, projectRoot: string): readonly string[] {\n if (!existsSync(cssEntry)) return []\n try {\n const { parser } = getRnwindState(projectRoot)\n return parser.declaredSchemes.filter((name) => name !== 'base')\n } catch {\n return []\n }\n}\n\n/** User-facing options for `withRnwindConfig`. */\nexport interface RnwindMetroOptions {\n /** Path to the theme CSS (absolute or relative to `projectRoot`). Required. */\n cssEntryFile: string\n /** Where rnwind writes the `.d.ts` file. Set `false` to disable. Defaults to `<projectRoot>/rnwind-types.d.ts`. */\n dtsFile?: string | false\n /** Optional project-root override — defaults to `metroConfig.projectRoot` then `process.cwd()`. */\n projectRoot?: string\n /** Cache directory. Absolute, or relative to `projectRoot`. Default: `.rnwind` at project root. */\n cacheDir?: string\n /**\n * Extra JSX prop-name prefixes that rnwind should rewrite. Each\n * prefix `P` turns `<Tag PClassName=\"…\">` into `<Tag\n * PStyle={lookupCss(…)}>`. The built-in `'contentContainer'` prefix\n * is always on (covers ScrollView / FlatList / SectionList); user\n * entries merge on top.\n */\n classNamePrefixes?: readonly string[]\n /**\n * Extra module specifiers whose JSX exports rnwind should treat as\n * \"host components\" — i.e. tags whose `className=\"…\"` attribute is\n * rewritten to `style={lookupCss(…)}` at build time (zero runtime\n * cost). Merged with the built-in defaults: `react-native`,\n * `react-native-reanimated`, `react-native-svg`,\n * `react-native-gesture-handler`, `expo-linear-gradient`, `expo-image`.\n *\n * Anything NOT marked as a host has its `className` left untouched —\n * the importing component receives the raw string and decides what\n * to do with it. Use this option to opt your design-system / UI\n * primitive packages into the zero-runtime path.\n */\n hostSources?: readonly string[]\n /**\n * Extra JSX tag names (verbatim — may include `.` for member access\n * like `'Animated.View'`) rnwind should treat as host components,\n * regardless of where they're imported from. Useful for one-off\n * escape-hatches: `import { View as MyBox } from 'react-native'`\n * doesn't change the local name → `'MyBox'` here picks it up.\n */\n hostComponents?: readonly string[]\n}\n\n/** Shape we mutate on Metro's config. Loose so we don't pin Metro's internal types. */\nexport interface MetroConfigLike {\n projectRoot?: string\n watchFolders?: string[]\n transformer?: {\n babelTransformerPath?: string\n [key: string]: unknown\n }\n resolver?: {\n resolveRequest?: ResolveRequestFn | null\n [key: string]: unknown\n }\n [key: string]: unknown\n}\n\n/**\n * Wrap a Metro config with rnwind's pipeline:\n * - Install the rnwind babel transformer.\n * - Chain a `resolveRequest` hook that serves\n * `rnwind/__generated/schemes` from `<cacheDir>/schemes.js`.\n * - Write the `.d.ts` so TypeScript accepts `className=` on RN components.\n * - Publish the theme CSS path + cache dir via env so Metro workers\n * can rebuild their local state.\n * - Ensure the cache dir is a watched folder Metro's haste-map indexes.\n *\n * Theme-edit hot reload happens implicitly: every transformed file\n * imports `rnwind/__generated/schemes`, and that module eager-imports\n * `common.style.js`. When the theme changes, the per-scheme files\n * regenerate with new bytes; Metro's content SHA1 dedup detects the\n * change and invalidates every importer automatically.\n * `getCacheKey()` on the transformer covers the per-file transform\n * cache. No file watcher / source-padding hack needed — the dep graph\n * carries the signal.\n * @param metroConfig Config from `getDefaultConfig(__dirname)` or equivalent.\n * @param options rnwind options.\n * @returns The same config, mutated.\n */\nexport function withRnwindConfig<C extends MetroConfigLike>(metroConfig: C, options: RnwindMetroOptions): C {\n const projectRoot = options.projectRoot ?? metroConfig.projectRoot ?? process.cwd()\n const cacheDir = resolveCacheDir(projectRoot, options.cacheDir)\n const cssEntry = path.isAbsolute(options.cssEntryFile) ? options.cssEntryFile : path.resolve(projectRoot, options.cssEntryFile)\n\n mkdirSync(cacheDir, { recursive: true })\n const watchFolders = (metroConfig.watchFolders ?? []).filter((p) => typeof p === 'string' && p.length > 0)\n configureRnwindState(cssEntry, cacheDir, watchFolders, options.classNamePrefixes, options.hostSources, options.hostComponents)\n\n // Warm the state eagerly (in the Metro master process) so oxide's\n // Scanner walks every project source (and every monorepo\n // watch-folder) ONCE and the manifest + scheme files hold the\n // complete union before Metro's resolver tries to SHA1 them on the\n // first transform. Each worker lazy-repeats this scan on its first\n // transform to converge on identical state.\n try {\n void getRnwindState(projectRoot).builder.ensureFilesExist()\n } catch {\n // Any init error surfaces again at the first transform; don't crash Metro boot.\n }\n\n // Install transformer + resolver. Capture the existing\n // babelTransformerPath BEFORE we override it — our worker chains to\n // it (env-passed) so Flow / expo-router / babel-preset-expo etc. all\n // continue to run.\n const existingTransformerPath = metroConfig.transformer?.babelTransformerPath\n if (typeof existingTransformerPath === 'string' && existingTransformerPath.length > 0) {\n process.env.RNWIND_UPSTREAM_TRANSFORMER = existingTransformerPath\n }\n const upstream = metroConfig.resolver?.resolveRequest ?? null\n metroConfig.transformer = { ...metroConfig.transformer, babelTransformerPath: transformerPath() }\n metroConfig.resolver = { ...metroConfig.resolver, resolveRequest: createRnwindResolver(upstream) }\n\n // Metro's haste-map indexes `watchFolders` at startup. Adding the\n // cache dir guarantees scheme style files + manifest get SHA1'd\n // without a \"Failed to get the SHA-1\" race when the first transform\n // writes them.\n const existingWatch = metroConfig.watchFolders ?? []\n metroConfig.watchFolders = existingWatch.includes(cacheDir) ? existingWatch : [...existingWatch, cacheDir]\n\n if (options.dtsFile !== false) {\n const dtsPath = options.dtsFile ?? path.resolve(projectRoot, 'rnwind-types.d.ts')\n const schemes = discoverSchemes(cssEntry, projectRoot)\n writeDtsFile(dtsPath, schemes, options.classNamePrefixes)\n }\n\n // Watch the theme CSS. On edit, we rewrite scheme files AND touch\n // mtime on every transformed source file so Metro invalidates them\n // and re-transforms — the only reliable way to propagate theme\n // changes to an already-running dev server.\n watchThemeCss(cssEntry, projectRoot)\n\n return metroConfig\n}\n"],"names":["existsSync","watchFile","onThemeChange","state","getRnwindState","utimesSync","mkdirSync","configureRnwindState","createRnwindResolver","writeDtsFile"],"mappings":";;;;;;;;AAMA;AACA,MAAM,iBAAiB,GAAG,SAAS;AAEnC;;;;AAIG;AACH,IAAI,gBAAgB,GAAkD,IAAI;AAE1E;;;;;;;;;;;AAWG;AACH,SAAS,aAAa,CAAC,OAAe,EAAE,WAAmB,EAAA;AACzD,IAAA,IAAI,gBAAgB,EAAE,OAAO,KAAK,OAAO;QAAE;IAC3C,gBAAgB,EAAE,KAAK,EAAE;AACzB,IAAA,IAAI,CAACA,kBAAU,CAAC,OAAO,CAAC;QAAE;IAC1B,IAAI,OAAO,GAAG,KAAK;AACnB,IAAA,MAAM,OAAO,GAAGC,aAAS,CAAC,OAAO,EAAE,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE,MAAK;;;AAG7D,QAAA,IAAI,OAAO;YAAE;QACb,OAAO,GAAG,IAAI;QACd,cAAc,CAAC,YAAW;YACxB,OAAO,GAAG,KAAK;AACf,YAAA,IAAI;AACF,gBAAA,MAAMC,mBAAa,CAAC,WAAW,CAAC;gBAChC,kBAAkB,CAAC,WAAW,CAAC;YACjC;AAAE,YAAA,MAAM;;YAER;AACF,QAAA,CAAC,CAAC;AACJ,IAAA,CAAC,CAAC;AACF,IAAA,gBAAgB,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,OAAO,CAAC,KAAK,EAAE,EAAE;AAC9D;AAEA;;;;;AAKG;AACH,SAAS,kBAAkB,CAAC,WAAmB,EAAA;AAC7C,IAAA,MAAMC,OAAK,GAAGC,oBAAc,CAAC,WAAW,CAAC;IACzC,MAAM,KAAK,GAAGD,OAAK,CAAC,OAAO,CAAC,aAAa,EAAE;AAC3C,IAAA,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE;AACtB,IAAA,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;AACxB,QAAA,IAAI;YACF,IAAIH,k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AoB,EAAE,eAAe,EAAE,EAAE;AACjG,IAAA,WAAW,CAAC,QAAQ,GAAG,EAAE,GAAG,WAAW,CAAC,QAAQ,EAAE,cAAc,EAAEI,6BAAoB,CAAC,QAAQ,CAAC,EAAE;;;;;AAMlG,IAAA,MAAM,aAAa,GAAG,WAAW,CAAC,YAAY,IAAI,EAAE;IACpD,WAAW,CAAC,YAAY,GAAG,aAAa,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,aAAa,GAAG,CAAC,GAAG,aAAa,EAAE,QAAQ,CAAC;AAE1G,IAAA,IAAI,OAAO,CAAC,OAAO,KAAK,KAAK,EAAE;AAC7B,QAAA,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,mBAAmB,CAAC;QACjF,MAAM,OAAO,GAAG,eAAe,CAAC,QAAQ,EAAE,WAAW,CAAC;QACtDC,gBAAY,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,iBAAiB,CAAC;IAC3D;;;;;AAMA,IAAA,aAAa,CAAC,QAAQ,EAAE,WAAW,CAAC;AAEpC,IAAA,OAAO,WAAW;AACpB;;;;"}
|
|
1
|
+
{"version":3,"file":"with-config.cjs","sources":["../../../../src/metro/with-config.ts"],"sourcesContent":["import { existsSync, mkdirSync, utimesSync, watch as watchFile } from 'node:fs'\nimport path from 'node:path'\nimport { writeDtsFile } from './dts'\nimport { createRnwindResolver, type ResolveRequestFn } from './resolver'\nimport { configureRnwindState, getRnwindState, onThemeChange } from './state'\n\n/** Default cache directory at the project root. Visible for debugging. */\nconst DEFAULT_CACHE_DIR = '.rnwind'\n\n/**\n * Active CSS watcher — replaced (and the prior one closed) when\n * `withRnwindConfig` is called again (Metro restart, repeated init).\n * Only one watcher per process; no stacking.\n */\nlet activeCssWatcher: { cssPath: string; close: () => void } | null = null\n\n/**\n * Watch the theme CSS for edits. On change, rewrite the per-scheme\n * files with the fresh theme AND bump `mtime` on every source file\n * rnwind has transformed so far — Metro's own watcher sees those\n * mtime changes, invalidates the modules, and re-transforms them\n * against the new CSS on the next request. `getCacheKey()` alone is\n * NOT enough: Metro samples the cache key once per worker lifetime,\n * so edits during an already-running dev server don't propagate\n * without this explicit nudge.\n * @param cssPath Absolute path to the theme CSS to watch.\n * @param projectRoot Metro's project root (for `getRnwindState`).\n */\nfunction watchThemeCss(cssPath: string, projectRoot: string): void {\n if (activeCssWatcher?.cssPath === cssPath) return\n activeCssWatcher?.close()\n if (!existsSync(cssPath)) return\n let pending = false\n const watcher = watchFile(cssPath, { persistent: false }, () => {\n // Debounce: editors often emit 2-3 change events per save (atomic\n // rename dance, tmp files). Coalesce to ONE rebuild per microtask.\n if (pending) return\n pending = true\n queueMicrotask(async () => {\n pending = false\n try {\n await onThemeChange(projectRoot)\n touchRecordedFiles(projectRoot)\n } catch {\n // Invalidation is best-effort — never crash the dev server.\n }\n })\n })\n activeCssWatcher = { cssPath, close: () => watcher.close() }\n}\n\n/**\n * Bump the mtime on every file the builder has transformed. Metro's\n * file watcher keys on `mtime`, so this is what makes it invalidate\n * those modules and re-transform them.\n * @param projectRoot Metro's project root.\n */\nfunction touchRecordedFiles(projectRoot: string): void {\n const state = getRnwindState(projectRoot)\n const files = state.builder.recordedFiles()\n const now = new Date()\n for (const file of files) {\n try {\n if (existsSync(file)) utimesSync(file, now, now)\n } catch {\n // One file's stat failure shouldn't stop the others.\n }\n }\n}\n\n/**\n * Where the rnwind babel transformer lives — resolved relative to this\n * module so the path works from both the `src/` tree (tests) and the\n * built `lib/` output. Tries a few extensions because `require.resolve`\n * doesn't auto-find `.cjs` / `.mjs` from a bare specifier.\n * @returns Absolute path to the rnwind transformer module.\n */\nfunction transformerPath(): string {\n for (const candidate of ['./transformer.cjs', './transformer.mjs', './transformer.js', './transformer.ts', './transformer']) {\n try {\n return require.resolve(candidate)\n } catch {\n // try the next extension\n }\n }\n throw new Error('rnwind: could not resolve the metro transformer path')\n}\n\n/**\n * Resolve the effective cache directory, honoring a user override and\n * falling back to `<projectRoot>/.rnwind`.\n * @param projectRoot Anchor for relative paths.\n * @param override User-supplied option.\n * @returns Absolute cache directory.\n */\nfunction resolveCacheDir(projectRoot: string, override: string | undefined): string {\n if (!override || override.length === 0) return path.resolve(projectRoot, DEFAULT_CACHE_DIR)\n return path.isAbsolute(override) ? override : path.resolve(projectRoot, override)\n}\n\n/**\n * Read the theme CSS and extract `@variant <name>` blocks for the .d.ts\n * generator. Forces construction of `getRnwindState`, then reads\n * `parser.declaredSchemes` (populated synchronously at construction).\n * @param cssEntry Absolute path to theme CSS.\n * @param projectRoot\n * @returns Scheme names (empty when the theme has no variants; `'base'` is filtered).\n */\nfunction discoverSchemes(cssEntry: string, projectRoot: string): readonly string[] {\n if (!existsSync(cssEntry)) return []\n try {\n const { parser } = getRnwindState(projectRoot)\n return parser.declaredSchemes.filter((name) => name !== 'base')\n } catch {\n return []\n }\n}\n\n/** User-facing options for `withRnwindConfig`. */\nexport interface RnwindMetroOptions {\n /** Path to the theme CSS (absolute or relative to `projectRoot`). Required. */\n cssEntryFile: string\n /** Where rnwind writes the `.d.ts` file. Set `false` to disable. Defaults to `<projectRoot>/rnwind-types.d.ts`. */\n dtsFile?: string | false\n /** Optional project-root override — defaults to `metroConfig.projectRoot` then `process.cwd()`. */\n projectRoot?: string\n /** Cache directory. Absolute, or relative to `projectRoot`. Default: `.rnwind` at project root. */\n cacheDir?: string\n /**\n * Extra module specifiers whose component exports rnwind should\n * auto-wrap at import sites — `import { View } from 'react-native'`\n * becomes `const View = wrap(_rnw0)` so `<View className=\"…\">` resolves\n * styles at runtime. Merged with the built-in defaults: `react-native`,\n * `react-native-reanimated`, `react-native-svg`,\n * `react-native-gesture-handler`, `react-native-safe-area-context`,\n * `expo-linear-gradient`, `expo-image`, and more.\n *\n * A module NOT in this list keeps its raw imports — the importing\n * component receives `className` as a plain prop and can resolve it\n * via `useCss` / `wrap` itself. Use this to opt your design-system /\n * UI primitive packages into the auto-wrap path.\n */\n wrapModules?: readonly string[]\n}\n\n/** Shape we mutate on Metro's config. Loose so we don't pin Metro's internal types. */\nexport interface MetroConfigLike {\n projectRoot?: string\n watchFolders?: string[]\n transformer?: {\n babelTransformerPath?: string\n [key: string]: unknown\n }\n resolver?: {\n resolveRequest?: ResolveRequestFn | null\n [key: string]: unknown\n }\n [key: string]: unknown\n}\n\n/**\n * Wrap a Metro config with rnwind's pipeline:\n * - Install the rnwind babel transformer.\n * - Chain a `resolveRequest` hook that serves\n * `rnwind/__generated/schemes` from `<cacheDir>/schemes.js`.\n * - Write the `.d.ts` so TypeScript accepts `className=` on RN components.\n * - Publish the theme CSS path + cache dir via env so Metro workers\n * can rebuild their local state.\n * - Ensure the cache dir is a watched folder Metro's haste-map indexes.\n *\n * Theme-edit hot reload happens implicitly: every transformed file\n * imports `rnwind/__generated/schemes`, and that module eager-imports\n * `common.style.js`. When the theme changes, the per-scheme files\n * regenerate with new bytes; Metro's content SHA1 dedup detects the\n * change and invalidates every importer automatically.\n * `getCacheKey()` on the transformer covers the per-file transform\n * cache. No file watcher / source-padding hack needed — the dep graph\n * carries the signal.\n * @param metroConfig Config from `getDefaultConfig(__dirname)` or equivalent.\n * @param options rnwind options.\n * @returns The same config, mutated.\n */\nexport function withRnwindConfig<C extends MetroConfigLike>(metroConfig: C, options: RnwindMetroOptions): C {\n const projectRoot = options.projectRoot ?? metroConfig.projectRoot ?? process.cwd()\n const cacheDir = resolveCacheDir(projectRoot, options.cacheDir)\n const cssEntry = path.isAbsolute(options.cssEntryFile) ? options.cssEntryFile : path.resolve(projectRoot, options.cssEntryFile)\n\n mkdirSync(cacheDir, { recursive: true })\n const watchFolders = (metroConfig.watchFolders ?? []).filter((p) => typeof p === 'string' && p.length > 0)\n configureRnwindState(cssEntry, cacheDir, watchFolders, options.wrapModules)\n\n // Warm the state eagerly (in the Metro master process) so oxide's\n // Scanner walks every project source (and every monorepo\n // watch-folder) ONCE and the manifest + scheme files hold the\n // complete union before Metro's resolver tries to SHA1 them on the\n // first transform. Each worker lazy-repeats this scan on its first\n // transform to converge on identical state.\n try {\n void getRnwindState(projectRoot).builder.ensureFilesExist()\n } catch {\n // Any init error surfaces again at the first transform; don't crash Metro boot.\n }\n\n // Install transformer + resolver. Capture the existing\n // babelTransformerPath BEFORE we override it — our worker chains to\n // it (env-passed) so Flow / expo-router / babel-preset-expo etc. all\n // continue to run.\n const existingTransformerPath = metroConfig.transformer?.babelTransformerPath\n if (typeof existingTransformerPath === 'string' && existingTransformerPath.length > 0) {\n process.env.RNWIND_UPSTREAM_TRANSFORMER = existingTransformerPath\n }\n const upstream = metroConfig.resolver?.resolveRequest ?? null\n metroConfig.transformer = { ...metroConfig.transformer, babelTransformerPath: transformerPath() }\n metroConfig.resolver = { ...metroConfig.resolver, resolveRequest: createRnwindResolver(upstream) }\n\n // Metro's haste-map indexes `watchFolders` at startup. Adding the\n // cache dir guarantees scheme style files + manifest get SHA1'd\n // without a \"Failed to get the SHA-1\" race when the first transform\n // writes them.\n const existingWatch = metroConfig.watchFolders ?? []\n metroConfig.watchFolders = existingWatch.includes(cacheDir) ? existingWatch : [...existingWatch, cacheDir]\n\n if (options.dtsFile !== false) {\n const dtsPath = options.dtsFile ?? path.resolve(projectRoot, 'rnwind-types.d.ts')\n const schemes = discoverSchemes(cssEntry, projectRoot)\n writeDtsFile(dtsPath, schemes)\n }\n\n // Watch the theme CSS. On edit, we rewrite scheme files AND touch\n // mtime on every transformed source file so Metro invalidates them\n // and re-transforms — the only reliable way to propagate theme\n // changes to an already-running dev server.\n watchThemeCss(cssEntry, projectRoot)\n\n return metroConfig\n}\n"],"names":["existsSync","watchFile","onThemeChange","state","getRnwindState","utimesSync","mkdirSync","configureRnwindState","createRnwindResolver","writeDtsFile"],"mappings":";;;;;;;;AAMA;AACA,MAAM,iBAAiB,GAAG,SAAS;AAEnC;;;;AAIG;AACH,IAAI,gBAAgB,GAAkD,IAAI;AAE1E;;;;;;;;;;;AAWG;AACH,SAAS,aAAa,CAAC,OAAe,EAA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,EAAE,QAAQ,CAAC;AAE1G,IAAA,IAAI,OAAO,CAAC,OAAO,KAAK,KAAK,EAAE;AAC7B,QAAA,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,mBAAmB,CAAC;QACjF,MAAM,OAAO,GAAG,eAAe,CAAC,QAAQ,EAAE,WAAW,CAAC;AACtD,QAAAC,gBAAY,CAAC,OAAO,EAAE,OAAO,CAAC;IAChC;;;;;AAMA,IAAA,aAAa,CAAC,QAAQ,EAAE,WAAW,CAAC;AAEpC,IAAA,OAAO,WAAW;AACpB;;;;"}
|
|
@@ -10,35 +10,20 @@ export interface RnwindMetroOptions {
|
|
|
10
10
|
/** Cache directory. Absolute, or relative to `projectRoot`. Default: `.rnwind` at project root. */
|
|
11
11
|
cacheDir?: string;
|
|
12
12
|
/**
|
|
13
|
-
* Extra
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* entries merge on top.
|
|
18
|
-
*/
|
|
19
|
-
classNamePrefixes?: readonly string[];
|
|
20
|
-
/**
|
|
21
|
-
* Extra module specifiers whose JSX exports rnwind should treat as
|
|
22
|
-
* "host components" — i.e. tags whose `className="…"` attribute is
|
|
23
|
-
* rewritten to `style={lookupCss(…)}` at build time (zero runtime
|
|
24
|
-
* cost). Merged with the built-in defaults: `react-native`,
|
|
13
|
+
* Extra module specifiers whose component exports rnwind should
|
|
14
|
+
* auto-wrap at import sites — `import { View } from 'react-native'`
|
|
15
|
+
* becomes `const View = wrap(_rnw0)` so `<View className="…">` resolves
|
|
16
|
+
* styles at runtime. Merged with the built-in defaults: `react-native`,
|
|
25
17
|
* `react-native-reanimated`, `react-native-svg`,
|
|
26
|
-
* `react-native-gesture-handler`, `
|
|
18
|
+
* `react-native-gesture-handler`, `react-native-safe-area-context`,
|
|
19
|
+
* `expo-linear-gradient`, `expo-image`, and more.
|
|
27
20
|
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
* primitive packages into the
|
|
32
|
-
*/
|
|
33
|
-
hostSources?: readonly string[];
|
|
34
|
-
/**
|
|
35
|
-
* Extra JSX tag names (verbatim — may include `.` for member access
|
|
36
|
-
* like `'Animated.View'`) rnwind should treat as host components,
|
|
37
|
-
* regardless of where they're imported from. Useful for one-off
|
|
38
|
-
* escape-hatches: `import { View as MyBox } from 'react-native'`
|
|
39
|
-
* doesn't change the local name → `'MyBox'` here picks it up.
|
|
21
|
+
* A module NOT in this list keeps its raw imports — the importing
|
|
22
|
+
* component receives `className` as a plain prop and can resolve it
|
|
23
|
+
* via `useCss` / `wrap` itself. Use this to opt your design-system /
|
|
24
|
+
* UI primitive packages into the auto-wrap path.
|
|
40
25
|
*/
|
|
41
|
-
|
|
26
|
+
wrapModules?: readonly string[];
|
|
42
27
|
}
|
|
43
28
|
/** Shape we mutate on Metro's config. Loose so we don't pin Metro's internal types. */
|
|
44
29
|
export interface MetroConfigLike {
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var t = require('@babel/types');
|
|
4
|
+
|
|
5
|
+
function _interopNamespaceDefault(e) {
|
|
6
|
+
var n = Object.create(null);
|
|
7
|
+
if (e) {
|
|
8
|
+
Object.keys(e).forEach(function (k) {
|
|
9
|
+
if (k !== 'default') {
|
|
10
|
+
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
11
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
12
|
+
enumerable: true,
|
|
13
|
+
get: function () { return e[k]; }
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
n.default = e;
|
|
19
|
+
return Object.freeze(n);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
var t__namespace = /*#__PURE__*/_interopNamespaceDefault(t);
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Build-time import rewrite. For every `import { View } from
|
|
26
|
+
* 'react-native'` (and the other configured modules) it aliases the
|
|
27
|
+
* original export and binds a `wrap()`-ed component in its place:
|
|
28
|
+
*
|
|
29
|
+
* ```
|
|
30
|
+
* import { View, StyleSheet } from 'react-native'
|
|
31
|
+
* ⇩
|
|
32
|
+
* import { View as _rnw0, StyleSheet } from 'react-native'
|
|
33
|
+
* import { wrap as _rnwWrap } from 'rnwind'
|
|
34
|
+
* const View = _rnwWrap(_rnw0)
|
|
35
|
+
* ```
|
|
36
|
+
*
|
|
37
|
+
* Now `<View className="…">` resolves className → style at render via the
|
|
38
|
+
* wrapper — no matter how className arrived (literal, `{...rest}` spread,
|
|
39
|
+
* forwarded through custom layers). Non-component exports (`StyleSheet`)
|
|
40
|
+
* are left untouched.
|
|
41
|
+
*/
|
|
42
|
+
/** Local binding the injected `wrap` import is aliased to. */
|
|
43
|
+
const WRAP_LOCAL = '_rnwWrap';
|
|
44
|
+
/** Local binding the injected `wrapNamespace` import is aliased to. */
|
|
45
|
+
const WRAP_NS_LOCAL = '_rnwWrapNs';
|
|
46
|
+
/** Module the wrapper is imported from. */
|
|
47
|
+
const RUNTIME_MODULE = 'rnwind';
|
|
48
|
+
/**
|
|
49
|
+
* Wrap-modules whose DEFAULT export is a component NAMESPACE accessed via
|
|
50
|
+
* member expressions (`Animated.View`), not a single component. Their
|
|
51
|
+
* default import is bound through `wrapNamespace` (a Proxy that wraps each
|
|
52
|
+
* accessed component member) instead of `wrap`. Every other default import
|
|
53
|
+
* is treated as a plain component.
|
|
54
|
+
*/
|
|
55
|
+
const NAMESPACE_DEFAULT_MODULES = new Set(['react-native-reanimated']);
|
|
56
|
+
/**
|
|
57
|
+
* react-native mixes styleable components with utilities (`StyleSheet`,
|
|
58
|
+
* `Platform`, …). Only these named exports are wrapped; everything else
|
|
59
|
+
* passes through. Other ecosystem modules export components only and use
|
|
60
|
+
* the `'all'` policy instead.
|
|
61
|
+
*/
|
|
62
|
+
const REACT_NATIVE_COMPONENTS = new Set([
|
|
63
|
+
'View',
|
|
64
|
+
'Text',
|
|
65
|
+
'TextInput',
|
|
66
|
+
'Pressable',
|
|
67
|
+
'ScrollView',
|
|
68
|
+
'Image',
|
|
69
|
+
'ImageBackground',
|
|
70
|
+
'FlatList',
|
|
71
|
+
'SectionList',
|
|
72
|
+
'VirtualizedList',
|
|
73
|
+
'KeyboardAvoidingView',
|
|
74
|
+
'SafeAreaView',
|
|
75
|
+
'Modal',
|
|
76
|
+
'Switch',
|
|
77
|
+
'RefreshControl',
|
|
78
|
+
'ActivityIndicator',
|
|
79
|
+
'TouchableOpacity',
|
|
80
|
+
'TouchableHighlight',
|
|
81
|
+
'TouchableWithoutFeedback',
|
|
82
|
+
'TouchableNativeFeedback',
|
|
83
|
+
'Button',
|
|
84
|
+
'StatusBar',
|
|
85
|
+
]);
|
|
86
|
+
/**
|
|
87
|
+
* Named exports that LOOK like components (PascalCase) under an `'all'`
|
|
88
|
+
* policy but aren't — React contexts, gesture-handler enums/namespaces,
|
|
89
|
+
* etc. Wrapping these would turn `Gesture.Pan()` / `State.ACTIVE` /
|
|
90
|
+
* `<XContext.Provider>` into a `wrap()`-ed component and break them.
|
|
91
|
+
* Names ending in `Context` are excluded separately.
|
|
92
|
+
*/
|
|
93
|
+
const NON_COMPONENT_EXPORTS = new Set([
|
|
94
|
+
'Gesture',
|
|
95
|
+
'GestureObjects',
|
|
96
|
+
'State',
|
|
97
|
+
'Directions',
|
|
98
|
+
'Extrapolation',
|
|
99
|
+
'Extrapolate',
|
|
100
|
+
'Easing',
|
|
101
|
+
'ReduceMotion',
|
|
102
|
+
'KeyframeRegistry',
|
|
103
|
+
]);
|
|
104
|
+
/**
|
|
105
|
+
* Default module → wrap policy. react-native is allow-listed (mixed
|
|
106
|
+
* exports); the rest are component-only packages → `'all'`. Only modules
|
|
107
|
+
* the project has installed are ever hit (you can't import from a missing
|
|
108
|
+
* package), so listing optional peers is free.
|
|
109
|
+
*/
|
|
110
|
+
const DEFAULT_WRAP_MODULES = new Map([
|
|
111
|
+
['react-native', REACT_NATIVE_COMPONENTS],
|
|
112
|
+
['react-native-reanimated', 'all'],
|
|
113
|
+
['react-native-svg', 'all'],
|
|
114
|
+
['react-native-gesture-handler', 'all'],
|
|
115
|
+
['react-native-safe-area-context', 'all'],
|
|
116
|
+
['expo-linear-gradient', 'all'],
|
|
117
|
+
['expo-image', 'all'],
|
|
118
|
+
['expo-blur', 'all'],
|
|
119
|
+
['expo-symbols', 'all'],
|
|
120
|
+
['@shopify/flash-list', 'all'],
|
|
121
|
+
['@shopify/react-native-skia', 'all'],
|
|
122
|
+
['lottie-react-native', 'all'],
|
|
123
|
+
]);
|
|
124
|
+
/**
|
|
125
|
+
* Whether a named import from a wrap-module should be wrapped.
|
|
126
|
+
*
|
|
127
|
+
* Explicit allow-lists (react-native) match by exact name. The `'all'`
|
|
128
|
+
* policy wraps only component-style names — PascalCase, not a React
|
|
129
|
+
* context (`*Context`), and not a known non-component export. This is
|
|
130
|
+
* what stops `useSafeAreaInsets` (a hook) from being wrapped into a
|
|
131
|
+
* component and crashing when called.
|
|
132
|
+
* @param policy The module's wrap policy.
|
|
133
|
+
* @param importedName The exported name being imported.
|
|
134
|
+
* @returns True when the name is a component to wrap.
|
|
135
|
+
*/
|
|
136
|
+
function shouldWrap(policy, importedName) {
|
|
137
|
+
if (policy !== 'all')
|
|
138
|
+
return policy.has(importedName);
|
|
139
|
+
if (!/^[A-Z]/.test(importedName))
|
|
140
|
+
return false;
|
|
141
|
+
if (importedName.endsWith('Context'))
|
|
142
|
+
return false;
|
|
143
|
+
return !NON_COMPONENT_EXPORTS.has(importedName);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Merge user-supplied wrap modules onto the defaults — a bare module name
|
|
147
|
+
* adopts the `'all'` policy.
|
|
148
|
+
* @param extra User module specifiers (or undefined).
|
|
149
|
+
* @returns Effective module → policy map.
|
|
150
|
+
*/
|
|
151
|
+
function buildWrapModules(extra) {
|
|
152
|
+
if (!extra || extra.length === 0)
|
|
153
|
+
return DEFAULT_WRAP_MODULES;
|
|
154
|
+
const merged = new Map(DEFAULT_WRAP_MODULES);
|
|
155
|
+
for (const moduleName of extra)
|
|
156
|
+
if (!merged.has(moduleName))
|
|
157
|
+
merged.set(moduleName, 'all');
|
|
158
|
+
return merged;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* The `imported` name of an import specifier (`import { a as b }` → `'a'`).
|
|
162
|
+
* @param specifier Named import specifier.
|
|
163
|
+
* @returns The exported name.
|
|
164
|
+
*/
|
|
165
|
+
function importedNameOf(specifier) {
|
|
166
|
+
return t__namespace.isIdentifier(specifier.imported) ? specifier.imported.name : specifier.imported.value;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Build `const Local = <wrapper>(alias)` and rebind the specifier's local
|
|
170
|
+
* to `alias` in place.
|
|
171
|
+
* @param specifier The import specifier to rebind.
|
|
172
|
+
* @param alias The `_rnwN` alias to bind the original import to.
|
|
173
|
+
* @param wrapper The runtime helper local (`_rnwWrap` / `_rnwWrapNs`).
|
|
174
|
+
* @returns The wrap declaration.
|
|
175
|
+
*/
|
|
176
|
+
function makeWrapDecl(specifier, alias, wrapper) {
|
|
177
|
+
const { name: localName } = specifier.local;
|
|
178
|
+
specifier.local = t__namespace.identifier(alias);
|
|
179
|
+
return t__namespace.variableDeclaration('const', [
|
|
180
|
+
t__namespace.variableDeclarator(t__namespace.identifier(localName), t__namespace.callExpression(t__namespace.identifier(wrapper), [t__namespace.identifier(alias)])),
|
|
181
|
+
]);
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Rewrite one import declaration's wrappable specifiers, aliasing each to
|
|
185
|
+
* `_rnw<N>` in place:
|
|
186
|
+
* - named (`{ View }`) → `const View = wrap(_rnwN)` (per policy),
|
|
187
|
+
* - namespace (`* as Animated`) → `const Animated = wrapNamespace(_rnwN)`,
|
|
188
|
+
* - default → `wrapNamespace` for {@link NAMESPACE_DEFAULT_MODULES}
|
|
189
|
+
* (reanimated's `Animated`), else `wrap` (a plain default component).
|
|
190
|
+
* @param node Import declaration to inspect.
|
|
191
|
+
* @param policy The module's wrap policy.
|
|
192
|
+
* @param counter Next alias index (caller-threaded for uniqueness).
|
|
193
|
+
* @returns New wrap declarations, advanced counter, and whether any
|
|
194
|
+
* binding used `wrapNamespace`.
|
|
195
|
+
*/
|
|
196
|
+
function wrapSpecifiers(node, policy, counter) {
|
|
197
|
+
const decls = [];
|
|
198
|
+
const moduleName = node.source.value;
|
|
199
|
+
let next = counter;
|
|
200
|
+
let usesNamespace = false;
|
|
201
|
+
for (const specifier of node.specifiers) {
|
|
202
|
+
if (t__namespace.isImportSpecifier(specifier)) {
|
|
203
|
+
if (!shouldWrap(policy, importedNameOf(specifier)))
|
|
204
|
+
continue;
|
|
205
|
+
decls.push(makeWrapDecl(specifier, `_rnw${next}`, WRAP_LOCAL));
|
|
206
|
+
next += 1;
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
const isNamespace = t__namespace.isImportNamespaceSpecifier(specifier) || NAMESPACE_DEFAULT_MODULES.has(moduleName);
|
|
210
|
+
const wrapper = isNamespace ? WRAP_NS_LOCAL : WRAP_LOCAL;
|
|
211
|
+
decls.push(makeWrapDecl(specifier, `_rnw${next}`, wrapper));
|
|
212
|
+
next += 1;
|
|
213
|
+
if (isNamespace)
|
|
214
|
+
usesNamespace = true;
|
|
215
|
+
}
|
|
216
|
+
return { decls, counter: next, usesNamespace };
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Insert the `wrap` import at the top and the `const X = wrap(_rnwN)`
|
|
220
|
+
* declarations AFTER every import. The consts reference the aliased
|
|
221
|
+
* binding `_rnwN`, and in Metro's real transform (CommonJS interop + the
|
|
222
|
+
* reanimated worklets plugin) a const placed above its source import
|
|
223
|
+
* evaluates before the binding initialises → `ReferenceError: _rnw0
|
|
224
|
+
* doesn't exist`. ESM-only hoisting would mask this; the bundle does not.
|
|
225
|
+
* @param ast Parsed Babel file (mutated).
|
|
226
|
+
* @param wrapDecls The wrap declarations to place.
|
|
227
|
+
* @param usesNamespace Whether any binding used `wrapNamespace`.
|
|
228
|
+
*/
|
|
229
|
+
function placeWrapDecls(ast, wrapDecls, usesNamespace) {
|
|
230
|
+
const specifiers = [t__namespace.importSpecifier(t__namespace.identifier(WRAP_LOCAL), t__namespace.identifier('wrap'))];
|
|
231
|
+
if (usesNamespace)
|
|
232
|
+
specifiers.push(t__namespace.importSpecifier(t__namespace.identifier(WRAP_NS_LOCAL), t__namespace.identifier('wrapNamespace')));
|
|
233
|
+
ast.program.body.unshift(t__namespace.importDeclaration(specifiers, t__namespace.stringLiteral(RUNTIME_MODULE)));
|
|
234
|
+
let afterImports = 0;
|
|
235
|
+
for (let index = 0; index < ast.program.body.length; index += 1) {
|
|
236
|
+
if (t__namespace.isImportDeclaration(ast.program.body[index]))
|
|
237
|
+
afterImports = index + 1;
|
|
238
|
+
}
|
|
239
|
+
ast.program.body.splice(afterImports, 0, ...wrapDecls);
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Rewrite component imports from the configured wrap-modules into
|
|
243
|
+
* `wrap()`-ed bindings, in place. Injects the `wrap` import once when any
|
|
244
|
+
* binding was rewritten.
|
|
245
|
+
* @param ast Parsed Babel file (mutated).
|
|
246
|
+
* @param modules Effective module → policy map.
|
|
247
|
+
* @returns True when at least one import was wrapped.
|
|
248
|
+
*/
|
|
249
|
+
function rewriteWrapImports(ast, modules) {
|
|
250
|
+
const wrapDecls = [];
|
|
251
|
+
let counter = 0;
|
|
252
|
+
let usesNamespace = false;
|
|
253
|
+
for (const node of ast.program.body) {
|
|
254
|
+
if (!t__namespace.isImportDeclaration(node))
|
|
255
|
+
continue;
|
|
256
|
+
const policy = modules.get(node.source.value);
|
|
257
|
+
if (!policy)
|
|
258
|
+
continue;
|
|
259
|
+
const { decls, counter: nextCounter, usesNamespace: ns } = wrapSpecifiers(node, policy, counter);
|
|
260
|
+
counter = nextCounter;
|
|
261
|
+
usesNamespace = usesNamespace || ns;
|
|
262
|
+
wrapDecls.push(...decls);
|
|
263
|
+
}
|
|
264
|
+
if (wrapDecls.length === 0)
|
|
265
|
+
return false;
|
|
266
|
+
placeWrapDecls(ast, wrapDecls, usesNamespace);
|
|
267
|
+
return true;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
exports.DEFAULT_WRAP_MODULES = DEFAULT_WRAP_MODULES;
|
|
271
|
+
exports.buildWrapModules = buildWrapModules;
|
|
272
|
+
exports.rewriteWrapImports = rewriteWrapImports;
|
|
273
|
+
//# sourceMappingURL=wrap-imports.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wrap-imports.cjs","sources":["../../../../src/metro/wrap-imports.ts"],"sourcesContent":["import * as t from '@babel/types'\nimport type { File } from '@babel/types'\n\n/**\n * Build-time import rewrite. For every `import { View } from\n * 'react-native'` (and the other configured modules) it aliases the\n * original export and binds a `wrap()`-ed component in its place:\n *\n * ```\n * import { View, StyleSheet } from 'react-native'\n * ⇩\n * import { View as _rnw0, StyleSheet } from 'react-native'\n * import { wrap as _rnwWrap } from 'rnwind'\n * const View = _rnwWrap(_rnw0)\n * ```\n *\n * Now `<View className=\"…\">` resolves className → style at render via the\n * wrapper — no matter how className arrived (literal, `{...rest}` spread,\n * forwarded through custom layers). Non-component exports (`StyleSheet`)\n * are left untouched.\n */\n\n/** Local binding the injected `wrap` import is aliased to. */\nconst WRAP_LOCAL = '_rnwWrap'\n/** Local binding the injected `wrapNamespace` import is aliased to. */\nconst WRAP_NS_LOCAL = '_rnwWrapNs'\n/** Module the wrapper is imported from. */\nconst RUNTIME_MODULE = 'rnwind'\n\n/**\n * Wrap-modules whose DEFAULT export is a component NAMESPACE accessed via\n * member expressions (`Animated.View`), not a single component. Their\n * default import is bound through `wrapNamespace` (a Proxy that wraps each\n * accessed component member) instead of `wrap`. Every other default import\n * is treated as a plain component.\n */\nconst NAMESPACE_DEFAULT_MODULES: ReadonlySet<string> = new Set(['react-native-reanimated'])\n\n/**\n * react-native mixes styleable components with utilities (`StyleSheet`,\n * `Platform`, …). Only these named exports are wrapped; everything else\n * passes through. Other ecosystem modules export components only and use\n * the `'all'` policy instead.\n */\nconst REACT_NATIVE_COMPONENTS: ReadonlySet<string> = new Set([\n 'View',\n 'Text',\n 'TextInput',\n 'Pressable',\n 'ScrollView',\n 'Image',\n 'ImageBackground',\n 'FlatList',\n 'SectionList',\n 'VirtualizedList',\n 'KeyboardAvoidingView',\n 'SafeAreaView',\n 'Modal',\n 'Switch',\n 'RefreshControl',\n 'ActivityIndicator',\n 'TouchableOpacity',\n 'TouchableHighlight',\n 'TouchableWithoutFeedback',\n 'TouchableNativeFeedback',\n 'Button',\n 'StatusBar',\n])\n\n/**\n * Named exports that LOOK like components (PascalCase) under an `'all'`\n * policy but aren't — React contexts, gesture-handler enums/namespaces,\n * etc. Wrapping these would turn `Gesture.Pan()` / `State.ACTIVE` /\n * `<XContext.Provider>` into a `wrap()`-ed component and break them.\n * Names ending in `Context` are excluded separately.\n */\nconst NON_COMPONENT_EXPORTS: ReadonlySet<string> = new Set([\n 'Gesture',\n 'GestureObjects',\n 'State',\n 'Directions',\n 'Extrapolation',\n 'Extrapolate',\n 'Easing',\n 'ReduceMotion',\n 'KeyframeRegistry',\n])\n\n/** Per-module policy: an explicit allow-list, or `'all'` named exports. */\nexport type WrapPolicy = 'all' | ReadonlySet<string>\n\n/**\n * Default module → wrap policy. react-native is allow-listed (mixed\n * exports); the rest are component-only packages → `'all'`. Only modules\n * the project has installed are ever hit (you can't import from a missing\n * package), so listing optional peers is free.\n */\nexport const DEFAULT_WRAP_MODULES: ReadonlyMap<string, WrapPolicy> = new Map<string, WrapPolicy>([\n ['react-native', REACT_NATIVE_COMPONENTS],\n ['react-native-reanimated', 'all'],\n ['react-native-svg', 'all'],\n ['react-native-gesture-handler', 'all'],\n ['react-native-safe-area-context', 'all'],\n ['expo-linear-gradient', 'all'],\n ['expo-image', 'all'],\n ['expo-blur', 'all'],\n ['expo-symbols', 'all'],\n ['@shopify/flash-list', 'all'],\n ['@shopify/react-native-skia', 'all'],\n ['lottie-react-native', 'all'],\n])\n\n/**\n * Whether a named import from a wrap-module should be wrapped.\n *\n * Explicit allow-lists (react-native) match by exact name. The `'all'`\n * policy wraps only component-style names — PascalCase, not a React\n * context (`*Context`), and not a known non-component export. This is\n * what stops `useSafeAreaInsets` (a hook) from being wrapped into a\n * component and crashing when called.\n * @param policy The module's wrap policy.\n * @param importedName The exported name being imported.\n * @returns True when the name is a component to wrap.\n */\nfunction shouldWrap(policy: WrapPolicy, importedName: string): boolean {\n if (policy !== 'all') return policy.has(importedName)\n if (!/^[A-Z]/.test(importedName)) return false\n if (importedName.endsWith('Context')) return false\n return !NON_COMPONENT_EXPORTS.has(importedName)\n}\n\n/**\n * Merge user-supplied wrap modules onto the defaults — a bare module name\n * adopts the `'all'` policy.\n * @param extra User module specifiers (or undefined).\n * @returns Effective module → policy map.\n */\nexport function buildWrapModules(extra?: readonly string[]): ReadonlyMap<string, WrapPolicy> {\n if (!extra || extra.length === 0) return DEFAULT_WRAP_MODULES\n const merged = new Map<string, WrapPolicy>(DEFAULT_WRAP_MODULES)\n for (const moduleName of extra) if (!merged.has(moduleName)) merged.set(moduleName, 'all')\n return merged\n}\n\n/**\n * The `imported` name of an import specifier (`import { a as b }` → `'a'`).\n * @param specifier Named import specifier.\n * @returns The exported name.\n */\nfunction importedNameOf(specifier: t.ImportSpecifier): string {\n return t.isIdentifier(specifier.imported) ? specifier.imported.name : specifier.imported.value\n}\n\n/**\n * Build `const Local = <wrapper>(alias)` and rebind the specifier's local\n * to `alias` in place.\n * @param specifier The import specifier to rebind.\n * @param alias The `_rnwN` alias to bind the original import to.\n * @param wrapper The runtime helper local (`_rnwWrap` / `_rnwWrapNs`).\n * @returns The wrap declaration.\n */\nfunction makeWrapDecl(\n specifier: t.ImportSpecifier | t.ImportDefaultSpecifier | t.ImportNamespaceSpecifier,\n alias: string,\n wrapper: string,\n): t.VariableDeclaration {\n const { name: localName } = specifier.local\n specifier.local = t.identifier(alias)\n return t.variableDeclaration('const', [\n t.variableDeclarator(t.identifier(localName), t.callExpression(t.identifier(wrapper), [t.identifier(alias)])),\n ])\n}\n\n/**\n * Rewrite one import declaration's wrappable specifiers, aliasing each to\n * `_rnw<N>` in place:\n * - named (`{ View }`) → `const View = wrap(_rnwN)` (per policy),\n * - namespace (`* as Animated`) → `const Animated = wrapNamespace(_rnwN)`,\n * - default → `wrapNamespace` for {@link NAMESPACE_DEFAULT_MODULES}\n * (reanimated's `Animated`), else `wrap` (a plain default component).\n * @param node Import declaration to inspect.\n * @param policy The module's wrap policy.\n * @param counter Next alias index (caller-threaded for uniqueness).\n * @returns New wrap declarations, advanced counter, and whether any\n * binding used `wrapNamespace`.\n */\nfunction wrapSpecifiers(\n node: t.ImportDeclaration,\n policy: WrapPolicy,\n counter: number,\n): { decls: t.VariableDeclaration[]; counter: number; usesNamespace: boolean } {\n const decls: t.VariableDeclaration[] = []\n const moduleName = node.source.value\n let next = counter\n let usesNamespace = false\n for (const specifier of node.specifiers) {\n if (t.isImportSpecifier(specifier)) {\n if (!shouldWrap(policy, importedNameOf(specifier))) continue\n decls.push(makeWrapDecl(specifier, `_rnw${next}`, WRAP_LOCAL))\n next += 1\n continue\n }\n const isNamespace = t.isImportNamespaceSpecifier(specifier) || NAMESPACE_DEFAULT_MODULES.has(moduleName)\n const wrapper = isNamespace ? WRAP_NS_LOCAL : WRAP_LOCAL\n decls.push(makeWrapDecl(specifier, `_rnw${next}`, wrapper))\n next += 1\n if (isNamespace) usesNamespace = true\n }\n return { decls, counter: next, usesNamespace }\n}\n\n/**\n * Insert the `wrap` import at the top and the `const X = wrap(_rnwN)`\n * declarations AFTER every import. The consts reference the aliased\n * binding `_rnwN`, and in Metro's real transform (CommonJS interop + the\n * reanimated worklets plugin) a const placed above its source import\n * evaluates before the binding initialises → `ReferenceError: _rnw0\n * doesn't exist`. ESM-only hoisting would mask this; the bundle does not.\n * @param ast Parsed Babel file (mutated).\n * @param wrapDecls The wrap declarations to place.\n * @param usesNamespace Whether any binding used `wrapNamespace`.\n */\nfunction placeWrapDecls(ast: File, wrapDecls: readonly t.VariableDeclaration[], usesNamespace: boolean): void {\n const specifiers = [t.importSpecifier(t.identifier(WRAP_LOCAL), t.identifier('wrap'))]\n if (usesNamespace) specifiers.push(t.importSpecifier(t.identifier(WRAP_NS_LOCAL), t.identifier('wrapNamespace')))\n ast.program.body.unshift(t.importDeclaration(specifiers, t.stringLiteral(RUNTIME_MODULE)))\n let afterImports = 0\n for (let index = 0; index < ast.program.body.length; index += 1) {\n if (t.isImportDeclaration(ast.program.body[index])) afterImports = index + 1\n }\n ast.program.body.splice(afterImports, 0, ...wrapDecls)\n}\n\n/**\n * Rewrite component imports from the configured wrap-modules into\n * `wrap()`-ed bindings, in place. Injects the `wrap` import once when any\n * binding was rewritten.\n * @param ast Parsed Babel file (mutated).\n * @param modules Effective module → policy map.\n * @returns True when at least one import was wrapped.\n */\nexport function rewriteWrapImports(ast: File, modules: ReadonlyMap<string, WrapPolicy>): boolean {\n const wrapDecls: t.VariableDeclaration[] = []\n let counter = 0\n let usesNamespace = false\n\n for (const node of ast.program.body) {\n if (!t.isImportDeclaration(node)) continue\n const policy = modules.get(node.source.value)\n if (!policy) continue\n const { decls, counter: nextCounter, usesNamespace: ns } = wrapSpecifiers(node, policy, counter)\n counter = nextCounter\n usesNamespace = usesNamespace || ns\n wrapDecls.push(...decls)\n }\n\n if (wrapDecls.length === 0) return false\n placeWrapDecls(ast, wrapDecls, usesNamespace)\n return true\n}\n"],"names":["t"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;AAiBG;AAEH;AACA,MAAM,UAAU,GAAG,UAAU;AAC7B;AACA,MAAM,aAAa,GAAG,YAAY;AAClC;AACA,MAAM,cAAc,GAAG,QAAQ;AAE/B;;;;;;AAMG;AACH,MAAM,yBAAyB,GAAwB,IAAI,GAAG,CAAC,CAAC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C,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC;AAC7C,QAAA,IAAI,CAAC,MAAM;YAAE;QACb,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,EAAE,EAAE,GAAG,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC;QAChG,OAAO,GAAG,WAAW;AACrB,QAAA,aAAa,GAAG,aAAa,IAAI,EAAE;AACnC,QAAA,SAAS,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;IAC1B;AAEA,IAAA,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC;AAAE,QAAA,OAAO,KAAK;AACxC,IAAA,cAAc,CAAC,GAAG,EAAE,SAAS,EAAE,aAAa,CAAC;AAC7C,IAAA,OAAO,IAAI;AACb;;;;;;"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { File } from '@babel/types';
|
|
2
|
+
/** Per-module policy: an explicit allow-list, or `'all'` named exports. */
|
|
3
|
+
export type WrapPolicy = 'all' | ReadonlySet<string>;
|
|
4
|
+
/**
|
|
5
|
+
* Default module → wrap policy. react-native is allow-listed (mixed
|
|
6
|
+
* exports); the rest are component-only packages → `'all'`. Only modules
|
|
7
|
+
* the project has installed are ever hit (you can't import from a missing
|
|
8
|
+
* package), so listing optional peers is free.
|
|
9
|
+
*/
|
|
10
|
+
export declare const DEFAULT_WRAP_MODULES: ReadonlyMap<string, WrapPolicy>;
|
|
11
|
+
/**
|
|
12
|
+
* Merge user-supplied wrap modules onto the defaults — a bare module name
|
|
13
|
+
* adopts the `'all'` policy.
|
|
14
|
+
* @param extra User module specifiers (or undefined).
|
|
15
|
+
* @returns Effective module → policy map.
|
|
16
|
+
*/
|
|
17
|
+
export declare function buildWrapModules(extra?: readonly string[]): ReadonlyMap<string, WrapPolicy>;
|
|
18
|
+
/**
|
|
19
|
+
* Rewrite component imports from the configured wrap-modules into
|
|
20
|
+
* `wrap()`-ed bindings, in place. Injects the `wrap` import once when any
|
|
21
|
+
* binding was rewritten.
|
|
22
|
+
* @param ast Parsed Babel file (mutated).
|
|
23
|
+
* @param modules Effective module → policy map.
|
|
24
|
+
* @returns True when at least one import was wrapped.
|
|
25
|
+
*/
|
|
26
|
+
export declare function rewriteWrapImports(ast: File, modules: ReadonlyMap<string, WrapPolicy>): boolean;
|