@vxrn/compiler 2.0.0-beta.98.1 → 2.6.0
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/dist/cjs/index.cjs +10 -1
- package/dist/cjs/reactNativeViewConfig.cjs +1 -1
- package/dist/cjs/transformBabel.cjs +15 -57
- package/dist/cjs/transformFlow.cjs +87 -0
- package/dist/cjs/transformHermesClasses.cjs +58 -0
- package/dist/cjs/transformSWC.cjs +3 -4
- package/dist/cjs/workletUtils.cjs +30 -0
- package/dist/cjs/worklets/autoworklet.cjs +2 -2
- package/dist/cjs/worklets/globals.cjs +22 -1
- package/dist/esm/index.js +12 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/index.mjs +12 -1
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/reactNativeViewConfig.mjs +1 -1
- package/dist/esm/reactNativeViewConfig.mjs.map +1 -1
- package/dist/esm/transformBabel.mjs +17 -58
- package/dist/esm/transformBabel.mjs.map +1 -1
- package/dist/esm/transformFlow.mjs +62 -0
- package/dist/esm/transformFlow.mjs.map +1 -0
- package/dist/esm/transformHermesClasses.mjs +32 -0
- package/dist/esm/transformHermesClasses.mjs.map +1 -0
- package/dist/esm/transformSWC.mjs +3 -4
- package/dist/esm/transformSWC.mjs.map +1 -1
- package/dist/esm/workletUtils.mjs +5 -0
- package/dist/esm/worklets/autoworklet.mjs +2 -2
- package/dist/esm/worklets/autoworklet.mjs.map +1 -1
- package/dist/esm/worklets/globals.mjs +22 -1
- package/dist/esm/worklets/globals.mjs.map +1 -1
- package/package.json +12 -4
- package/src/index.ts +12 -1
- package/src/reactNativeViewConfig.ts +7 -2
- package/src/transformBabel.test.ts +61 -37
- package/src/transformBabel.ts +28 -92
- package/src/transformFlow.test.ts +134 -0
- package/src/transformFlow.ts +68 -0
- package/src/transformHermesClasses.ts +34 -0
- package/src/transformSWC.test.ts +33 -1
- package/src/transformSWC.ts +14 -4
- package/src/transformWorklets.test.ts +64 -0
- package/src/workletUtils.ts +4 -0
- package/src/worklets/autoworklet.ts +5 -2
- package/src/worklets/globals.ts +23 -0
- package/types/index.d.ts +2 -0
- package/types/index.d.ts.map +1 -1
- package/types/reactNativeViewConfig.d.ts +1 -1
- package/types/reactNativeViewConfig.d.ts.map +1 -1
- package/types/transformBabel.d.ts +0 -12
- package/types/transformBabel.d.ts.map +1 -1
- package/types/transformFlow.d.ts +5 -0
- package/types/transformFlow.d.ts.map +1 -0
- package/types/transformHermesClasses.d.ts +5 -0
- package/types/transformHermesClasses.d.ts.map +1 -0
- package/types/transformSWC.d.ts.map +1 -1
- package/types/workletUtils.d.ts +4 -0
- package/types/workletUtils.d.ts.map +1 -0
- package/types/worklets/autoworklet.d.ts.map +1 -1
- package/types/worklets/globals.d.ts.map +1 -1
package/dist/esm/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["esm/index.js"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, extname, join, relative, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { resolvePath } from \"@vxrn/utils\";\nimport { cssToReactNativeRuntime } from \"react-native-css-interop/css-to-rn/index.js\";\nimport { configuration, isNativeWorkletsEnabled } from \"./configure\";\nimport { debug, runtimePublicPath, validParsers } from \"./constants\";\nimport {\n getBabelOptions,\n transformBabel,\n transformOxcReactCompiler\n} from \"./transformBabel\";\nimport { shouldSourceMap } from \"./transformSWC\";\nimport {\n prepareWorkletsForReactCompiler,\n shouldTransformWorklets,\n transformWorklets\n} from \"./transformWorklets\";\nimport { getCachedTransform, logCacheStats, setCachedTransform } from \"./cache\";\nexport * from \"./configure\";\nexport * from \"./transformBabel\";\nexport * from \"./transformSWC\";\nexport * from \"./transformWorklets\";\nexport * from \"./reactNativeCodegen\";\nexport * from \"./transformHermesLoops\";\nexport * from \"./transformHermesAsync\";\nimport { clearTransformCache } from \"./cache\";\nimport { JS_GLOBALS } from \"./worklets/globals\";\nimport { getClosureVariables } from \"./worklets/scope\";\nconst perfStats = {\n babel: {\n totalCalls: 0,\n totalTransforms: 0,\n totalTime: 0,\n byEnvironment: {}\n },\n optimizeDeps: {\n byEnvironment: {}\n }\n};\nfunction logPerfSummary() {\n if (!process.env.DEBUG_COMPILER_PERF) {\n return;\n }\n console.info(\"\\n\\u{1F4CA} [Compiler Performance Summary]\");\n console.info(\n `Babel: ${perfStats.babel.totalTransforms} transforms / ${perfStats.babel.totalCalls} calls (${(perfStats.babel.totalTransforms / Math.max(perfStats.babel.totalCalls, 1) * 100).toFixed(1)}% transform rate)`\n );\n console.info(`Babel total time: ${perfStats.babel.totalTime}ms`);\n for (const [env, stats] of Object.entries(perfStats.babel.byEnvironment)) {\n if (stats.transforms > 0) {\n console.info(\n ` ${env}: ${stats.transforms} transforms, ${stats.time}ms (${(stats.time / stats.transforms).toFixed(1)}ms avg)`\n );\n }\n }\n for (const [env, stats] of Object.entries(perfStats.optimizeDeps.byEnvironment)) {\n const elapsed = Date.now() - stats.startTime;\n console.info(\n `optimizeDeps ${env}: checked ${stats.filesChecked} files, transformed ${stats.filesTransformed} (${elapsed}ms)`\n );\n }\n}\nconst compilerLog = {\n compiled: 0,\n cached: 0,\n time: 0,\n // typed loose because the dom lib types setTimeout as number, but node gives\n // us a Timeout we need to unref so the debounce never holds the process open\n timer: null\n};\nfunction logCompiled(cached, ms) {\n if (cached) {\n compilerLog.cached++;\n } else {\n compilerLog.compiled++;\n compilerLog.time += ms;\n }\n if (compilerLog.timer) clearTimeout(compilerLog.timer);\n compilerLog.timer = setTimeout(() => {\n const total = compilerLog.compiled + compilerLog.cached;\n const detail = compilerLog.compiled ? `${compilerLog.compiled} compiled in ${compilerLog.time}ms${compilerLog.cached ? `, ${compilerLog.cached} cached` : \"\"}` : `all cached`;\n console.info(` \\u{1FA84} [compiler] ${total} file${total === 1 ? \"\" : \"s\"} (${detail})`);\n compilerLog.compiled = 0;\n compilerLog.cached = 0;\n compilerLog.time = 0;\n compilerLog.timer = null;\n }, 500);\n compilerLog.timer.unref?.();\n}\nasync function performBabelTransform({\n id,\n code,\n projectRoot,\n environment,\n production,\n reactForRNVersion,\n optionsIn\n}) {\n perfStats.babel.totalCalls++;\n if (!perfStats.babel.byEnvironment[environment]) {\n perfStats.babel.byEnvironment[environment] = { calls: 0, transforms: 0, time: 0 };\n }\n perfStats.babel.byEnvironment[environment].calls++;\n const transformProps = {\n id,\n code,\n projectRoot,\n development: !production,\n environment,\n reactForRNVersion\n };\n const userTransform = optionsIn?.transform?.(transformProps);\n if (userTransform === false) {\n return null;\n }\n if (userTransform !== \"swc\" && userTransform !== \"oxc\") {\n const babelOptions = getBabelOptions({\n ...transformProps,\n userSetting: userTransform\n });\n if (babelOptions) {\n const hasCompilerPlugin = babelOptions.plugins?.some(\n (x) => Array.isArray(x) && x[0] === \"babel-plugin-react-compiler\"\n );\n const userBabelConfigPath = typeof babelOptions.configFile === \"string\" ? babelOptions.configFile : null;\n const cached = getCachedTransform(id, code, environment, userBabelConfigPath);\n if (cached) {\n perfStats.babel.byEnvironment[environment].transforms++;\n if (hasCompilerPlugin && (cached.code.includes(\"react/compiler-runtime\") || cached.code.includes(\"react-compiler-runtime\"))) {\n debug?.(` \\u{1FA84} [compiler] ${relative(process.cwd(), id)} (cached)`);\n logCompiled(true, 0);\n }\n debug?.(`[babel/cached] ${id}`);\n return cached;\n }\n const isWorkletPlugin = (entry) => {\n if (!entry) return false;\n const name = typeof entry === \"string\" ? entry : Array.isArray(entry) ? entry[0] : null;\n return typeof name === \"string\" && (name.includes(\"react-native-worklets\") || name.includes(\"react-native-reanimated\"));\n };\n const workletEntry = babelOptions.plugins?.find(isWorkletPlugin);\n const workletPluginOptions = Array.isArray(workletEntry) ? workletEntry[1] : void 0;\n const useWorklets = isNativeWorkletsEnabled() && (Boolean(workletEntry) || shouldTransformWorklets({ id, code }));\n let curCode = code;\n let workletPreparation = null;\n let compilerOut = null;\n const compilerPluginIndex = babelOptions.plugins?.findIndex(\n (x) => Array.isArray(x) && x[0] === \"babel-plugin-react-compiler\"\n ) ?? -1;\n if (compilerPluginIndex !== -1) {\n const compilerPluginConfig = babelOptions.plugins[compilerPluginIndex];\n const compilerPluginOptions = compilerPluginConfig[1] || {};\n const useBabelCompiler = compilerPluginOptions.compiler === \"babel\" || process.env.ONE_REACT_COMPILER === \"babel\" || process.env.VXRN_REACT_COMPILER === \"babel\";\n if (!useBabelCompiler) {\n if (useWorklets) {\n workletPreparation = prepareWorkletsForReactCompiler(\n id,\n curCode,\n shouldSourceMap()\n );\n if (workletPreparation) curCode = workletPreparation.code;\n }\n compilerOut = await transformOxcReactCompiler(\n id,\n curCode,\n compilerPluginOptions,\n shouldSourceMap()\n );\n if (compilerOut) curCode = compilerOut.code;\n babelOptions.plugins.splice(compilerPluginIndex, 1);\n }\n }\n let workletsOut = null;\n if (useWorklets) {\n workletsOut = await transformWorklets(id, curCode, shouldSourceMap(), {\n projectRoot,\n ...workletPluginOptions\n });\n babelOptions.plugins = babelOptions.plugins?.filter(\n (entry) => !isWorkletPlugin(entry)\n );\n curCode = workletsOut.code;\n }\n const startTime = Date.now();\n let babelOut = null;\n if (babelOptions.plugins?.length === 0 && !babelOptions.configFile && !babelOptions.babelrc) {\n let finalMap = void 0;\n if (shouldSourceMap()) {\n const intermediateMaps = [\n workletPreparation?.map,\n compilerOut?.map,\n workletsOut?.map\n ].filter(Boolean);\n if (intermediateMaps.length === 1) {\n finalMap = intermediateMaps[0];\n } else if (intermediateMaps.length > 1) {\n const remapping = (await import(\"@jridgewell/remapping\")).default;\n finalMap = remapping(intermediateMaps.slice().reverse(), () => null);\n }\n }\n babelOut = { code: curCode, map: finalMap };\n } else {\n const babelOptsWithMap = shouldSourceMap() && (workletsOut?.map || compilerOut?.map || workletPreparation?.map) ? { ...babelOptions, sourceMaps: true } : babelOptions;\n babelOut = await transformBabel(id, curCode, babelOptsWithMap);\n if (shouldSourceMap() && babelOut?.map) {\n const priorMaps = [\n workletPreparation?.map,\n compilerOut?.map,\n workletsOut?.map\n ].filter(Boolean);\n if (priorMaps.length > 0) {\n const remapping = (await import(\"@jridgewell/remapping\")).default;\n babelOut.map = remapping(\n [babelOut.map, ...priorMaps.slice().reverse()],\n () => null\n );\n }\n }\n }\n const babelTime = Date.now() - startTime;\n if (babelOut?.code) {\n perfStats.babel.totalTransforms++;\n perfStats.babel.totalTime += babelTime;\n perfStats.babel.byEnvironment[environment].transforms++;\n perfStats.babel.byEnvironment[environment].time += babelTime;\n if (hasCompilerPlugin && (babelOut.code.includes(\"react/compiler-runtime\") || babelOut.code.includes(\"react-compiler-runtime\"))) {\n debug?.(` \\u{1FA84} [compiler] ${relative(process.cwd(), id)} (${babelTime}ms)`);\n logCompiled(false, babelTime);\n }\n debug?.(`[babel] ${id}`);\n const outCode = `${babelOut.code}\n// vxrn-did-babel`;\n const result = { code: outCode, map: babelOut.map };\n setCachedTransform(id, code, result, environment, userBabelConfigPath);\n return result;\n }\n }\n }\n return null;\n}\nasync function createVXRNCompilerPlugin(optionsIn) {\n const reactVersion = await (async () => {\n const path = resolvePath(\"react/package.json\");\n const json = JSON.parse(await readFile(path, \"utf-8\"));\n return json.version;\n })();\n const envNames = {\n ios: true,\n android: true,\n client: true,\n ssr: true\n };\n function getEnvName(name) {\n if (name === \"worker\") return \"ssr\";\n if (!envNames[name]) throw new Error(`Invalid env: ${name}`);\n return name;\n }\n const reactForRNVersion = reactVersion.split(\".\")[0];\n const cssTransformCache = /* @__PURE__ */ new Map();\n const rolldownPath = resolvePath(\"rolldown\");\n const rolldownNodeMods = rolldownPath.slice(\n 0,\n rolldownPath.indexOf(sep + \"node_modules\")\n );\n let config;\n return [\n {\n name: \"one:compiler-resolve-refresh-runtime\",\n apply: \"serve\",\n enforce: \"pre\",\n // Run before Vite default resolve to avoid syscalls\n resolveId: (id) => id === runtimePublicPath || id === `${runtimePublicPath}.map` ? id : void 0,\n load: (id) => {\n const basePath = dirname(fileURLToPath(import.meta.url));\n if (id === runtimePublicPath) {\n return readFileSync(join(basePath, \"refresh-runtime.mjs\"), \"utf-8\").replace(\n /\\/\\/# sourceMappingURL=.*/,\n \"\"\n );\n }\n if (id === `${runtimePublicPath}.map`) {\n return JSON.stringify({ version: 3, sources: [], mappings: \"\" });\n }\n return void 0;\n }\n },\n {\n name: `one:compiler-css-to-js`,\n // only .css files can match, so let rust reject everything else\n transform: {\n filter: { id: /\\.css$/ },\n handler(codeIn, id) {\n const environment = getEnvName(this.environment.name);\n if (configuration.enableNativeCSS && (environment === \"ios\" || environment === \"android\")) {\n {\n const data = JSON.stringify(\n cssToReactNativeRuntime(codeIn, { inlineRem: 16 })\n );\n const code = `require(\"nativewind/dist/index.js\").require().StyleSheet.registerCompiled(${data})`;\n const newId = `${id}.js`;\n const cssId = newId.replace(rolldownNodeMods + sep, \"\");\n cssTransformCache.set(cssId, code);\n return {\n code,\n id: newId,\n map: null\n };\n }\n }\n }\n },\n generateBundle(_, bundle) {\n const environment = getEnvName(this.environment.name);\n if (configuration.enableNativeCSS && (environment === \"ios\" || environment === \"android\")) {\n const rootJSName = Object.keys(bundle).find((i) => {\n const chunk = bundle[i];\n return chunk.type == \"chunk\" && chunk.fileName.match(/.[cm]?js(?:\\?.+)?$/) != null;\n });\n if (!rootJSName) {\n throw new Error(`Can't find root js, internal one error`);\n }\n const rootJS = bundle[rootJSName];\n const cssAssets = Object.keys(bundle).filter(\n (i) => bundle[i].fileName.endsWith(\".css.js\")\n );\n for (const name of cssAssets) {\n delete bundle[name];\n const jsCSS = cssTransformCache.get(name);\n rootJS.code = `\n${jsCSS}\n${rootJS.code}\n`;\n }\n }\n }\n },\n {\n name: \"one:compiler\",\n enforce: \"pre\",\n config: () => {\n const nodeModulesFilter = /node_modules[/\\\\].*\\.(tsx?|jsx?|mjs|cjs)$/;\n const createEnvironmentConfig = (environment) => {\n if (!perfStats.optimizeDeps.byEnvironment[environment]) {\n perfStats.optimizeDeps.byEnvironment[environment] = {\n filesChecked: 0,\n filesTransformed: 0,\n startTime: Date.now()\n };\n }\n return {\n optimizeDeps: {\n rolldownOptions: {\n plugins: [\n {\n name: `transform-before-optimize-deps-${environment}`,\n async transform(code, id) {\n if (!nodeModulesFilter.test(id)) {\n return null;\n }\n perfStats.optimizeDeps.byEnvironment[environment].filesChecked++;\n const production = process.env.NODE_ENV === \"production\" || process.env.NODE_ENV === \"test\";\n debug?.(`[rolldown optimizeDeps] ${id}`);\n const result = await performBabelTransform({\n id,\n code,\n projectRoot: config.root,\n environment,\n production,\n reactForRNVersion,\n optionsIn\n });\n if (!result) {\n return null;\n }\n perfStats.optimizeDeps.byEnvironment[environment].filesTransformed++;\n return {\n code: result.code,\n map: result.map\n };\n },\n buildEnd() {\n if (process.env.DEBUG_COMPILER_PERF) {\n const stats = perfStats.optimizeDeps.byEnvironment[environment];\n const elapsed = Date.now() - stats.startTime;\n console.info(\n `[optimizeDeps ${environment}] Done: ${stats.filesChecked} files checked, ${stats.filesTransformed} transformed (${elapsed}ms)`\n );\n }\n const allDone = Object.keys(perfStats.optimizeDeps.byEnvironment).length >= 2;\n if (allDone) {\n logCacheStats();\n logPerfSummary();\n }\n }\n }\n ]\n }\n },\n define: {\n \"process.env.NATIVEWIND_OS\": JSON.stringify(\n environment === \"ios\" || environment === \"android\" ? \"native\" : \"web\"\n )\n }\n };\n };\n return {\n environments: {\n ios: createEnvironmentConfig(\"ios\"),\n android: createEnvironmentConfig(\"android\"),\n client: createEnvironmentConfig(\"client\"),\n ssr: createEnvironmentConfig(\"ssr\")\n }\n };\n },\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n },\n async transform(codeIn, _id) {\n let code = codeIn;\n const environment = getEnvName(this.environment.name);\n const isNative = environment === \"ios\" || environment === \"android\";\n const production = config.command === \"build\" || process.env.NODE_ENV === \"production\" || JSON.parse(\n this.environment.config?.define?.[\"process.env.NODE_ENV\"] || '\"\"'\n ) === \"production\";\n const isEntry = _id.includes(\"one-entry-native\");\n if (isEntry) {\n if (isNative && !production) {\n code = `import '@vxrn/vite-native-client'\n${code}`;\n }\n if (isNative && configuration.enableNativewind) {\n code = `import * as x from 'nativewind'\n${code}`;\n }\n return code;\n }\n const id = _id.split(\"?\")[0];\n const extension = extname(id);\n if (extension === \".css\" || !validParsers.has(extension)) {\n return;\n }\n if (id.includes(`virtual:`)) {\n return;\n }\n if (codeIn.endsWith(`// vxrn-did-babel`)) {\n debug?.(`[skip babel] ${id}`);\n return;\n }\n return performBabelTransform({\n id,\n code: codeIn,\n projectRoot: config.root,\n environment,\n production,\n reactForRNVersion,\n optionsIn\n });\n }\n },\n // wraps client-side TSX/JSX with React Refresh preamble + import.meta.hot.accept\n // runs after vite:oxc (no enforce:'pre') so it sees the already-transformed code\n {\n name: \"one:react-refresh-web\",\n apply: \"serve\",\n transform(code, _id) {\n if (this.environment.name !== \"client\") return;\n if (code.includes(runtimePublicPath)) return;\n const id = _id.split(\"?\")[0];\n if (id.includes(\"node_modules\")) return;\n if (id.includes(\"virtual:\")) return;\n if (id === runtimePublicPath) return;\n const ext = extname(id);\n if (ext !== \".tsx\" && ext !== \".jsx\") return;\n const hasRefreshCalls = /\\$RefreshReg\\$\\(/.test(code);\n let out = `import * as RefreshRuntime from \"${runtimePublicPath}\";\n\n`;\n if (hasRefreshCalls) {\n out += `if (!window.$RefreshReg$) throw new Error(\"React refresh preamble was not loaded. Something is wrong.\");\nconst prevRefreshReg = window.$RefreshReg$;\nconst prevRefreshSig = window.$RefreshSig$;\nwindow.$RefreshReg$ = RefreshRuntime.getRefreshReg(\"${id}\");\nwindow.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;\n\n`;\n }\n out += code;\n if (hasRefreshCalls) {\n out += `\n\nwindow.$RefreshReg$ = prevRefreshReg;\nwindow.$RefreshSig$ = prevRefreshSig;\n`;\n }\n out += `\nRefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {\n RefreshRuntime.registerExportsForReactRefresh(\"${id}\", currentExports);\n import.meta.hot.accept((nextExports) => {\n if (!nextExports) return;\n const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(\"${id}\", currentExports, nextExports);\n if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);\n });\n});\n`;\n return { code: out, map: null };\n }\n }\n ];\n}\nexport {\n JS_GLOBALS,\n clearTransformCache,\n createVXRNCompilerPlugin,\n getClosureVariables\n};\n//# sourceMappingURL=index.js.map\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,YAAY;CAChB,OAAO;EACL,YAAY;EACZ,iBAAiB;EACjB,WAAW;EACX,eAAe,CAAC;CAClB;CACA,cAAc,EACZ,eAAe,CAAC,EAClB;AACF;AACA,SAAS,iBAAiB;CACxB,IAAI,CAAC,QAAQ,IAAI,qBAAqB;EACpC;CACF;CACA,QAAQ,KAAK,qCAA4C;CACzD,QAAQ,KACN,UAAU,UAAU,MAAM,gBAAgB,gBAAgB,UAAU,MAAM,WAAW,WAAW,UAAU,MAAM,kBAAkB,KAAK,IAAI,UAAU,MAAM,YAAY,CAAC,IAAI,IAAG,CAAE,QAAQ,CAAC,EAAE,kBAC9L;CACA,QAAQ,KAAK,qBAAqB,UAAU,MAAM,UAAU,GAAG;CAC/D,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,UAAU,MAAM,aAAa,GAAG;EACxE,IAAI,MAAM,aAAa,GAAG;GACxB,QAAQ,KACN,KAAK,IAAI,IAAI,MAAM,WAAW,eAAe,MAAM,KAAK,OAAO,MAAM,OAAO,MAAM,WAAU,CAAE,QAAQ,CAAC,EAAE,QAC3G;EACF;CACF;CACA,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,UAAU,aAAa,aAAa,GAAG;EAC/E,MAAM,UAAU,KAAK,IAAI,IAAI,MAAM;EACnC,QAAQ,KACN,gBAAgB,IAAI,YAAY,MAAM,aAAa,sBAAsB,MAAM,iBAAiB,IAAI,QAAQ,IAC9G;CACF;AACF;A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AC3B;KACA,MAAM;KACN,aAAa,OAAO;KACpB;KACA;KACA;KACA;IACF,CAAC;GACH;EACF;EAGA;GACE,MAAM;GACN,OAAO;GACP,UAAU,MAAM,KAAK;IACnB,IAAI,KAAK,YAAY,SAAS,UAAU;IACxC,IAAI,KAAK,SAAS,iBAAiB,GAAG;IACtC,MAAM,KAAK,IAAI,MAAM,GAAG,CAAC,CAAC;IAC1B,IAAI,GAAG,SAAS,cAAc,GAAG;IACjC,IAAI,GAAG,SAAS,UAAU,GAAG;IAC7B,IAAI,OAAO,mBAAmB;IAC9B,MAAM,MAAM,QAAQ,EAAE;IACtB,IAAI,QAAQ,UAAU,QAAQ,QAAQ;IACtC,MAAM,kBAAkB,mBAAmB,KAAK,IAAI;IACpD,IAAI,MAAM,oCAAoC,kBAAkB;;;IAGhE,IAAI,iBAAiB;KACnB,OAAO;;;sDAGqC,GAAG;;;;IAIjD;IACA,OAAO;IACP,IAAI,iBAAiB;KACnB,OAAO;;;;;IAKT;IACA,OAAO;;mDAEoC,GAAG;;;wFAGkC,GAAG;;;;;IAKnF,OAAO;KAAE,MAAM;KAAK,KAAK;IAAK;GAChC;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["esm/index.js"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, extname, join, relative, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { resolvePath } from \"@vxrn/utils\";\nimport { cssToReactNativeRuntime } from \"react-native-css-interop/css-to-rn/index.js\";\nimport { configuration, isNativeWorkletsEnabled } from \"./configure\";\nimport { debug, runtimePublicPath, validParsers } from \"./constants\";\nimport {\n getBabelOptions,\n transformBabel,\n transformOxcReactCompiler\n} from \"./transformBabel\";\nimport { shouldSourceMap } from \"./transformSWC\";\nimport {\n prepareWorkletsForReactCompiler,\n shouldTransformWorklets,\n transformWorklets\n} from \"./transformWorklets\";\nimport { getCachedTransform, logCacheStats, setCachedTransform } from \"./cache\";\nexport * from \"./configure\";\nexport * from \"./transformBabel\";\nexport * from \"./transformFlow\";\nexport * from \"./transformSWC\";\nexport * from \"./transformWorklets\";\nexport * from \"./reactNativeCodegen\";\nexport * from \"./transformHermesLoops\";\nexport * from \"./transformHermesAsync\";\nexport * from \"./transformHermesClasses\";\nimport { clearTransformCache } from \"./cache\";\nimport { JS_GLOBALS } from \"./worklets/globals\";\nimport { getClosureVariables } from \"./worklets/scope\";\nconst perfStats = {\n babel: {\n totalCalls: 0,\n totalTransforms: 0,\n totalTime: 0,\n byEnvironment: {}\n },\n optimizeDeps: {\n byEnvironment: {}\n }\n};\nfunction logPerfSummary() {\n if (!process.env.DEBUG_COMPILER_PERF) {\n return;\n }\n console.info(\"\\n\\u{1F4CA} [Compiler Performance Summary]\");\n console.info(\n `Babel: ${perfStats.babel.totalTransforms} transforms / ${perfStats.babel.totalCalls} calls (${(perfStats.babel.totalTransforms / Math.max(perfStats.babel.totalCalls, 1) * 100).toFixed(1)}% transform rate)`\n );\n console.info(`Babel total time: ${perfStats.babel.totalTime}ms`);\n for (const [env, stats] of Object.entries(perfStats.babel.byEnvironment)) {\n if (stats.transforms > 0) {\n console.info(\n ` ${env}: ${stats.transforms} transforms, ${stats.time}ms (${(stats.time / stats.transforms).toFixed(1)}ms avg)`\n );\n }\n }\n for (const [env, stats] of Object.entries(perfStats.optimizeDeps.byEnvironment)) {\n const elapsed = Date.now() - stats.startTime;\n console.info(\n `optimizeDeps ${env}: checked ${stats.filesChecked} files, transformed ${stats.filesTransformed} (${elapsed}ms)`\n );\n }\n}\nconst compilerLog = {\n compiled: 0,\n cached: 0,\n time: 0,\n // typed loose because the dom lib types setTimeout as number, but node gives\n // us a Timeout we need to unref so the debounce never holds the process open\n timer: null\n};\nfunction logCompiled(cached, ms) {\n if (cached) {\n compilerLog.cached++;\n } else {\n compilerLog.compiled++;\n compilerLog.time += ms;\n }\n if (compilerLog.timer) clearTimeout(compilerLog.timer);\n compilerLog.timer = setTimeout(() => {\n const total = compilerLog.compiled + compilerLog.cached;\n const detail = compilerLog.compiled ? `${compilerLog.compiled} compiled in ${compilerLog.time}ms${compilerLog.cached ? `, ${compilerLog.cached} cached` : \"\"}` : `all cached`;\n console.info(` \\u{1FA84} [compiler] ${total} file${total === 1 ? \"\" : \"s\"} (${detail})`);\n compilerLog.compiled = 0;\n compilerLog.cached = 0;\n compilerLog.time = 0;\n compilerLog.timer = null;\n }, 500);\n compilerLog.timer.unref?.();\n}\nasync function performBabelTransform({\n id,\n code,\n projectRoot,\n environment,\n production,\n reactForRNVersion,\n optionsIn\n}) {\n perfStats.babel.totalCalls++;\n if (!perfStats.babel.byEnvironment[environment]) {\n perfStats.babel.byEnvironment[environment] = { calls: 0, transforms: 0, time: 0 };\n }\n perfStats.babel.byEnvironment[environment].calls++;\n const transformProps = {\n id,\n code,\n projectRoot,\n development: !production,\n environment,\n reactForRNVersion\n };\n const userTransform = optionsIn?.transform?.(transformProps);\n if (userTransform === false) {\n return null;\n }\n if (userTransform !== \"swc\" && userTransform !== \"oxc\") {\n let babelOptions = getBabelOptions({\n ...transformProps,\n userSetting: userTransform\n });\n if (!babelOptions && shouldTransformWorklets({ id, code })) {\n babelOptions = { plugins: [] };\n }\n if (babelOptions) {\n const hasCompilerPlugin = babelOptions.plugins?.some(\n (x) => Array.isArray(x) && x[0] === \"babel-plugin-react-compiler\"\n );\n const userBabelConfigPath = typeof babelOptions.configFile === \"string\" ? babelOptions.configFile : null;\n const cached = getCachedTransform(id, code, environment, userBabelConfigPath);\n if (cached) {\n perfStats.babel.byEnvironment[environment].transforms++;\n if (hasCompilerPlugin && (cached.code.includes(\"react/compiler-runtime\") || cached.code.includes(\"react-compiler-runtime\"))) {\n debug?.(` \\u{1FA84} [compiler] ${relative(process.cwd(), id)} (cached)`);\n logCompiled(true, 0);\n }\n debug?.(`[babel/cached] ${id}`);\n return cached;\n }\n const isWorkletPlugin = (entry) => {\n if (!entry) return false;\n const name = typeof entry === \"string\" ? entry : Array.isArray(entry) ? entry[0] : null;\n return typeof name === \"string\" && (name.includes(\"react-native-worklets\") || name.includes(\"react-native-reanimated\"));\n };\n const workletEntry = babelOptions.plugins?.find(isWorkletPlugin);\n const workletPluginOptions = Array.isArray(workletEntry) ? workletEntry[1] : void 0;\n const useWorklets = isNativeWorkletsEnabled() && (Boolean(workletEntry) || shouldTransformWorklets({ id, code }));\n let curCode = code;\n let workletPreparation = null;\n let compilerOut = null;\n const compilerPluginIndex = babelOptions.plugins?.findIndex(\n (x) => Array.isArray(x) && x[0] === \"babel-plugin-react-compiler\"\n ) ?? -1;\n if (compilerPluginIndex !== -1) {\n const compilerPluginConfig = babelOptions.plugins[compilerPluginIndex];\n const compilerPluginOptions = compilerPluginConfig[1] || {};\n const useBabelCompiler = compilerPluginOptions.compiler === \"babel\" || process.env.ONE_REACT_COMPILER === \"babel\" || process.env.VXRN_REACT_COMPILER === \"babel\";\n if (!useBabelCompiler) {\n if (useWorklets) {\n workletPreparation = prepareWorkletsForReactCompiler(\n id,\n curCode,\n shouldSourceMap()\n );\n if (workletPreparation) curCode = workletPreparation.code;\n }\n compilerOut = await transformOxcReactCompiler(\n id,\n curCode,\n compilerPluginOptions,\n shouldSourceMap()\n );\n if (compilerOut) curCode = compilerOut.code;\n babelOptions.plugins.splice(compilerPluginIndex, 1);\n }\n }\n let workletsOut = null;\n if (useWorklets) {\n workletsOut = await transformWorklets(id, curCode, shouldSourceMap(), {\n projectRoot,\n ...workletPluginOptions\n });\n babelOptions.plugins = babelOptions.plugins?.filter(\n (entry) => !isWorkletPlugin(entry)\n );\n curCode = workletsOut.code;\n }\n const startTime = Date.now();\n let babelOut = null;\n if (babelOptions.plugins?.length === 0 && !babelOptions.configFile && !babelOptions.babelrc) {\n let finalMap = void 0;\n if (shouldSourceMap()) {\n const intermediateMaps = [\n workletPreparation?.map,\n compilerOut?.map,\n workletsOut?.map\n ].filter(Boolean);\n if (intermediateMaps.length === 1) {\n finalMap = intermediateMaps[0];\n } else if (intermediateMaps.length > 1) {\n const remapping = (await import(\"@jridgewell/remapping\")).default;\n finalMap = remapping(intermediateMaps.slice().reverse(), () => null);\n }\n }\n babelOut = { code: curCode, map: finalMap };\n } else {\n const babelOptsWithMap = shouldSourceMap() && (workletsOut?.map || compilerOut?.map || workletPreparation?.map) ? { ...babelOptions, sourceMaps: true } : babelOptions;\n babelOut = await transformBabel(id, curCode, babelOptsWithMap);\n if (shouldSourceMap() && babelOut?.map) {\n const priorMaps = [\n workletPreparation?.map,\n compilerOut?.map,\n workletsOut?.map\n ].filter(Boolean);\n if (priorMaps.length > 0) {\n const remapping = (await import(\"@jridgewell/remapping\")).default;\n babelOut.map = remapping(\n [babelOut.map, ...priorMaps.slice().reverse()],\n () => null\n );\n }\n }\n }\n const babelTime = Date.now() - startTime;\n if (babelOut?.code) {\n perfStats.babel.totalTransforms++;\n perfStats.babel.totalTime += babelTime;\n perfStats.babel.byEnvironment[environment].transforms++;\n perfStats.babel.byEnvironment[environment].time += babelTime;\n if (hasCompilerPlugin && (babelOut.code.includes(\"react/compiler-runtime\") || babelOut.code.includes(\"react-compiler-runtime\"))) {\n debug?.(` \\u{1FA84} [compiler] ${relative(process.cwd(), id)} (${babelTime}ms)`);\n logCompiled(false, babelTime);\n }\n debug?.(`[babel] ${id}`);\n const outCode = `${babelOut.code}\n// vxrn-did-babel`;\n const result = { code: outCode, map: babelOut.map };\n setCachedTransform(id, code, result, environment, userBabelConfigPath);\n return result;\n }\n }\n }\n return null;\n}\nasync function createVXRNCompilerPlugin(optionsIn) {\n const reactVersion = await (async () => {\n const path = resolvePath(\"react/package.json\");\n const json = JSON.parse(await readFile(path, \"utf-8\"));\n return json.version;\n })();\n const envNames = {\n ios: true,\n android: true,\n client: true,\n ssr: true\n };\n function getEnvName(name) {\n if (name === \"worker\") return \"ssr\";\n if (!envNames[name]) throw new Error(`Invalid env: ${name}`);\n return name;\n }\n const reactForRNVersion = reactVersion.split(\".\")[0];\n const cssTransformCache = /* @__PURE__ */ new Map();\n const rolldownPath = resolvePath(\"rolldown\");\n const rolldownNodeMods = rolldownPath.slice(\n 0,\n rolldownPath.indexOf(sep + \"node_modules\")\n );\n let config;\n return [\n {\n name: \"one:compiler-resolve-refresh-runtime\",\n apply: \"serve\",\n enforce: \"pre\",\n // Run before Vite default resolve to avoid syscalls\n resolveId: (id) => id === runtimePublicPath || id === `${runtimePublicPath}.map` ? id : void 0,\n load: (id) => {\n const basePath = dirname(fileURLToPath(import.meta.url));\n if (id === runtimePublicPath) {\n return readFileSync(join(basePath, \"refresh-runtime.mjs\"), \"utf-8\").replace(\n /\\/\\/# sourceMappingURL=.*/,\n \"\"\n );\n }\n if (id === `${runtimePublicPath}.map`) {\n return JSON.stringify({ version: 3, sources: [], mappings: \"\" });\n }\n return void 0;\n }\n },\n {\n name: `one:compiler-css-to-js`,\n // only .css files can match, so let rust reject everything else\n transform: {\n filter: { id: /\\.css$/ },\n handler(codeIn, id) {\n const environment = getEnvName(this.environment.name);\n if (configuration.enableNativeCSS && (environment === \"ios\" || environment === \"android\")) {\n {\n const data = JSON.stringify(\n cssToReactNativeRuntime(codeIn, { inlineRem: 16 })\n );\n const code = `require(\"nativewind/dist/index.js\").require().StyleSheet.registerCompiled(${data})`;\n const newId = `${id}.js`;\n const cssId = newId.replace(rolldownNodeMods + sep, \"\");\n cssTransformCache.set(cssId, code);\n return {\n code,\n id: newId,\n map: null\n };\n }\n }\n }\n },\n generateBundle(_, bundle) {\n const environment = getEnvName(this.environment.name);\n if (configuration.enableNativeCSS && (environment === \"ios\" || environment === \"android\")) {\n const rootJSName = Object.keys(bundle).find((i) => {\n const chunk = bundle[i];\n return chunk.type == \"chunk\" && chunk.fileName.match(/.[cm]?js(?:\\?.+)?$/) != null;\n });\n if (!rootJSName) {\n throw new Error(`Can't find root js, internal one error`);\n }\n const rootJS = bundle[rootJSName];\n const cssAssets = Object.keys(bundle).filter(\n (i) => bundle[i].fileName.endsWith(\".css.js\")\n );\n for (const name of cssAssets) {\n delete bundle[name];\n const jsCSS = cssTransformCache.get(name);\n rootJS.code = `\n${jsCSS}\n${rootJS.code}\n`;\n }\n }\n }\n },\n {\n name: \"one:compiler\",\n enforce: \"pre\",\n config: () => {\n const nodeModulesFilter = /node_modules[/\\\\].*\\.(tsx?|jsx?|mjs|cjs)$/;\n const createEnvironmentConfig = (environment) => {\n if (!perfStats.optimizeDeps.byEnvironment[environment]) {\n perfStats.optimizeDeps.byEnvironment[environment] = {\n filesChecked: 0,\n filesTransformed: 0,\n startTime: Date.now()\n };\n }\n return {\n optimizeDeps: {\n rolldownOptions: {\n plugins: [\n {\n name: `transform-before-optimize-deps-${environment}`,\n async transform(code, id) {\n if (!nodeModulesFilter.test(id)) {\n return null;\n }\n perfStats.optimizeDeps.byEnvironment[environment].filesChecked++;\n const production = process.env.NODE_ENV === \"production\" || process.env.NODE_ENV === \"test\";\n debug?.(`[rolldown optimizeDeps] ${id}`);\n const result = await performBabelTransform({\n id,\n code,\n projectRoot: config.root,\n environment,\n production,\n reactForRNVersion,\n optionsIn\n });\n if (!result) {\n return null;\n }\n perfStats.optimizeDeps.byEnvironment[environment].filesTransformed++;\n return {\n code: result.code,\n map: result.map\n };\n },\n buildEnd() {\n if (process.env.DEBUG_COMPILER_PERF) {\n const stats = perfStats.optimizeDeps.byEnvironment[environment];\n const elapsed = Date.now() - stats.startTime;\n console.info(\n `[optimizeDeps ${environment}] Done: ${stats.filesChecked} files checked, ${stats.filesTransformed} transformed (${elapsed}ms)`\n );\n }\n const allDone = Object.keys(perfStats.optimizeDeps.byEnvironment).length >= 2;\n if (allDone) {\n logCacheStats();\n logPerfSummary();\n }\n }\n }\n ]\n }\n },\n define: {\n \"process.env.NATIVEWIND_OS\": JSON.stringify(\n environment === \"ios\" || environment === \"android\" ? \"native\" : \"web\"\n )\n }\n };\n };\n return {\n environments: {\n ios: createEnvironmentConfig(\"ios\"),\n android: createEnvironmentConfig(\"android\"),\n client: createEnvironmentConfig(\"client\"),\n ssr: createEnvironmentConfig(\"ssr\")\n }\n };\n },\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n },\n async transform(codeIn, _id) {\n let code = codeIn;\n const environment = getEnvName(this.environment.name);\n const isNative = environment === \"ios\" || environment === \"android\";\n const production = config.command === \"build\" || process.env.NODE_ENV === \"production\" || JSON.parse(\n this.environment.config?.define?.[\"process.env.NODE_ENV\"] || '\"\"'\n ) === \"production\";\n const isEntry = _id.includes(\"one-entry-native\");\n if (isEntry) {\n if (isNative && !production) {\n code = `import '@vxrn/vite-native-client'\n${code}`;\n }\n if (isNative && configuration.enableNativewind) {\n code = `import * as x from 'nativewind'\n${code}`;\n }\n return code;\n }\n const id = _id.split(\"?\")[0];\n const extension = extname(id);\n if (extension === \".css\" || !validParsers.has(extension)) {\n return;\n }\n if (id.includes(`virtual:`)) {\n return;\n }\n if (codeIn.endsWith(`// vxrn-did-babel`)) {\n debug?.(`[skip babel] ${id}`);\n return;\n }\n return performBabelTransform({\n id,\n code: codeIn,\n projectRoot: config.root,\n environment,\n production,\n reactForRNVersion,\n optionsIn\n });\n }\n },\n // wraps client-side TSX/JSX with React Refresh preamble + import.meta.hot.accept\n // runs after vite:oxc (no enforce:'pre') so it sees the already-transformed code\n {\n name: \"one:react-refresh-web\",\n apply: \"serve\",\n transform(code, _id) {\n if (this.environment.name !== \"client\") return;\n if (code.includes(runtimePublicPath)) return;\n if (/[?&](?:worker|sharedworker|raw|url)\\b/.test(_id)) return;\n const id = _id.split(\"?\")[0];\n if (id.includes(\"node_modules\")) return;\n if (id.includes(\"virtual:\")) return;\n if (id === runtimePublicPath) return;\n const ext = extname(id);\n if (ext !== \".tsx\" && ext !== \".jsx\") return;\n const hasRefreshCalls = /\\$RefreshReg\\$\\(/.test(code);\n let out = `import * as RefreshRuntime from \"${runtimePublicPath}\";\n\n`;\n if (hasRefreshCalls) {\n out += `if (!window.$RefreshReg$) throw new Error(\"React refresh preamble was not loaded. Something is wrong.\");\nconst prevRefreshReg = window.$RefreshReg$;\nconst prevRefreshSig = window.$RefreshSig$;\nwindow.$RefreshReg$ = RefreshRuntime.getRefreshReg(\"${id}\");\nwindow.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;\n\n`;\n }\n out += code;\n if (hasRefreshCalls) {\n out += `\n\nwindow.$RefreshReg$ = prevRefreshReg;\nwindow.$RefreshSig$ = prevRefreshSig;\n`;\n }\n out += `\nRefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {\n RefreshRuntime.registerExportsForReactRefresh(\"${id}\", currentExports);\n import.meta.hot.accept((nextExports) => {\n if (!nextExports) return;\n const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(\"${id}\", currentExports, nextExports);\n if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);\n });\n});\n`;\n return { code: out, map: null };\n }\n }\n ];\n}\nexport {\n JS_GLOBALS,\n clearTransformCache,\n createVXRNCompilerPlugin,\n getClosureVariables\n};\n//# sourceMappingURL=index.js.map\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAM,YAAY;CAChB,OAAO;EACL,YAAY;EACZ,iBAAiB;EACjB,WAAW;EACX,eAAe,CAAC;CAClB;CACA,cAAc,EACZ,eAAe,CAAC,EAClB;AACF;AACA,SAAS,iBAAiB;CACxB,IAAI,CAAC,QAAQ,IAAI,qBAAqB;EACpC;CACF;CACA,QAAQ,KAAK,qCAA4C;CACzD,QAAQ,KACN,UAAU,UAAU,MAAM,gBAAgB,gBAAgB,UAAU,MAAM,WAAW,WAAW,UAAU,MAAM,kBAAkB,KAAK,IAAI,UAAU,MAAM,YAAY,CAAC,IAAI,IAAG,CAAE,QAAQ,CAAC,EAAE,kBAC9L;CACA,QAAQ,KAAK,qBAAqB,UAAU,MAAM,UAAU,GAAG;CAC/D,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,UAAU,MAAM,aAAa,GAAG;EACxE,IAAI,MAAM,aAAa,GAAG;GACxB,QAAQ,KACN,KAAK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@ function readCommands(call, decls) {
|
|
|
288
288
|
for (const m of commandMembers) {
|
|
289
289
|
const name = m.key?.name ?? m.key?.value;
|
|
290
290
|
if (!name) continue;
|
|
291
|
-
const fn = m.typeAnnotation?.typeAnnotation ?? m.value ?? m.typeAnnotation;
|
|
291
|
+
const fn = m.type === "TSMethodSignature" ? m : m.typeAnnotation?.typeAnnotation ?? m.value ?? m.typeAnnotation;
|
|
292
292
|
const params = (fn?.params ?? fn?.parameters ?? []).slice(1);
|
|
293
293
|
byName.set(name, params.map((p, i) => p.name?.name ?? p.name ?? `arg${i}`));
|
|
294
294
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reactNativeViewConfig.js","names":[],"sources":["esm/reactNativeViewConfig.js"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport { basename, join } from \"node:path\";\nimport { parseSync } from \"oxc-parser\";\nconst SELF_URL = typeof __filename !== \"undefined\" ? __filename : import.meta.url;\nconst COLOR_ATTRIBUTE = \"require('react-native/Libraries/Components/View/ReactNativeStyleAttributes').colorAttribute\";\nconst COLOR_ARRAY_ATTRIBUTE = \"{\\n process: (req => 'default' in req ? req.default : req)(require('react-native/Libraries/StyleSheet/processColorArray'))\\n }\";\nconst IMAGE_ATTRIBUTE = \"{\\n process: (req => 'default' in req ? req.default : req)(require('react-native/Libraries/Image/resolveAssetSource'))\\n }\";\nconst POINT_ATTRIBUTE = \"{\\n diff: (req => 'default' in req ? req.default : req)(require('react-native/Libraries/Utilities/differ/pointsDiffer'))\\n }\";\nconst EDGE_INSETS_ATTRIBUTE = \"{\\n diff: (req => 'default' in req ? req.default : req)(require('react-native/Libraries/Utilities/differ/insetsDiffer'))\\n }\";\nconst IMPORT_REGISTRY = \"const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry');\";\nconst IMPORT_IGNORE = \"const {ConditionallyIgnoredEventHandlers} = require('react-native/Libraries/NativeComponent/ViewConfigIgnore');\";\nconst IMPORT_DISPATCH = 'const {dispatchCommand} = require(\"react-native/Libraries/ReactNative/RendererProxy\");';\nconst IMPORT_UIMANAGER = 'const {UIManager} = require(\"react-native\")';\nlet hermesParser = void 0;\nfunction getHermesParser(projectRoot) {\n if (hermesParser === void 0) {\n try {\n const req = projectRoot ? createRequire(join(projectRoot, \"package.json\")) : createRequire(SELF_URL);\n hermesParser = req(\"hermes-parser\");\n } catch {\n try {\n hermesParser = createRequire(SELF_URL)(\"hermes-parser\");\n } catch {\n hermesParser = null;\n }\n }\n }\n return hermesParser;\n}\nfunction readType(node) {\n if (!node) return { name: \"\", args: [] };\n switch (node.type) {\n // flow\n case \"NullableTypeAnnotation\":\n case \"TypeAnnotation\":\n return readType(node.typeAnnotation);\n case \"GenericTypeAnnotation\":\n return {\n name: readTypeName(node.id),\n args: (node.typeParameters?.params ?? []).map(readType)\n };\n case \"ObjectTypeAnnotation\":\n return { name: \"__object\", args: [] };\n case \"StringTypeAnnotation\":\n return { name: \"string\", args: [] };\n case \"BooleanTypeAnnotation\":\n return { name: \"boolean\", args: [] };\n case \"NumberTypeAnnotation\":\n return { name: \"number\", args: [] };\n case \"UnionTypeAnnotation\":\n return readUnion(node);\n case \"FunctionTypeAnnotation\":\n return { name: \"__function\", args: [] };\n // typescript\n case \"TSTypeAnnotation\":\n return readType(node.typeAnnotation);\n case \"TSTypeReference\":\n return {\n name: readTypeName(node.typeName),\n args: (node.typeArguments ?? node.typeParameters)?.params?.map(readType) ?? []\n };\n case \"TSTypeLiteral\":\n return { name: \"__object\", args: [] };\n case \"TSStringKeyword\":\n return { name: \"string\", args: [] };\n case \"TSBooleanKeyword\":\n return { name: \"boolean\", args: [] };\n case \"TSNumberKeyword\":\n return { name: \"number\", args: [] };\n case \"TSUnionType\":\n return readUnion(node);\n case \"TSFunctionType\":\n return { name: \"__function\", args: [] };\n case \"TSArrayType\":\n return { name: \"Array\", args: [readType(node.elementType)] };\n }\n return { name: \"__unknown\", args: [] };\n}\nconst NULLISH_TYPES = /* @__PURE__ */ new Set([\n \"TSUndefinedKeyword\",\n \"TSNullKeyword\",\n \"TSVoidKeyword\",\n \"NullLiteralTypeAnnotation\",\n \"VoidTypeAnnotation\"\n]);\nfunction readUnion(node) {\n const real = (node.types ?? []).filter((t) => !NULLISH_TYPES.has(t.type));\n if (real.length === 1) return readType(real[0]);\n return { name: \"__union\", args: [] };\n}\nfunction readTypeName(id) {\n if (!id) return \"\";\n if (id.type === \"Identifier\") return id.name;\n if (id.type === \"QualifiedTypeIdentifier\") return readTypeName(id.id);\n if (id.type === \"TSQualifiedName\") return readTypeName(id.right);\n return \"\";\n}\nconst READONLY_ARRAYS = /* @__PURE__ */ new Set([\"ReadonlyArray\", \"$ReadOnlyArray\", \"Array\"]);\nconst TRANSPARENT = /* @__PURE__ */ new Set([\"WithDefault\", \"UnsafeMixed\", \"Readonly\", \"$ReadOnly\"]);\nfunction unwrap(type) {\n let cur = type;\n while (TRANSPARENT.has(cur.name) && cur.args.length > 0) {\n cur = cur.args[0];\n }\n return cur;\n}\nfunction attributeValue(type) {\n const t = unwrap(type);\n switch (t.name) {\n case \"ColorValue\":\n case \"ProcessedColorValue\":\n return COLOR_ATTRIBUTE;\n case \"ImageSource\":\n return IMAGE_ATTRIBUTE;\n case \"PointValue\":\n return POINT_ATTRIBUTE;\n case \"EdgeInsetsValue\":\n return EDGE_INSETS_ATTRIBUTE;\n }\n if (READONLY_ARRAYS.has(t.name) && t.args.length === 1) {\n const el = unwrap(t.args[0]);\n if (el.name === \"ColorValue\" || el.name === \"ProcessedColorValue\") {\n return COLOR_ARRAY_ATTRIBUTE;\n }\n }\n return \"true\";\n}\nfunction eventOf(name, type) {\n const t = unwrap(type);\n if (t.name !== \"DirectEventHandler\" && t.name !== \"BubblingEventHandler\") return null;\n const override = t.args[1]?.name;\n return {\n name,\n bubbling: t.name === \"BubblingEventHandler\",\n topName: normalizeInputEventName(\n override && override !== \"__unknown\" ? override : name\n )\n };\n}\nfunction normalizeInputEventName(name) {\n if (name.startsWith(\"on\")) return name.replace(/^on/, \"top\");\n if (!name.startsWith(\"top\")) return `top${name[0].toUpperCase()}${name.slice(1)}`;\n return name;\n}\nfunction collectDeclarations(body) {\n const out = /* @__PURE__ */ new Map();\n for (const raw of body) {\n const node = raw?.type === \"ExportNamedDeclaration\" ? raw.declaration : raw;\n if (!node) continue;\n switch (node.type) {\n case \"TSTypeAliasDeclaration\":\n case \"TypeAlias\":\n case \"TSInterfaceDeclaration\":\n case \"InterfaceDeclaration\":\n if (node.id?.name) out.set(node.id.name, node);\n break;\n }\n }\n return out;\n}\nfunction flattenMembers(typeName, decls, seen = /* @__PURE__ */ new Set()) {\n if (typeName === \"ViewProps\" || seen.has(typeName)) return [];\n seen.add(typeName);\n const decl = decls.get(typeName);\n if (!decl) return [];\n const out = [];\n const heritage = decl.extends ?? decl.heritage ?? [];\n for (const h of heritage) {\n const name = readTypeName(h.id ?? h.expression ?? h.typeName);\n if (name) out.push(...flattenMembers(name, decls, seen));\n }\n const bodyNode = decl.body ?? // interface\n decl.right ?? // type alias\n decl.typeAnnotation;\n out.push(...readObjectMembers(bodyNode, decls, seen));\n return out;\n}\nfunction readObjectMembers(node, decls, seen) {\n if (!node) return [];\n if (node.type === \"TSTypeReference\" || node.type === \"GenericTypeAnnotation\") {\n const name = readTypeName(node.typeName ?? node.id);\n const args = (node.typeArguments ?? node.typeParameters)?.params ?? [];\n if (TRANSPARENT.has(name) && args.length) {\n return readObjectMembers(args[0], decls, seen);\n }\n return flattenMembers(name, decls, seen);\n }\n if (node.type === \"TSIntersectionType\" || node.type === \"IntersectionTypeAnnotation\") {\n const out2 = [];\n for (const t of node.types ?? []) out2.push(...readObjectMembers(t, decls, seen));\n return out2;\n }\n const members = node.members ?? node.body ?? node.properties ?? [];\n const out = [];\n for (const m of members) {\n switch (m.type) {\n case \"TSPropertySignature\":\n case \"ObjectTypeProperty\": {\n const name = m.key?.name ?? m.key?.value;\n if (!name) break;\n out.push({ name, type: readType(m.typeAnnotation ?? m.value) });\n break;\n }\n // flow's `...OtherProps` inside an object type\n case \"ObjectTypeSpreadProperty\": {\n const name = readTypeName(m.argument?.id ?? m.argument);\n if (name) out.push(...flattenMembers(name, decls, seen));\n break;\n }\n }\n }\n return out;\n}\nfunction findComponentCall(body) {\n for (const node of body) {\n if (node.type !== \"ExportDefaultDeclaration\") continue;\n let expr = node.declaration;\n while (expr) {\n if (expr.type === \"CallExpression\") break;\n expr = expr.expression ?? (expr.type === \"SequenceExpression\" ? expr.expressions[expr.expressions.length - 1] : null);\n }\n if (expr?.type === \"CallExpression\" && expr.callee?.name === \"codegenNativeComponent\") {\n return expr;\n }\n }\n return null;\n}\nfunction findCommandsCall(body) {\n for (const raw of body) {\n const node = raw?.type === \"ExportNamedDeclaration\" ? raw.declaration : raw;\n const decl = node?.declarations?.[0];\n let init = decl?.init;\n while (init && init.type !== \"CallExpression\") init = init.expression;\n if (init?.type === \"CallExpression\" && init.callee?.name === \"codegenNativeCommands\") {\n return init;\n }\n }\n return null;\n}\nfunction readStringOption(objectExpression, key) {\n for (const p of objectExpression?.properties ?? []) {\n if ((p.key?.name ?? p.key?.value) === key && typeof p.value?.value === \"string\") {\n return p.value.value;\n }\n }\n return null;\n}\nfunction readCommands(call, decls) {\n const typeName = readTypeName(\n (call.typeArguments ?? call.typeParameters)?.params?.[0]?.typeName ?? (call.typeArguments ?? call.typeParameters)?.params?.[0]?.id\n );\n const supported = [];\n for (const p of call.arguments?.[0]?.properties ?? []) {\n if ((p.key?.name ?? p.key?.value) !== \"supportedCommands\") continue;\n for (const el of p.value?.elements ?? []) {\n if (typeof el?.value === \"string\") supported.push(el.value);\n }\n }\n if (!supported.length) return [];\n const decl = decls.get(typeName);\n const byName = /* @__PURE__ */ new Map();\n const commandMembers = decl?.body?.body ?? decl?.body?.members ?? decl?.body?.properties ?? [];\n for (const m of commandMembers) {\n const name = m.key?.name ?? m.key?.value;\n if (!name) continue;\n const fn = m.typeAnnotation?.typeAnnotation ?? m.value ?? m.typeAnnotation;\n const params = (fn?.params ?? fn?.parameters ?? []).slice(1);\n byName.set(\n name,\n params.map((p, i) => p.name?.name ?? p.name ?? `arg${i}`)\n );\n }\n return supported.map((name) => ({ name, params: byName.get(name) ?? [] }));\n}\nfunction indent(text, spaces) {\n const pad = \" \".repeat(spaces);\n return text.split(\"\\n\").map((line, i) => i === 0 || line === \"\" ? line : pad + line).join(\"\\n\");\n}\nfunction printViewConfig(componentName, attributes, events) {\n const lines = [` uiViewClassName: ${JSON.stringify(componentName)}`];\n const bubbling = events.filter((e) => e.bubbling);\n if (bubbling.length) {\n lines.push(\n ` bubblingEventTypes: {\n${bubbling.map(\n (e) => ` ${e.topName}: {\n phasedRegistrationNames: {\n captured: ${JSON.stringify(\n `${e.name}Capture`\n )},\n bubbled: ${JSON.stringify(e.name)}\n }\n }`\n ).join(\",\\n\")}\n }`\n );\n }\n const direct = events.filter((e) => !e.bubbling);\n if (direct.length) {\n lines.push(\n ` directEventTypes: {\n${direct.map(\n (e) => ` ${e.topName}: {\n registrationName: ${JSON.stringify(e.name)}\n }`\n ).join(\",\\n\")}\n }`\n );\n }\n const attrLines = attributes.map((a) => ` ${a.name}: ${indent(a.value, 4)}`);\n if (events.length) {\n attrLines.push(\n ` ...ConditionallyIgnoredEventHandlers({\n${events.map((e) => ` ${e.name}: true`).join(\",\\n\")}\n })`\n );\n }\n lines.push(\n attrLines.length ? ` validAttributes: {\n${attrLines.join(\",\\n\")}\n }` : \" validAttributes: {}\"\n );\n return `{\n${lines.join(\",\\n\")}\n}`;\n}\nfunction printCommands(commands) {\n return `export const Commands = {\n${commands.map(\n (c) => ` ${c.name}(ref${c.params.map((p) => `, ${p}`).join(\"\")}) {\n dispatchCommand(ref, ${JSON.stringify(\n c.name\n )}, [${c.params.join(\", \")}]);\n }`\n ).join(\",\\n\")}\n};`;\n}\nconst FILE_HEADER = `/**\n * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).\n *\n * Do not edit this file as changes may cause incorrect behavior and will be lost\n * once the code is regenerated.\n *\n * @flow\n *\n * @generated by codegen project: GenerateViewConfigJs.js\n */\n\n'use strict';\n`;\nfunction parseSpec(code, filename, projectRoot) {\n const isTS = /\\.[cm]?tsx?$/.test(filename);\n if (isTS) {\n const result = parseSync(filename, code, {\n lang: filename.endsWith(\"x\") ? \"tsx\" : \"ts\"\n });\n if (result.errors?.length) return null;\n return result.program;\n }\n const hermes = getHermesParser(projectRoot);\n if (!hermes) return null;\n try {\n return hermes.parse(code, {\n babel: false,\n flow: \"all\",\n sourceFilename: filename\n });\n } catch {\n return null;\n }\n}\nfunction generateViewConfig(program) {\n const body = program?.body;\n if (!body) return null;\n const call = findComponentCall(body);\n if (!call) return null;\n const componentNameArg = call.arguments?.[0];\n if (typeof componentNameArg?.value !== \"string\") return null;\n const componentName = componentNameArg.value;\n const options = call.arguments?.[1];\n const paperComponentName = readStringOption(options, \"paperComponentName\");\n const paperComponentNameDeprecated = readStringOption(\n options,\n \"paperComponentNameDeprecated\"\n );\n const propsTypeName = readTypeName(\n (call.typeArguments ?? call.typeParameters)?.params?.[0]?.typeName ?? (call.typeArguments ?? call.typeParameters)?.params?.[0]?.id\n );\n if (!propsTypeName) return null;\n const decls = collectDeclarations(body);\n const members = flattenMembers(propsTypeName, decls);\n const attributes = [];\n const events = [];\n for (const m of members) {\n const event = eventOf(m.name, m.type);\n if (event) {\n events.push(event);\n continue;\n }\n attributes.push({ name: m.name, value: attributeValue(m.type) });\n }\n const commandsCall = findCommandsCall(body);\n const commands = commandsCall ? readCommands(commandsCall, decls) : [];\n const imports = /* @__PURE__ */ new Set([IMPORT_REGISTRY]);\n if (events.length) imports.add(IMPORT_IGNORE);\n if (commands.length) imports.add(IMPORT_DISPATCH);\n if (paperComponentNameDeprecated) imports.add(IMPORT_UIMANAGER);\n const nativeName = paperComponentName ?? componentName;\n const parts = [`let nativeComponentName = '${nativeName}';`];\n if (paperComponentNameDeprecated) {\n parts.push(\n `if (UIManager.hasViewManagerConfig('${componentName}')) {\n nativeComponentName = '${componentName}';\n} else if (UIManager.hasViewManagerConfig('${paperComponentNameDeprecated}')) {\n nativeComponentName = '${paperComponentNameDeprecated}';\n} else {\n throw new Error('Failed to find native component for either \"${componentName}\" or \"${paperComponentNameDeprecated}\"');\n}`\n );\n }\n parts.push(\n `export const __INTERNAL_VIEW_CONFIG = ${printViewConfig(nativeName, attributes, events)};`\n );\n parts.push(\n \"export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG);\"\n );\n if (commands.length) parts.push(printCommands(commands));\n return { imports: [...imports].sort(), body: parts.join(\"\\n\") };\n}\nfunction renderViewConfigModule(result) {\n return `\n${FILE_HEADER}\n${result.imports.join(\"\\n\")}\n\n${result.body}\n`;\n}\nfunction getLibraryName(filename) {\n const base = basename(filename);\n const replaced = base.replace(/NativeComponent\\.[cm]?[jt]sx?$/, \"\");\n return replaced === base ? base.replace(/\\.[cm]?[jt]sx?$/, \"\") : replaced;\n}\nexport {\n generateViewConfig,\n getLibraryName,\n parseSpec,\n renderViewConfigModule\n};\n//# sourceMappingURL=reactNativeViewConfig.js.map\n"],"mappings":";;;;;AAGA,MAAM,WAAW,OAAO,eAAe,cAAc,aAAa,YAAY;AAC9E,MAAM,kBAAkB;AACxB,MAAM,wBAAwB;AAC9B,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AACxB,MAAM,wBAAwB;AAC9B,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,IAAI,eAAe,KAAK;AACxB,SAAS,gBAAgB,aAAa;CACpC,IAAI,iBAAiB,KAAK,GAAG;EAC3B,IAAI;GACF,MAAM,MAAM,cAAc,cAAc,KAAK,aAAa,cAAc,CAAC,IAAI,cAAc,QAAQ;GACnG,eAAe,IAAI,eAAe;EACpC,QAAQ;GACN,IAAI;IACF,eAAe,cAAc,QAAQ,CAAC,CAAC,eAAe;GACxD,QAAQ;IACN,eAAe;GACjB;EACF;CACF;CACA,OAA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AI,eAAe;CAChD,IAAI,8BAA8B,QAAQ,IAAI,gBAAgB;CAC9D,MAAM,aAAa,sBAAsB;CACzC,MAAM,QAAQ,CAAC,8BAA8B,WAAW,GAAG;CAC3D,IAAI,8BAA8B;EAChC,MAAM,KACJ,uCAAuC,cAAc;2BAChC,cAAc;6CACI,6BAA6B;2BAC/C,6BAA6B;;iEAES,cAAc,QAAQ,6BAA6B;EAEhH;CACF;CACA,MAAM,KACJ,yCAAyC,gBAAgB,YAAY,YAAY,MAAM,EAAE,EAC3F;CACA,MAAM,KACJ,gGACF;CACA,IAAI,SAAS,QAAQ,MAAM,KAAK,cAAc,QAAQ,CAAC;CACvD,OAAO;EAAE,SAAS,CAAC,GAAG,OAAO,CAAC,CAAC,KAAK;EAAG,MAAM,MAAM,KAAK,IAAI;CAAE;AAChE;AACA,SAAS,uBAAuB,QAAQ;CACtC,OAAO;EACP,YAAY;EACZ,OAAO,QAAQ,KAAK,IAAI,EAAE;;EAE1B,OAAO,KAAK;;AAEd;AACA,SAAS,eAAe,UAAU;CAChC,MAAM,OAAO,SAAS,QAAQ;CAC9B,MAAM,WAAW,KAAK,QAAQ,kCAAkC,EAAE;CAClE,OAAO,aAAa,OAAO,KAAK,QAAQ,mBAAmB,EAAE,IAAI;AACnE"}
|
|
1
|
+
{"version":3,"file":"reactNativeViewConfig.js","names":[],"sources":["esm/reactNativeViewConfig.js"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport { basename, join } from \"node:path\";\nimport { parseSync } from \"oxc-parser\";\nconst SELF_URL = typeof __filename !== \"undefined\" ? __filename : import.meta.url;\nconst COLOR_ATTRIBUTE = \"require('react-native/Libraries/Components/View/ReactNativeStyleAttributes').colorAttribute\";\nconst COLOR_ARRAY_ATTRIBUTE = \"{\\n process: (req => 'default' in req ? req.default : req)(require('react-native/Libraries/StyleSheet/processColorArray'))\\n }\";\nconst IMAGE_ATTRIBUTE = \"{\\n process: (req => 'default' in req ? req.default : req)(require('react-native/Libraries/Image/resolveAssetSource'))\\n }\";\nconst POINT_ATTRIBUTE = \"{\\n diff: (req => 'default' in req ? req.default : req)(require('react-native/Libraries/Utilities/differ/pointsDiffer'))\\n }\";\nconst EDGE_INSETS_ATTRIBUTE = \"{\\n diff: (req => 'default' in req ? req.default : req)(require('react-native/Libraries/Utilities/differ/insetsDiffer'))\\n }\";\nconst IMPORT_REGISTRY = \"const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry');\";\nconst IMPORT_IGNORE = \"const {ConditionallyIgnoredEventHandlers} = require('react-native/Libraries/NativeComponent/ViewConfigIgnore');\";\nconst IMPORT_DISPATCH = 'const {dispatchCommand} = require(\"react-native/Libraries/ReactNative/RendererProxy\");';\nconst IMPORT_UIMANAGER = 'const {UIManager} = require(\"react-native\")';\nlet hermesParser = void 0;\nfunction getHermesParser(projectRoot) {\n if (hermesParser === void 0) {\n try {\n const req = projectRoot ? createRequire(join(projectRoot, \"package.json\")) : createRequire(SELF_URL);\n hermesParser = req(\"hermes-parser\");\n } catch {\n try {\n hermesParser = createRequire(SELF_URL)(\"hermes-parser\");\n } catch {\n hermesParser = null;\n }\n }\n }\n return hermesParser;\n}\nfunction readType(node) {\n if (!node) return { name: \"\", args: [] };\n switch (node.type) {\n // flow\n case \"NullableTypeAnnotation\":\n case \"TypeAnnotation\":\n return readType(node.typeAnnotation);\n case \"GenericTypeAnnotation\":\n return {\n name: readTypeName(node.id),\n args: (node.typeParameters?.params ?? []).map(readType)\n };\n case \"ObjectTypeAnnotation\":\n return { name: \"__object\", args: [] };\n case \"StringTypeAnnotation\":\n return { name: \"string\", args: [] };\n case \"BooleanTypeAnnotation\":\n return { name: \"boolean\", args: [] };\n case \"NumberTypeAnnotation\":\n return { name: \"number\", args: [] };\n case \"UnionTypeAnnotation\":\n return readUnion(node);\n case \"FunctionTypeAnnotation\":\n return { name: \"__function\", args: [] };\n // typescript\n case \"TSTypeAnnotation\":\n return readType(node.typeAnnotation);\n case \"TSTypeReference\":\n return {\n name: readTypeName(node.typeName),\n args: (node.typeArguments ?? node.typeParameters)?.params?.map(readType) ?? []\n };\n case \"TSTypeLiteral\":\n return { name: \"__object\", args: [] };\n case \"TSStringKeyword\":\n return { name: \"string\", args: [] };\n case \"TSBooleanKeyword\":\n return { name: \"boolean\", args: [] };\n case \"TSNumberKeyword\":\n return { name: \"number\", args: [] };\n case \"TSUnionType\":\n return readUnion(node);\n case \"TSFunctionType\":\n return { name: \"__function\", args: [] };\n case \"TSArrayType\":\n return { name: \"Array\", args: [readType(node.elementType)] };\n }\n return { name: \"__unknown\", args: [] };\n}\nconst NULLISH_TYPES = /* @__PURE__ */ new Set([\n \"TSUndefinedKeyword\",\n \"TSNullKeyword\",\n \"TSVoidKeyword\",\n \"NullLiteralTypeAnnotation\",\n \"VoidTypeAnnotation\"\n]);\nfunction readUnion(node) {\n const real = (node.types ?? []).filter((t) => !NULLISH_TYPES.has(t.type));\n if (real.length === 1) return readType(real[0]);\n return { name: \"__union\", args: [] };\n}\nfunction readTypeName(id) {\n if (!id) return \"\";\n if (id.type === \"Identifier\") return id.name;\n if (id.type === \"QualifiedTypeIdentifier\") return readTypeName(id.id);\n if (id.type === \"TSQualifiedName\") return readTypeName(id.right);\n return \"\";\n}\nconst READONLY_ARRAYS = /* @__PURE__ */ new Set([\"ReadonlyArray\", \"$ReadOnlyArray\", \"Array\"]);\nconst TRANSPARENT = /* @__PURE__ */ new Set([\"WithDefault\", \"UnsafeMixed\", \"Readonly\", \"$ReadOnly\"]);\nfunction unwrap(type) {\n let cur = type;\n while (TRANSPARENT.has(cur.name) && cur.args.length > 0) {\n cur = cur.args[0];\n }\n return cur;\n}\nfunction attributeValue(type) {\n const t = unwrap(type);\n switch (t.name) {\n case \"ColorValue\":\n case \"ProcessedColorValue\":\n return COLOR_ATTRIBUTE;\n case \"ImageSource\":\n return IMAGE_ATTRIBUTE;\n case \"PointValue\":\n return POINT_ATTRIBUTE;\n case \"EdgeInsetsValue\":\n return EDGE_INSETS_ATTRIBUTE;\n }\n if (READONLY_ARRAYS.has(t.name) && t.args.length === 1) {\n const el = unwrap(t.args[0]);\n if (el.name === \"ColorValue\" || el.name === \"ProcessedColorValue\") {\n return COLOR_ARRAY_ATTRIBUTE;\n }\n }\n return \"true\";\n}\nfunction eventOf(name, type) {\n const t = unwrap(type);\n if (t.name !== \"DirectEventHandler\" && t.name !== \"BubblingEventHandler\") return null;\n const override = t.args[1]?.name;\n return {\n name,\n bubbling: t.name === \"BubblingEventHandler\",\n topName: normalizeInputEventName(\n override && override !== \"__unknown\" ? override : name\n )\n };\n}\nfunction normalizeInputEventName(name) {\n if (name.startsWith(\"on\")) return name.replace(/^on/, \"top\");\n if (!name.startsWith(\"top\")) return `top${name[0].toUpperCase()}${name.slice(1)}`;\n return name;\n}\nfunction collectDeclarations(body) {\n const out = /* @__PURE__ */ new Map();\n for (const raw of body) {\n const node = raw?.type === \"ExportNamedDeclaration\" ? raw.declaration : raw;\n if (!node) continue;\n switch (node.type) {\n case \"TSTypeAliasDeclaration\":\n case \"TypeAlias\":\n case \"TSInterfaceDeclaration\":\n case \"InterfaceDeclaration\":\n if (node.id?.name) out.set(node.id.name, node);\n break;\n }\n }\n return out;\n}\nfunction flattenMembers(typeName, decls, seen = /* @__PURE__ */ new Set()) {\n if (typeName === \"ViewProps\" || seen.has(typeName)) return [];\n seen.add(typeName);\n const decl = decls.get(typeName);\n if (!decl) return [];\n const out = [];\n const heritage = decl.extends ?? decl.heritage ?? [];\n for (const h of heritage) {\n const name = readTypeName(h.id ?? h.expression ?? h.typeName);\n if (name) out.push(...flattenMembers(name, decls, seen));\n }\n const bodyNode = decl.body ?? // interface\n decl.right ?? // type alias\n decl.typeAnnotation;\n out.push(...readObjectMembers(bodyNode, decls, seen));\n return out;\n}\nfunction readObjectMembers(node, decls, seen) {\n if (!node) return [];\n if (node.type === \"TSTypeReference\" || node.type === \"GenericTypeAnnotation\") {\n const name = readTypeName(node.typeName ?? node.id);\n const args = (node.typeArguments ?? node.typeParameters)?.params ?? [];\n if (TRANSPARENT.has(name) && args.length) {\n return readObjectMembers(args[0], decls, seen);\n }\n return flattenMembers(name, decls, seen);\n }\n if (node.type === \"TSIntersectionType\" || node.type === \"IntersectionTypeAnnotation\") {\n const out2 = [];\n for (const t of node.types ?? []) out2.push(...readObjectMembers(t, decls, seen));\n return out2;\n }\n const members = node.members ?? node.body ?? node.properties ?? [];\n const out = [];\n for (const m of members) {\n switch (m.type) {\n case \"TSPropertySignature\":\n case \"ObjectTypeProperty\": {\n const name = m.key?.name ?? m.key?.value;\n if (!name) break;\n out.push({ name, type: readType(m.typeAnnotation ?? m.value) });\n break;\n }\n // flow's `...OtherProps` inside an object type\n case \"ObjectTypeSpreadProperty\": {\n const name = readTypeName(m.argument?.id ?? m.argument);\n if (name) out.push(...flattenMembers(name, decls, seen));\n break;\n }\n }\n }\n return out;\n}\nfunction findComponentCall(body) {\n for (const node of body) {\n if (node.type !== \"ExportDefaultDeclaration\") continue;\n let expr = node.declaration;\n while (expr) {\n if (expr.type === \"CallExpression\") break;\n expr = expr.expression ?? (expr.type === \"SequenceExpression\" ? expr.expressions[expr.expressions.length - 1] : null);\n }\n if (expr?.type === \"CallExpression\" && expr.callee?.name === \"codegenNativeComponent\") {\n return expr;\n }\n }\n return null;\n}\nfunction findCommandsCall(body) {\n for (const raw of body) {\n const node = raw?.type === \"ExportNamedDeclaration\" ? raw.declaration : raw;\n const decl = node?.declarations?.[0];\n let init = decl?.init;\n while (init && init.type !== \"CallExpression\") init = init.expression;\n if (init?.type === \"CallExpression\" && init.callee?.name === \"codegenNativeCommands\") {\n return init;\n }\n }\n return null;\n}\nfunction readStringOption(objectExpression, key) {\n for (const p of objectExpression?.properties ?? []) {\n if ((p.key?.name ?? p.key?.value) === key && typeof p.value?.value === \"string\") {\n return p.value.value;\n }\n }\n return null;\n}\nfunction readCommands(call, decls) {\n const typeName = readTypeName(\n (call.typeArguments ?? call.typeParameters)?.params?.[0]?.typeName ?? (call.typeArguments ?? call.typeParameters)?.params?.[0]?.id\n );\n const supported = [];\n for (const p of call.arguments?.[0]?.properties ?? []) {\n if ((p.key?.name ?? p.key?.value) !== \"supportedCommands\") continue;\n for (const el of p.value?.elements ?? []) {\n if (typeof el?.value === \"string\") supported.push(el.value);\n }\n }\n if (!supported.length) return [];\n const decl = decls.get(typeName);\n const byName = /* @__PURE__ */ new Map();\n const commandMembers = decl?.body?.body ?? decl?.body?.members ?? decl?.body?.properties ?? [];\n for (const m of commandMembers) {\n const name = m.key?.name ?? m.key?.value;\n if (!name) continue;\n const fn = m.type === \"TSMethodSignature\" ? m : m.typeAnnotation?.typeAnnotation ?? m.value ?? m.typeAnnotation;\n const params = (fn?.params ?? fn?.parameters ?? []).slice(1);\n byName.set(\n name,\n params.map((p, i) => p.name?.name ?? p.name ?? `arg${i}`)\n );\n }\n return supported.map((name) => ({ name, params: byName.get(name) ?? [] }));\n}\nfunction indent(text, spaces) {\n const pad = \" \".repeat(spaces);\n return text.split(\"\\n\").map((line, i) => i === 0 || line === \"\" ? line : pad + line).join(\"\\n\");\n}\nfunction printViewConfig(componentName, attributes, events) {\n const lines = [` uiViewClassName: ${JSON.stringify(componentName)}`];\n const bubbling = events.filter((e) => e.bubbling);\n if (bubbling.length) {\n lines.push(\n ` bubblingEventTypes: {\n${bubbling.map(\n (e) => ` ${e.topName}: {\n phasedRegistrationNames: {\n captured: ${JSON.stringify(\n `${e.name}Capture`\n )},\n bubbled: ${JSON.stringify(e.name)}\n }\n }`\n ).join(\",\\n\")}\n }`\n );\n }\n const direct = events.filter((e) => !e.bubbling);\n if (direct.length) {\n lines.push(\n ` directEventTypes: {\n${direct.map(\n (e) => ` ${e.topName}: {\n registrationName: ${JSON.stringify(e.name)}\n }`\n ).join(\",\\n\")}\n }`\n );\n }\n const attrLines = attributes.map((a) => ` ${a.name}: ${indent(a.value, 4)}`);\n if (events.length) {\n attrLines.push(\n ` ...ConditionallyIgnoredEventHandlers({\n${events.map((e) => ` ${e.name}: true`).join(\",\\n\")}\n })`\n );\n }\n lines.push(\n attrLines.length ? ` validAttributes: {\n${attrLines.join(\",\\n\")}\n }` : \" validAttributes: {}\"\n );\n return `{\n${lines.join(\",\\n\")}\n}`;\n}\nfunction printCommands(commands) {\n return `export const Commands = {\n${commands.map(\n (c) => ` ${c.name}(ref${c.params.map((p) => `, ${p}`).join(\"\")}) {\n dispatchCommand(ref, ${JSON.stringify(\n c.name\n )}, [${c.params.join(\", \")}]);\n }`\n ).join(\",\\n\")}\n};`;\n}\nconst FILE_HEADER = `/**\n * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).\n *\n * Do not edit this file as changes may cause incorrect behavior and will be lost\n * once the code is regenerated.\n *\n * @flow\n *\n * @generated by codegen project: GenerateViewConfigJs.js\n */\n\n'use strict';\n`;\nfunction parseSpec(code, filename, projectRoot) {\n const isTS = /\\.[cm]?tsx?$/.test(filename);\n if (isTS) {\n const result = parseSync(filename, code, {\n lang: filename.endsWith(\"x\") ? \"tsx\" : \"ts\"\n });\n if (result.errors?.length) return null;\n return result.program;\n }\n const hermes = getHermesParser(projectRoot);\n if (!hermes) return null;\n try {\n return hermes.parse(code, {\n babel: false,\n flow: \"all\",\n sourceFilename: filename\n });\n } catch {\n return null;\n }\n}\nfunction generateViewConfig(program) {\n const body = program?.body;\n if (!body) return null;\n const call = findComponentCall(body);\n if (!call) return null;\n const componentNameArg = call.arguments?.[0];\n if (typeof componentNameArg?.value !== \"string\") return null;\n const componentName = componentNameArg.value;\n const options = call.arguments?.[1];\n const paperComponentName = readStringOption(options, \"paperComponentName\");\n const paperComponentNameDeprecated = readStringOption(\n options,\n \"paperComponentNameDeprecated\"\n );\n const propsTypeName = readTypeName(\n (call.typeArguments ?? call.typeParameters)?.params?.[0]?.typeName ?? (call.typeArguments ?? call.typeParameters)?.params?.[0]?.id\n );\n if (!propsTypeName) return null;\n const decls = collectDeclarations(body);\n const members = flattenMembers(propsTypeName, decls);\n const attributes = [];\n const events = [];\n for (const m of members) {\n const event = eventOf(m.name, m.type);\n if (event) {\n events.push(event);\n continue;\n }\n attributes.push({ name: m.name, value: attributeValue(m.type) });\n }\n const commandsCall = findCommandsCall(body);\n const commands = commandsCall ? readCommands(commandsCall, decls) : [];\n const imports = /* @__PURE__ */ new Set([IMPORT_REGISTRY]);\n if (events.length) imports.add(IMPORT_IGNORE);\n if (commands.length) imports.add(IMPORT_DISPATCH);\n if (paperComponentNameDeprecated) imports.add(IMPORT_UIMANAGER);\n const nativeName = paperComponentName ?? componentName;\n const parts = [`let nativeComponentName = '${nativeName}';`];\n if (paperComponentNameDeprecated) {\n parts.push(\n `if (UIManager.hasViewManagerConfig('${componentName}')) {\n nativeComponentName = '${componentName}';\n} else if (UIManager.hasViewManagerConfig('${paperComponentNameDeprecated}')) {\n nativeComponentName = '${paperComponentNameDeprecated}';\n} else {\n throw new Error('Failed to find native component for either \"${componentName}\" or \"${paperComponentNameDeprecated}\"');\n}`\n );\n }\n parts.push(\n `export const __INTERNAL_VIEW_CONFIG = ${printViewConfig(nativeName, attributes, events)};`\n );\n parts.push(\n \"export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG);\"\n );\n if (commands.length) parts.push(printCommands(commands));\n return { imports: [...imports].sort(), body: parts.join(\"\\n\") };\n}\nfunction renderViewConfigModule(result) {\n return `\n${FILE_HEADER}\n${result.imports.join(\"\\n\")}\n\n${result.body}\n`;\n}\nfunction getLibraryName(filename) {\n const base = basename(filename);\n const replaced = base.replace(/NativeComponent\\.[cm]?[jt]sx?$/, \"\");\n return replaced === base ? base.replace(/\\.[cm]?[jt]sx?$/, \"\") : replaced;\n}\nexport {\n generateViewConfig,\n getLibraryName,\n parseSpec,\n renderViewConfigModule\n};\n//# sourceMappingURL=reactNativeViewConfig.js.map\n"],"mappings":";;;;;AAGA,MAAM,WAAW,OAAO,eAAe,cAAc,aAAa,YAAY;AAC9E,MAAM,kBAAkB;AACxB,MAAM,wBAAwB;AAC9B,MAAM,kBAAkB;AACxB,MAAM,k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}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
-
import { extname, join
|
|
2
|
+
import { extname, join } from "node:path";
|
|
3
3
|
import { resolvePath } from "@vxrn/utils";
|
|
4
4
|
import { normalizePath } from "vite";
|
|
5
5
|
import { configuration } from "./configure.mjs";
|
|
@@ -46,6 +46,7 @@ function getBabelOptions(props) {
|
|
|
46
46
|
if (typeof props.userSetting === "undefined" || typeof props.userSetting === "object" && props.userSetting.transform === "babel") {
|
|
47
47
|
if (props.userSetting?.excludeDefaultPlugins) {
|
|
48
48
|
return {
|
|
49
|
+
caller: getBabelCaller(props),
|
|
49
50
|
...props.userSetting,
|
|
50
51
|
...userBabelConfig ? {
|
|
51
52
|
configFile: userBabelConfig,
|
|
@@ -75,13 +76,6 @@ const getOptions = (props, force = false, userBabelConfig = null) => {
|
|
|
75
76
|
plugins.push(resolvePath("react-native-css-interop/dist/babel-plugin.js"));
|
|
76
77
|
}
|
|
77
78
|
}
|
|
78
|
-
if (enableNativewind || shouldBabelReanimated(props)) {
|
|
79
|
-
try {
|
|
80
|
-
const workletsPlugin = resolvePath("react-native-worklets/plugin", props.projectRoot);
|
|
81
|
-
debug?.(`Using babel worklets on file ${props.id}`);
|
|
82
|
-
plugins.push(workletsPlugin);
|
|
83
|
-
} catch {}
|
|
84
|
-
}
|
|
85
79
|
if (shouldBabelReactCompiler(props)) {
|
|
86
80
|
debug?.(`Using babel react compiler on file`);
|
|
87
81
|
plugins.push(getBabelReactCompilerPlugin(props));
|
|
@@ -89,6 +83,7 @@ const getOptions = (props, force = false, userBabelConfig = null) => {
|
|
|
89
83
|
if (plugins.length || userBabelConfig) {
|
|
90
84
|
return {
|
|
91
85
|
plugins,
|
|
86
|
+
caller: getBabelCaller(props),
|
|
92
87
|
...userBabelConfig ? {
|
|
93
88
|
configFile: userBabelConfig,
|
|
94
89
|
babelrc: true
|
|
@@ -97,6 +92,14 @@ const getOptions = (props, force = false, userBabelConfig = null) => {
|
|
|
97
92
|
}
|
|
98
93
|
return null;
|
|
99
94
|
};
|
|
95
|
+
function getBabelCaller(props) {
|
|
96
|
+
const caller = {
|
|
97
|
+
name: "vxrn",
|
|
98
|
+
platform: props.environment === "ios" || props.environment === "android" ? props.environment : "web",
|
|
99
|
+
isDev: props.development
|
|
100
|
+
};
|
|
101
|
+
return caller;
|
|
102
|
+
}
|
|
100
103
|
async function transformOxcReactCompiler(id, code, optionsOrTarget = "19", sourceMap = false) {
|
|
101
104
|
const { transform } = await import("oxc-transform-react");
|
|
102
105
|
const compilerOptions = typeof optionsOrTarget === "string" ? { target: optionsOrTarget } : optionsOrTarget || {};
|
|
@@ -137,8 +140,13 @@ async function transformBabel(id, code, options) {
|
|
|
137
140
|
sourceMaps: false,
|
|
138
141
|
minified: false,
|
|
139
142
|
...options,
|
|
143
|
+
...!isTS ? { parserOpts: {
|
|
144
|
+
...options.parserOpts,
|
|
145
|
+
plugins: [...options.parserOpts?.plugins || [], "jsx"]
|
|
146
|
+
} } : {},
|
|
140
147
|
caller: {
|
|
141
148
|
name: "vxrn",
|
|
149
|
+
...options.caller,
|
|
142
150
|
supportsStaticESM: true,
|
|
143
151
|
supportsDynamicImport: true
|
|
144
152
|
},
|
|
@@ -164,13 +172,6 @@ async function transformBabel(id, code, options) {
|
|
|
164
172
|
});
|
|
165
173
|
});
|
|
166
174
|
}
|
|
167
|
-
async function stripFlowTypes(id, code, sourceMaps = true) {
|
|
168
|
-
const result = await transformBabel(id, code, { sourceMaps });
|
|
169
|
-
return {
|
|
170
|
-
code: result.code,
|
|
171
|
-
map: result.map
|
|
172
|
-
};
|
|
173
|
-
}
|
|
174
175
|
const getBasePlugins = ({ development }) => [
|
|
175
176
|
["@babel/plugin-transform-destructuring"],
|
|
176
177
|
["@babel/plugin-transform-react-jsx", { development }],
|
|
@@ -236,48 +237,6 @@ function shouldBabelGenerators({ code }) {
|
|
|
236
237
|
return asyncGeneratorRegex.test(code);
|
|
237
238
|
}
|
|
238
239
|
}
|
|
239
|
-
const REANIMATED_AUTOWORKLETIZATION_KEYWORDS = [
|
|
240
|
-
"worklet",
|
|
241
|
-
"useAnimatedGestureHandler",
|
|
242
|
-
"useAnimatedScrollHandler",
|
|
243
|
-
"useFrameCallback",
|
|
244
|
-
"useAnimatedStyle",
|
|
245
|
-
"useAnimatedProps",
|
|
246
|
-
"createAnimatedPropAdapter",
|
|
247
|
-
"useDerivedValue",
|
|
248
|
-
"useAnimatedReaction",
|
|
249
|
-
"useWorkletCallback",
|
|
250
|
-
"withTiming",
|
|
251
|
-
"withSpring",
|
|
252
|
-
"withDecay",
|
|
253
|
-
"withRepeat",
|
|
254
|
-
"runOnUI",
|
|
255
|
-
"executeOnUIRuntimeSync"
|
|
256
|
-
];
|
|
257
|
-
const REANIMATED_REGEX = new RegExp(REANIMATED_AUTOWORKLETIZATION_KEYWORDS.join("|"));
|
|
258
|
-
const REANIMATED_IGNORED_PATHS = [
|
|
259
|
-
"react-native-prebuilt",
|
|
260
|
-
"node_modules/.vxrn/react-native",
|
|
261
|
-
"node_modules/react/",
|
|
262
|
-
"node_modules/react-dom/",
|
|
263
|
-
"node_modules/react-native/",
|
|
264
|
-
"node_modules/react-native-web/"
|
|
265
|
-
];
|
|
266
|
-
const REANIMATED_IGNORED_PATHS_REGEX = new RegExp(REANIMATED_IGNORED_PATHS.join("|"));
|
|
267
|
-
function shouldBabelReanimated({ code, id }) {
|
|
268
|
-
if (!configuration.enableReanimated) {
|
|
269
|
-
return false;
|
|
270
|
-
}
|
|
271
|
-
if (REANIMATED_IGNORED_PATHS_REGEX.test(id)) {
|
|
272
|
-
return false;
|
|
273
|
-
}
|
|
274
|
-
if (REANIMATED_REGEX.test(code)) {
|
|
275
|
-
const location = id.includes("node_modules") ? "node_modules" : "user-code";
|
|
276
|
-
debug?.(` \u{1FA84} [reanimated/${location}] ${relative(process.cwd(), id)}`);
|
|
277
|
-
return true;
|
|
278
|
-
}
|
|
279
|
-
return false;
|
|
280
|
-
}
|
|
281
240
|
|
|
282
|
-
export { findUserBabelConfig, getBabelOptions,
|
|
241
|
+
export { findUserBabelConfig, getBabelOptions, transformBabel, transformOxcReactCompiler };
|
|
283
242
|
//# sourceMappingURL=transformBabel.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transformBabel.js","names":[],"sources":["esm/transformBabel.js"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { extname, join, relative } from \"node:path\";\nimport { resolvePath } from \"@vxrn/utils\";\nimport { normalizePath } from \"vite\";\nimport { configuration } from \"./configure\";\nimport { asyncGeneratorRegex, debug } from \"./constants\";\nconst USER_BABEL_CONFIG_FILES = [\n \"babel.config.js\",\n \"babel.config.cjs\",\n \"babel.config.mjs\",\n \"babel.config.json\",\n \".babelrc\",\n \".babelrc.js\",\n \".babelrc.json\"\n];\nconst ONE_GENERATED_MARKER = \"@one/generated bundler-config\";\nfunction findUserBabelConfig(projectRoot) {\n if (!projectRoot) return null;\n for (const name of USER_BABEL_CONFIG_FILES) {\n const fullPath = join(projectRoot, name);\n if (existsSync(fullPath)) {\n try {\n const content = readFileSync(fullPath, \"utf8\");\n if (content.includes(ONE_GENERATED_MARKER)) {\n continue;\n }\n } catch {\n continue;\n }\n return fullPath;\n }\n }\n return null;\n}\nfunction getBabelOptions(props) {\n props = { ...props, id: normalizePath(props.id.split(\"?\")[0]) };\n const isProjectFile = !props.id.includes(\"node_modules\");\n const userBabelConfig = isProjectFile && props.projectRoot ? findUserBabelConfig(props.projectRoot) : null;\n if (props.userSetting === \"babel\") {\n return getOptions(props, true, userBabelConfig);\n }\n if (typeof props.userSetting === \"undefined\" || typeof props.userSetting === \"object\" && props.userSetting.transform === \"babel\") {\n if (props.userSetting?.excludeDefaultPlugins) {\n return {\n ...props.userSetting,\n ...userBabelConfig ? { configFile: userBabelConfig, babelrc: true } : {}\n };\n }\n return getOptions(props, false, userBabelConfig);\n }\n const userSetting = props.userSetting;\n if (userSetting === \"swc\" || userSetting === \"oxc\" || userSetting === false || typeof userSetting === \"object\" && userSetting !== null && (userSetting.transform === \"swc\" || userSetting.transform === \"oxc\")) {\n return null;\n }\n if (userBabelConfig) {\n return getOptions(props, false, userBabelConfig);\n }\n return null;\n}\nconst getOptions = (props, force = false, userBabelConfig = null) => {\n let plugins = [];\n if (force || shouldBabelGenerators(props)) {\n plugins = getBasePlugins(props);\n }\n const enableNativewind = configuration.enableNativewind && (props.environment === \"ios\" || props.environment === \"android\") && // if reanimated gets wrapped in transform it causes circular dep issues\n !/node_modules/.test(props.id) && // only needed for createElement calls, so be a bit conservative\n props.code.includes(\"createElement\");\n if (enableNativewind) {\n if (!props.id.includes(\"node_modules\")) {\n plugins.push(resolvePath(\"react-native-css-interop/dist/babel-plugin.js\"));\n }\n }\n if (enableNativewind || shouldBabelReanimated(props)) {\n try {\n const workletsPlugin = resolvePath(\n \"react-native-worklets/plugin\",\n props.projectRoot\n );\n debug?.(`Using babel worklets on file ${props.id}`);\n plugins.push(workletsPlugin);\n } catch {\n }\n }\n if (shouldBabelReactCompiler(props)) {\n debug?.(`Using babel react compiler on file`);\n plugins.push(getBabelReactCompilerPlugin(props));\n }\n if (plugins.length || userBabelConfig) {\n return {\n plugins,\n ...userBabelConfig ? { configFile: userBabelConfig, babelrc: true } : {}\n };\n }\n return null;\n};\nasync function transformOxcReactCompiler(id, code, optionsOrTarget = \"19\", sourceMap = false) {\n const { transform } = await import(\"oxc-transform-react\");\n const compilerOptions = typeof optionsOrTarget === \"string\" ? { target: optionsOrTarget } : optionsOrTarget || {};\n const target = compilerOptions.target ?? \"19\";\n const result = await transform(id, code, {\n jsx: \"preserve\",\n sourcemap: sourceMap,\n reactCompiler: {\n target,\n ...compilerOptions,\n environment: {\n enableCustomTypeDefinitionForReanimated: true,\n ...compilerOptions.environment\n }\n }\n });\n if (result.fatal) {\n throw new Error(\n `[vxrn:compiler] oxc react compiler failed on ${id}: ${(result.errors ?? []).map((e) => e.message ?? String(e)).join(\", \")}`\n );\n }\n if (result.errors?.length) {\n debug?.(\n `[compiler/bailout] ${id}: ${result.errors.map((e) => e.message ?? String(e)).join(\", \")}`\n );\n }\n return {\n code: result.code,\n map: sourceMap ? result.map : void 0\n };\n}\nasync function transformBabel(id, code, options) {\n const [{ default: babelCore }, { default: hermesParserPlugin }] = await Promise.all([\n import(\"@babel/core\"),\n import(\"babel-plugin-syntax-hermes-parser\")\n ]);\n const extension = extname(id);\n const isTSX = extension === \".tsx\";\n const isTS = isTSX || extension === \".ts\";\n const babelOptions = {\n filename: id,\n compact: false,\n babelrc: options.babelrc ?? false,\n configFile: options.configFile ?? false,\n sourceMaps: false,\n minified: false,\n ...options,\n // vite and rolldown own module syntax and import.meta, so presets written for\n // metro (babel-preset-expo) must keep esm instead of rewriting it for metro's runtime\n caller: {\n name: \"vxrn\",\n supportsStaticESM: true,\n supportsDynamicImport: true\n },\n presets: [\n isTS ? [\n \"@babel/preset-typescript\",\n {\n isTSX,\n allExtensions: isTSX\n }\n ] : \"\",\n ...options.presets || []\n ].filter(Boolean),\n // non-TS files use React Native's Flow dialect. RN's own component specs are\n // Flow `.js` (`import type`, `codegenNativeComponent<T>(…)`, `(expr: Type)` casts).\n // enable Hermes Flow parsing + stripping, mirroring the TypeScript preset above\n // (`@react-native/babel-preset` uses the same parser for JS). without it babel\n // can't parse current RN Flow syntax such as `call<T>(...) as HostComponent<T>`, so\n // plugins like\n // @react-native/babel-plugin-codegen silently fail on RN specs and the runtime\n // \"Codegen didn't run\" warning fires. TS path is byte-identical (empty slice).\n plugins: [\n ...isTS ? [] : [\n [hermesParserPlugin, { parseLangTypes: \"flow\", reactRuntimeTarget: \"19\" }],\n \"babel-plugin-transform-flow-enums\"\n ],\n ...options.plugins || [],\n ...isTS ? [] : [\"@babel/plugin-transform-flow-strip-types\"]\n ]\n };\n return await new Promise((res, rej) => {\n babelCore.transform(code, babelOptions, (err, result) => {\n if (!result || err) {\n return rej(err || new Error(`[vxrn:compiler] babel returned no result for ${id}`));\n }\n res(result);\n });\n });\n}\nasync function stripFlowTypes(id, code, sourceMaps = true) {\n const result = await transformBabel(id, code, { sourceMaps });\n return {\n code: result.code,\n map: result.map\n };\n}\nconst getBasePlugins = ({ development }) => [\n [\"@babel/plugin-transform-destructuring\"],\n [\"@babel/plugin-transform-react-jsx\", { development }],\n [\"@babel/plugin-transform-async-generator-functions\"],\n [\"@babel/plugin-transform-async-to-generator\"],\n [\n \"@babel/plugin-transform-runtime\",\n {\n helpers: true,\n // NOTE THIS WAS SPELLED WRONG BEFOER THIS COMMIT MAYBE IT WAS UNINTENTIONALLY WORKING\n regenerator: false\n }\n ]\n];\nconst shouldBabelReactCompiler = (props) => {\n if (props.environment === \"ssr\") {\n return false;\n }\n if (!configuration.enableCompiler) {\n return false;\n }\n const { enableCompiler } = configuration;\n if (typeof enableCompiler === \"object\" && !Array.isArray(enableCompiler) && !(enableCompiler instanceof RegExp)) {\n const isNative = props.environment === \"ios\" || props.environment === \"android\";\n const filter = isNative ? enableCompiler.native : enableCompiler.web;\n if (!filter) return false;\n return applyCompilerFilter(filter, props);\n }\n if (typeof enableCompiler === \"function\") {\n return enableCompiler(props.id, props.environment);\n }\n if (enableCompiler instanceof RegExp) {\n return enableCompiler.test(props.id);\n }\n if (Array.isArray(enableCompiler)) {\n if (!enableCompiler.includes(props.environment)) {\n return false;\n }\n }\n return applyDefaultFilters(props);\n};\nfunction applyCompilerFilter(filter, props) {\n if (typeof filter === \"function\") {\n return filter(props.id, props.environment);\n }\n if (filter instanceof RegExp) {\n return filter.test(props.id);\n }\n if (filter === true) {\n return applyDefaultFilters(props);\n }\n return false;\n}\nfunction applyDefaultFilters(props) {\n if (!/(\\.tsx?)$/.test(props.id)) return false;\n if (props.id.includes(\"node_modules\")) return false;\n if (props.id.includes(\"+api.\")) return false;\n if (props.code.startsWith(\"// disable-compiler\")) return false;\n return true;\n}\nconst getBabelReactCompilerPlugin = (props) => {\n const target = props.reactForRNVersion === \"18\" && (props.environment === \"ios\" || props.environment === \"android\") ? \"18\" : \"19\";\n return [\"babel-plugin-react-compiler\", { target }];\n};\nfunction shouldBabelGenerators({ code }) {\n if (process.env.VXRN_USE_BABEL_FOR_GENERATORS) {\n return asyncGeneratorRegex.test(code);\n }\n}\nconst REANIMATED_AUTOWORKLETIZATION_KEYWORDS = [\n \"worklet\",\n \"useAnimatedGestureHandler\",\n \"useAnimatedScrollHandler\",\n \"useFrameCallback\",\n \"useAnimatedStyle\",\n \"useAnimatedProps\",\n \"createAnimatedPropAdapter\",\n \"useDerivedValue\",\n \"useAnimatedReaction\",\n \"useWorkletCallback\",\n \"withTiming\",\n \"withSpring\",\n \"withDecay\",\n \"withRepeat\",\n \"runOnUI\",\n \"executeOnUIRuntimeSync\"\n];\nconst REANIMATED_REGEX = new RegExp(REANIMATED_AUTOWORKLETIZATION_KEYWORDS.join(\"|\"));\nconst REANIMATED_IGNORED_PATHS = [\n // Prebuilt/vendored react-native that shouldn't be transformed\n \"react-native-prebuilt\",\n \"node_modules/.vxrn/react-native\",\n // Known false positives - they mention worklet keywords in comments/strings but don't use them\n \"node_modules/react/\",\n \"node_modules/react-dom/\",\n \"node_modules/react-native/\",\n \"node_modules/react-native-web/\"\n];\nconst REANIMATED_IGNORED_PATHS_REGEX = new RegExp(REANIMATED_IGNORED_PATHS.join(\"|\"));\nfunction shouldBabelReanimated({ code, id }) {\n if (!configuration.enableReanimated) {\n return false;\n }\n if (REANIMATED_IGNORED_PATHS_REGEX.test(id)) {\n return false;\n }\n if (REANIMATED_REGEX.test(code)) {\n const location = id.includes(\"node_modules\") ? \"node_modules\" : \"user-code\";\n debug?.(` \\u{1FA84} [reanimated/${location}] ${relative(process.cwd(), id)}`);\n return true;\n }\n return false;\n}\nexport {\n findUserBabelConfig,\n getBabelOptions,\n stripFlowTypes,\n transformBabel,\n transformOxcReactCompiler\n};\n//# sourceMappingURL=transformBabel.js.map\n"],"mappings":";;;;;;;;AAMA,MAAM,0BAA0B;CAC9B;CACA;CACA;CACA;CACA;CACA;C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":3,"file":"transformBabel.js","names":[],"sources":["esm/transformBabel.js"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { extname, join } from \"node:path\";\nimport { resolvePath } from \"@vxrn/utils\";\nimport { normalizePath } from \"vite\";\nimport { configuration } from \"./configure\";\nimport { asyncGeneratorRegex, debug } from \"./constants\";\nconst USER_BABEL_CONFIG_FILES = [\n \"babel.config.js\",\n \"babel.config.cjs\",\n \"babel.config.mjs\",\n \"babel.config.json\",\n \".babelrc\",\n \".babelrc.js\",\n \".babelrc.json\"\n];\nconst ONE_GENERATED_MARKER = \"@one/generated bundler-config\";\nfunction findUserBabelConfig(projectRoot) {\n if (!projectRoot) return null;\n for (const name of USER_BABEL_CONFIG_FILES) {\n const fullPath = join(projectRoot, name);\n if (existsSync(fullPath)) {\n try {\n const content = readFileSync(fullPath, \"utf8\");\n if (content.includes(ONE_GENERATED_MARKER)) {\n continue;\n }\n } catch {\n continue;\n }\n return fullPath;\n }\n }\n return null;\n}\nfunction getBabelOptions(props) {\n props = { ...props, id: normalizePath(props.id.split(\"?\")[0]) };\n const isProjectFile = !props.id.includes(\"node_modules\");\n const userBabelConfig = isProjectFile && props.projectRoot ? findUserBabelConfig(props.projectRoot) : null;\n if (props.userSetting === \"babel\") {\n return getOptions(props, true, userBabelConfig);\n }\n if (typeof props.userSetting === \"undefined\" || typeof props.userSetting === \"object\" && props.userSetting.transform === \"babel\") {\n if (props.userSetting?.excludeDefaultPlugins) {\n return {\n caller: getBabelCaller(props),\n ...props.userSetting,\n ...userBabelConfig ? { configFile: userBabelConfig, babelrc: true } : {}\n };\n }\n return getOptions(props, false, userBabelConfig);\n }\n const userSetting = props.userSetting;\n if (userSetting === \"swc\" || userSetting === \"oxc\" || userSetting === false || typeof userSetting === \"object\" && userSetting !== null && (userSetting.transform === \"swc\" || userSetting.transform === \"oxc\")) {\n return null;\n }\n if (userBabelConfig) {\n return getOptions(props, false, userBabelConfig);\n }\n return null;\n}\nconst getOptions = (props, force = false, userBabelConfig = null) => {\n let plugins = [];\n if (force || shouldBabelGenerators(props)) {\n plugins = getBasePlugins(props);\n }\n const enableNativewind = configuration.enableNativewind && (props.environment === \"ios\" || props.environment === \"android\") && // if reanimated gets wrapped in transform it causes circular dep issues\n !/node_modules/.test(props.id) && // only needed for createElement calls, so be a bit conservative\n props.code.includes(\"createElement\");\n if (enableNativewind) {\n if (!props.id.includes(\"node_modules\")) {\n plugins.push(resolvePath(\"react-native-css-interop/dist/babel-plugin.js\"));\n }\n }\n if (shouldBabelReactCompiler(props)) {\n debug?.(`Using babel react compiler on file`);\n plugins.push(getBabelReactCompilerPlugin(props));\n }\n if (plugins.length || userBabelConfig) {\n return {\n plugins,\n caller: getBabelCaller(props),\n ...userBabelConfig ? { configFile: userBabelConfig, babelrc: true } : {}\n };\n }\n return null;\n};\nfunction getBabelCaller(props) {\n const caller = {\n name: \"vxrn\",\n platform: props.environment === \"ios\" || props.environment === \"android\" ? props.environment : \"web\",\n isDev: props.development\n };\n return caller;\n}\nasync function transformOxcReactCompiler(id, code, optionsOrTarget = \"19\", sourceMap = false) {\n const { transform } = await import(\"oxc-transform-react\");\n const compilerOptions = typeof optionsOrTarget === \"string\" ? { target: optionsOrTarget } : optionsOrTarget || {};\n const target = compilerOptions.target ?? \"19\";\n const result = await transform(id, code, {\n jsx: \"preserve\",\n sourcemap: sourceMap,\n reactCompiler: {\n target,\n ...compilerOptions,\n environment: {\n enableCustomTypeDefinitionForReanimated: true,\n ...compilerOptions.environment\n }\n }\n });\n if (result.fatal) {\n throw new Error(\n `[vxrn:compiler] oxc react compiler failed on ${id}: ${(result.errors ?? []).map((e) => e.message ?? String(e)).join(\", \")}`\n );\n }\n if (result.errors?.length) {\n debug?.(\n `[compiler/bailout] ${id}: ${result.errors.map((e) => e.message ?? String(e)).join(\", \")}`\n );\n }\n return {\n code: result.code,\n map: sourceMap ? result.map : void 0\n };\n}\nasync function transformBabel(id, code, options) {\n const [{ default: babelCore }, { default: hermesParserPlugin }] = await Promise.all([\n import(\"@babel/core\"),\n import(\"babel-plugin-syntax-hermes-parser\")\n ]);\n const extension = extname(id);\n const isTSX = extension === \".tsx\";\n const isTS = isTSX || extension === \".ts\";\n const babelOptions = {\n filename: id,\n compact: false,\n babelrc: options.babelrc ?? false,\n configFile: options.configFile ?? false,\n sourceMaps: false,\n minified: false,\n ...options,\n ...!isTS ? {\n parserOpts: {\n ...options.parserOpts,\n plugins: [...options.parserOpts?.plugins || [], \"jsx\"]\n }\n } : {},\n // vite and rolldown own module syntax and import.meta, so presets written for\n // metro (babel-preset-expo) must keep esm instead of rewriting it for metro's runtime\n caller: {\n name: \"vxrn\",\n ...options.caller,\n supportsStaticESM: true,\n supportsDynamicImport: true\n },\n presets: [\n isTS ? [\n \"@babel/preset-typescript\",\n {\n isTSX,\n allExtensions: isTSX\n }\n ] : \"\",\n ...options.presets || []\n ].filter(Boolean),\n // non-TS files use React Native's Flow dialect. RN's own component specs are\n // Flow `.js` (`import type`, `codegenNativeComponent<T>(…)`, `(expr: Type)` casts).\n // enable Hermes Flow parsing + stripping, mirroring the TypeScript preset above\n // (`@react-native/babel-preset` uses the same parser for JS). without it babel\n // can't parse current RN Flow syntax such as `call<T>(...) as HostComponent<T>`, so\n // plugins like\n // @react-native/babel-plugin-codegen silently fail on RN specs and the runtime\n // \"Codegen didn't run\" warning fires. TS path is byte-identical (empty slice).\n plugins: [\n ...isTS ? [] : [\n [hermesParserPlugin, { parseLangTypes: \"flow\", reactRuntimeTarget: \"19\" }],\n \"babel-plugin-transform-flow-enums\"\n ],\n ...options.plugins || [],\n ...isTS ? [] : [\"@babel/plugin-transform-flow-strip-types\"]\n ]\n };\n return await new Promise((res, rej) => {\n babelCore.transform(code, babelOptions, (err, result) => {\n if (!result || err) {\n return rej(err || new Error(`[vxrn:compiler] babel returned no result for ${id}`));\n }\n res(result);\n });\n });\n}\nconst getBasePlugins = ({ development }) => [\n [\"@babel/plugin-transform-destructuring\"],\n [\"@babel/plugin-transform-react-jsx\", { development }],\n [\"@babel/plugin-transform-async-generator-functions\"],\n [\"@babel/plugin-transform-async-to-generator\"],\n [\n \"@babel/plugin-transform-runtime\",\n {\n helpers: true,\n // NOTE THIS WAS SPELLED WRONG BEFOER THIS COMMIT MAYBE IT WAS UNINTENTIONALLY WORKING\n regenerator: false\n }\n ]\n];\nconst shouldBabelReactCompiler = (props) => {\n if (props.environment === \"ssr\") {\n return false;\n }\n if (!configuration.enableCompiler) {\n return false;\n }\n const { enableCompiler } = configuration;\n if (typeof enableCompiler === \"object\" && !Array.isArray(enableCompiler) && !(enableCompiler instanceof RegExp)) {\n const isNative = props.environment === \"ios\" || props.environment === \"android\";\n const filter = isNative ? enableCompiler.native : enableCompiler.web;\n if (!filter) return false;\n return applyCompilerFilter(filter, props);\n }\n if (typeof enableCompiler === \"function\") {\n return enableCompiler(props.id, props.environment);\n }\n if (enableCompiler instanceof RegExp) {\n return enableCompiler.test(props.id);\n }\n if (Array.isArray(enableCompiler)) {\n if (!enableCompiler.includes(props.environment)) {\n return false;\n }\n }\n return applyDefaultFilters(props);\n};\nfunction applyCompilerFilter(filter, props) {\n if (typeof filter === \"function\") {\n return filter(props.id, props.environment);\n }\n if (filter instanceof RegExp) {\n return filter.test(props.id);\n }\n if (filter === true) {\n return applyDefaultFilters(props);\n }\n return false;\n}\nfunction applyDefaultFilters(props) {\n if (!/(\\.tsx?)$/.test(props.id)) return false;\n if (props.id.includes(\"node_modules\")) return false;\n if (props.id.includes(\"+api.\")) return false;\n if (props.code.startsWith(\"// disable-compiler\")) return false;\n return true;\n}\nconst getBabelReactCompilerPlugin = (props) => {\n const target = props.reactForRNVersion === \"18\" && (props.environment === \"ios\" || props.environment === \"android\") ? \"18\" : \"19\";\n return [\"babel-plugin-react-compiler\", { target }];\n};\nfunction shouldBabelGenerators({ code }) {\n if (process.env.VXRN_USE_BABEL_FOR_GENERATORS) {\n return asyncGeneratorRegex.test(code);\n }\n}\nexport {\n findUserBabelConfig,\n getBabelOptions,\n transformBabel,\n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AO;CAC1C,IAAI,OAAO,WAAW,YAAY;EAChC,OAAO,OAAO,MAAM,IAAI,MAAM,WAAW;CAC3C;CACA,IAAI,kBAAkB,QAAQ;EAC5B,OAAO,OAAO,KAAK,MAAM,EAAE;CAC7B;CACA,IAAI,WAAW,MAAM;EACnB,OAAO,oBAAoB,KAAK;CAClC;CACA,OAAO;AACT;AACA,SAAS,oBAAoB,OAAO;CAClC,IAAI,CAAC,YAAY,KAAK,MAAM,EAAE,GAAG,OAAO;CACxC,IAAI,MAAM,GAAG,SAAS,cAAc,GAAG,OAAO;CAC9C,IAAI,MAAM,GAAG,SAAS,OAAO,GAAG,OAAO;CACvC,IAAI,MAAM,KAAK,WAAW,qBAAqB,GAAG,OAAO;CACzD,OAAO;AACT;AACA,MAAM,+BAA+B,UAAU;CAC7C,MAAM,SAAS,MAAM,sBAAsB,SAAS,MAAM,gBAAgB,SAAS,MAAM,gBAAgB,aAAa,OAAO;CAC7H,OAAO,CAAC,+BAA+B,EAAE,OAAO,CAAC;AACnD;AACA,SAAS,sBAAsB,EAAE,QAAQ;CACvC,IAAI,QAAQ,IAAI,+BAA+B;EAC7C,OAAO,oBAAoB,KAAK,IAAI;CACtC;AACF"}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import remapping from "@jridgewell/remapping";
|
|
2
|
+
import { generate } from "astring";
|
|
3
|
+
import { SimpleTraverser, Transforms, parse } from "hermes-parser";
|
|
4
|
+
import MagicString from "magic-string";
|
|
5
|
+
|
|
6
|
+
async function stripFlowTypes(id, code, sourceMaps = true) {
|
|
7
|
+
const edited = new MagicString(code);
|
|
8
|
+
if (/\benum\b/.test(code)) {
|
|
9
|
+
const program = parse(code, {
|
|
10
|
+
flow: "all",
|
|
11
|
+
sourceType: "module"
|
|
12
|
+
});
|
|
13
|
+
SimpleTraverser.traverse(program, {
|
|
14
|
+
enter(node, parent) {
|
|
15
|
+
if (node.type !== "EnumDeclaration") return;
|
|
16
|
+
const declaration = parent?.type === "ExportDefaultDeclaration" ? parent : node;
|
|
17
|
+
const [start, end] = declaration.range;
|
|
18
|
+
const lowered = Transforms.transformEnumSyntax({
|
|
19
|
+
...program,
|
|
20
|
+
body: [declaration]
|
|
21
|
+
}, {});
|
|
22
|
+
edited.overwrite(start, end, generate(lowered).trimEnd());
|
|
23
|
+
},
|
|
24
|
+
leave() {}
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
const { transform } = await import("@swc/core");
|
|
28
|
+
const result = await transform(edited.toString(), {
|
|
29
|
+
filename: id,
|
|
30
|
+
swcrc: false,
|
|
31
|
+
configFile: false,
|
|
32
|
+
inputSourceMap: false,
|
|
33
|
+
sourceMaps,
|
|
34
|
+
jsc: {
|
|
35
|
+
target: "esnext",
|
|
36
|
+
parser: {
|
|
37
|
+
syntax: "flow",
|
|
38
|
+
all: true,
|
|
39
|
+
jsx: true,
|
|
40
|
+
enums: true,
|
|
41
|
+
components: true,
|
|
42
|
+
patternMatching: true
|
|
43
|
+
},
|
|
44
|
+
transform: {
|
|
45
|
+
react: { runtime: "preserve" },
|
|
46
|
+
useDefineForClassFields: false
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
const map = result.map ? JSON.parse(result.map) : void 0;
|
|
51
|
+
return {
|
|
52
|
+
code: result.code,
|
|
53
|
+
map: map && edited.hasChanged() ? remapping([map, edited.generateMap({
|
|
54
|
+
source: id,
|
|
55
|
+
includeContent: true,
|
|
56
|
+
hires: true
|
|
57
|
+
})], () => null) : map
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export { stripFlowTypes };
|
|
62
|
+
//# sourceMappingURL=transformFlow.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transformFlow.js","names":[],"sources":["esm/transformFlow.js"],"sourcesContent":["import remapping from \"@jridgewell/remapping\";\nimport { generate } from \"astring\";\nimport { parse, SimpleTraverser, Transforms } from \"hermes-parser\";\nimport MagicString from \"magic-string\";\nasync function stripFlowTypes(id, code, sourceMaps = true) {\n const edited = new MagicString(code);\n if (/\\benum\\b/.test(code)) {\n const program = parse(code, { flow: \"all\", sourceType: \"module\" });\n SimpleTraverser.traverse(program, {\n enter(node, parent) {\n if (node.type !== \"EnumDeclaration\") return;\n const declaration = parent?.type === \"ExportDefaultDeclaration\" ? parent : node;\n const [start, end] = declaration.range;\n const lowered = Transforms.transformEnumSyntax(\n { ...program, body: [declaration] },\n {}\n );\n edited.overwrite(start, end, generate(lowered).trimEnd());\n },\n leave() {\n }\n });\n }\n const { transform } = await import(\"@swc/core\");\n const result = await transform(edited.toString(), {\n filename: id,\n swcrc: false,\n configFile: false,\n inputSourceMap: false,\n sourceMaps,\n jsc: {\n target: \"esnext\",\n parser: {\n syntax: \"flow\",\n all: true,\n jsx: true,\n enums: true,\n components: true,\n patternMatching: true\n },\n // match Flow's declaration erasure before the native class-field pass.\n transform: {\n react: { runtime: \"preserve\" },\n useDefineForClassFields: false\n }\n }\n });\n const map = result.map ? JSON.parse(result.map) : void 0;\n return {\n code: result.code,\n map: map && edited.hasChanged() ? remapping(\n [\n map,\n edited.generateMap({\n source: id,\n includeContent: true,\n hires: true\n })\n ],\n () => null\n ) : map\n };\n}\nexport {\n stripFlowTypes\n};\n//# sourceMappingURL=transformFlow.js.map\n"],"mappings":";;;;;;AAIA,eAAe,eAAe,IAAI,MAAM,aAAa,MAAM;CACzD,MAAM,SAAS,IAAI,YAAY,IAAI;CACnC,IAAI,WAAW,KAAK,IAAI,GAAG;EACzB,MAAM,UAAU,MAAM,MAAM;GAAE,MAAM;GAAO,YAAY;EAAS,CAAC;EACjE,gBAAgB,SAAS,SAAS;GAChC,MAAM,MAAM,QAAQ;IAClB,IAAI,KAAK,SAAS,mBAAmB;IACrC,MAAM,cAAc,QAAQ,SAAS,6BAA6B,SAAS;IAC3E,MAAM,CAAC,OAAO,OAAO,YAAY;IACjC,MAAM,UAAU,WAAW,oBACzB;KAAE,GAAG;KAAS,MAAM,CAAC,WAAW;IAAE,GAClC,CAAC,CACH;IACA,OAAO,UAAU,OAAO,KAAK,SAAS,OAAO,CAAC,CAAC,QAAQ,CAAC;GAC1D;GACA,QAAQ,CACR;EACF,CAAC;CACH;CACA,MAAM,EAAE,cAAc,MAAM,OAAO;CACnC,MAAM,SAAS,MAAM,UAAU,OAAO,SAAS,GAAG;EAChD,UAAU;EACV,OAAO;EACP,YAAY;EACZ,gBAAgB;EAChB;EACA,KAAK;GACH,QAAQ;GACR,QAAQ;IACN,QAAQ;IACR,KAAK;IACL,KAAK;IACL,OAAO;IACP,YAAY;IACZ,iBAAiB;GACnB;GAEA,WAAW;IACT,OAAO,EAAE,SAAS,WAAW;IAC7B,yBAAyB;GAC3B;EACF;CACF,CAAC;CACD,MAAM,MAAM,OAAO,MAAM,KAAK,MAAM,OAAO,GAAG,IAAI,KAAK;CACvD,OAAO;EACL,MAAM,OAAO;EACb,KAAK,OAAO,OAAO,WAAW,IAAI,UAChC,CACE,KACA,OAAO,YAAY;GACjB,QAAQ;GACR,gBAAgB;GAChB,OAAO;EACT,CAAC,CACH,SACM,IACR,IAAI;CACN;AACF"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
async function transformHermesClasses(code, filename, sourceMaps = false) {
|
|
2
|
+
if (!/\b(?:class(?:\s|\{)|(?:let|const)\s)/.test(code)) return;
|
|
3
|
+
const { transform } = await import("@swc/core");
|
|
4
|
+
const result = await transform(code, {
|
|
5
|
+
filename,
|
|
6
|
+
swcrc: false,
|
|
7
|
+
configFile: false,
|
|
8
|
+
sourceMaps,
|
|
9
|
+
inputSourceMap: false,
|
|
10
|
+
isModule: "unknown",
|
|
11
|
+
jsc: {
|
|
12
|
+
parser: {
|
|
13
|
+
syntax: "ecmascript",
|
|
14
|
+
jsx: true
|
|
15
|
+
},
|
|
16
|
+
transform: { react: { runtime: "preserve" } }
|
|
17
|
+
},
|
|
18
|
+
env: { include: [
|
|
19
|
+
"transform-classes",
|
|
20
|
+
"transform-block-scoping",
|
|
21
|
+
"transform-parameters"
|
|
22
|
+
] }
|
|
23
|
+
});
|
|
24
|
+
if (!result?.code) return;
|
|
25
|
+
return {
|
|
26
|
+
code: result.code,
|
|
27
|
+
map: result.map ? JSON.parse(result.map) : void 0
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export { transformHermesClasses };
|
|
32
|
+
//# sourceMappingURL=transformHermesClasses.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transformHermesClasses.js","names":[],"sources":["esm/transformHermesClasses.js"],"sourcesContent":["async function transformHermesClasses(code, filename, sourceMaps = false) {\n if (!/\\b(?:class(?:\\s|\\{)|(?:let|const)\\s)/.test(code)) return;\n const { transform } = await import(\"@swc/core\");\n const result = await transform(code, {\n filename,\n swcrc: false,\n configFile: false,\n sourceMaps,\n // the caller composes stage maps itself; a file's own sourceMappingURL\n // composed here would give the stage map several sources\n inputSourceMap: false,\n isModule: \"unknown\",\n jsc: {\n parser: { syntax: \"ecmascript\", jsx: true },\n transform: { react: { runtime: \"preserve\" } }\n },\n // class lowering emits strict constructors, so their defaults and rest\n // parameters must be lowered with them; async lowering belongs to its stage.\n env: {\n include: [\"transform-classes\", \"transform-block-scoping\", \"transform-parameters\"]\n }\n });\n if (!result?.code) return;\n return {\n code: result.code,\n map: result.map ? JSON.parse(result.map) : void 0\n };\n}\nexport {\n transformHermesClasses\n};\n//# sourceMappingURL=transformHermesClasses.js.map\n"],"mappings":";AAAA,eAAe,uBAAuB,MAAM,UAAU,aAAa,OAAO;CACxE,IAAI,CAAC,uCAAuC,KAAK,IAAI,GAAG;CACxD,MAAM,EAAE,cAAc,MAAM,OAAO;CACnC,MAAM,SAAS,MAAM,UAAU,MAAM;EACnC;EACA,OAAO;EACP,YAAY;EACZ;EAGA,gBAAgB;EAChB,UAAU;EACV,KAAK;GACH,QAAQ;IAAE,QAAQ;IAAc,KAAK;GAAK;GAC1C,WAAW,EAAE,OAAO,EAAE,SAAS,WAAW,EAAE;EAC9C;EAGA,KAAK,EACH,SAAS;GAAC;GAAqB;GAA2B;EAAsB,EAClF;CACF,CAAC;CACD,IAAI,CAAC,QAAQ,MAAM;CACnB,OAAO;EACL,MAAM,OAAO;EACb,KAAK,OAAO,MAAM,KAAK,MAAM,OAAO,GAAG,IAAI,KAAK;CAClD;AACF"}
|