@tamagui/vite-plugin 2.7.7 → 3.0.0-beta.1097.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,469 +5,1176 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __getProtoOf = Object.getPrototypeOf;
6
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
7
  var __export = (target, all) => {
8
- for (var name in all) __defProp(target, name, {
9
- get: all[name],
10
- enumerable: true
11
- });
8
+ for (var name in all) __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true
11
+ });
12
12
  };
13
13
  var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
- get: () => from[key],
17
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
- });
19
- }
20
- return to;
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: () => from[key],
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
21
  };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
- // If the importer is in node compatibility mode or this is not an ESM
24
- // file that has been converted to a CommonJS file using a Babel-
25
- // compatible transform (i.e. "__esModule" has not been set), then set
26
- // "default" to the CommonJS "module.exports" for node compatibility.
27
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
28
- value: mod,
29
- enumerable: true
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
30
25
  }) : target, mod));
31
- var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
32
- value: true
33
- }), mod);
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
34
27
  var plugin_exports = {};
35
28
  __export(plugin_exports, {
36
- tamaguiAliases: () => tamaguiAliases,
37
- tamaguiPlugin: () => tamaguiPlugin
29
+ createTamaguiPlugins: () => createTamaguiPlugins,
30
+ tamaguiAliases: () => tamaguiAliases,
31
+ tamaguiNativePlugin: () => tamaguiNativePlugin,
32
+ tamaguiPlugin: () => tamaguiPlugin
38
33
  });
39
34
  module.exports = __toCommonJS(plugin_exports);
40
- var Static = __toESM(require("@tamagui/static-worker"), 1);
41
- var import_static_worker = require("@tamagui/static-worker");
35
+ var import_static = __toESM(require("@tamagui/static"), 1);
42
36
  var import_node_crypto = require("node:crypto");
43
37
  var import_node_fs = require("node:fs");
38
+ var import_node_zlib = require("node:zlib");
39
+ var import_promises = require("node:fs/promises");
44
40
  var import_node_module = require("node:module");
45
41
  var import_node_path = __toESM(require("node:path"), 1);
46
42
  var import_node_url = require("node:url");
43
+ var import_vite = require("vite");
47
44
  var import_loadTamagui = require("./loadTamagui.cjs");
45
+ var import_compilerStats = require("./compilerStats.cjs");
46
+ var import_zeroRuntime = require("./zeroRuntime.cjs");
48
47
  const import_meta = {};
49
- const _pluginRequire = (0, import_node_module.createRequire)(typeof __filename === "string" ? __filename : (0, import_node_url.fileURLToPath)(import_meta.url));
50
- const resolve = name => _pluginRequire.resolve(name);
51
- const normalizePath = value => value.replace(/\\/g, "/");
52
- const CACHE_KEY = "__tamagui_vite_cache__";
53
- const CACHE_SIZE_KEY = "__tamagui_vite_cache_size__";
54
- const PENDING_KEY = "__tamagui_vite_pending__";
55
- function getSharedCache() {
56
- if (!globalThis[CACHE_KEY]) {
57
- ;
58
- globalThis[CACHE_KEY] = {};
59
- }
60
- return globalThis[CACHE_KEY];
48
+ const environmentSpecificTransformPluginNames = /* @__PURE__ */ new Set(["one:compiler", "one:compiler-css-to-js"]);
49
+ const oneTsconfigPathsPluginName = "one:tsconfig-paths";
50
+ const bareTamaguiPackage = /^@tamagui\/[^/?#]+(?:[/?#]|$)/;
51
+ const inlineEvaluationTamaguiPackage = /^@tamagui\/(?:config|core|slider|web)(?:[/?#]|$)/;
52
+ const externalizablePackageExtensions = /* @__PURE__ */ new Set([
53
+ "",
54
+ ".js",
55
+ ".mjs",
56
+ ".cjs"
57
+ ]);
58
+ const TAMAGUI_COMPILER_CONDITION = "tamagui-compiler";
59
+ function packageDeclaresCompilerCondition(packageDir) {
60
+ const manifest = import_node_path.default.join(packageDir, "package.json");
61
+ if (!(0, import_node_fs.existsSync)(manifest)) return false;
62
+ try {
63
+ const exports = JSON.parse((0, import_node_fs.readFileSync)(manifest, "utf8")).exports;
64
+ return JSON.stringify(exports ?? null).includes(`"${TAMAGUI_COMPILER_CONDITION}"`);
65
+ } catch {
66
+ return false;
67
+ }
68
+ }
69
+ function mergeEvaluationNoExternal(required, userNoExternal) {
70
+ if (userNoExternal === true) return true;
71
+ if (!userNoExternal) return required;
72
+ return [...required, ...Array.isArray(userNoExternal) ? userNoExternal : [userNoExternal]];
73
+ }
74
+ function createEvaluationResolveId(plugin, resolveBarePackage) {
75
+ const resolveId = plugin.resolveId;
76
+ if (plugin.name !== oneTsconfigPathsPluginName || !resolveId) return resolveId;
77
+ const handler = typeof resolveId === "object" ? resolveId.handler : resolveId;
78
+ const evaluationHandler = function(source, ...args) {
79
+ if (bareTamaguiPackage.test(source)) {
80
+ const importer = typeof args[0] === "string" ? args[0] : void 0;
81
+ return resolveBarePackage?.(this.environment, source, importer);
82
+ }
83
+ return Reflect.apply(handler, this, [source, ...args]);
84
+ };
85
+ return typeof resolveId === "object" ? {
86
+ ...resolveId,
87
+ handler: evaluationHandler
88
+ } : evaluationHandler;
89
+ }
90
+ function createEvaluationPluginFacade(plugin, resolveBarePackage) {
91
+ return {
92
+ name: plugin.name,
93
+ enforce: plugin.enforce,
94
+ resolveId: createEvaluationResolveId(plugin, resolveBarePackage),
95
+ load: plugin.load,
96
+ transform: environmentSpecificTransformPluginNames.has(plugin.name) ? void 0 : plugin.transform
97
+ };
98
+ }
99
+ const tamaguiEvaluationPluginNames = /* @__PURE__ */ new Set([
100
+ "tamagui",
101
+ "tamagui-extract",
102
+ "tamagui-rnw-lite"
103
+ ]);
104
+ function isEvaluationUserPlugin(plugin) {
105
+ return !!(plugin.resolveId || plugin.load || plugin.transform) && plugin.name !== "alias" && !plugin.name.startsWith("native:") && !plugin.name.startsWith("vite:") && !plugin.name.startsWith("builtin:vite-") && !tamaguiEvaluationPluginNames.has(plugin.name);
106
+ }
107
+ function isEvaluationCorePlugin(plugin) {
108
+ return plugin.name === "alias" || plugin.name.startsWith("vite:") || plugin.name.startsWith("builtin:vite-");
109
+ }
110
+ function isConfiguredEvaluationPackage(source, packages) {
111
+ const cleanSource = source.split(/[?#]/, 1)[0];
112
+ return [...packages].some((packageName) => cleanSource === packageName || cleanSource.startsWith(`${packageName}/`));
113
+ }
114
+ function getEvaluationPackageName(source) {
115
+ if (!source) return;
116
+ const cleanSource = source.split(/[?#]/, 1)[0];
117
+ if (!cleanSource || cleanSource.startsWith(".") || cleanSource.startsWith("#") || cleanSource.startsWith("\0") || import_node_path.default.isAbsolute(cleanSource)) return;
118
+ if (cleanSource.startsWith("@")) {
119
+ const [scope, name2] = cleanSource.split("/");
120
+ return scope && name2 ? `${scope}/${name2}` : void 0;
121
+ }
122
+ const [name] = cleanSource.split("/");
123
+ return name && !import_node_path.default.extname(name) ? name : void 0;
124
+ }
125
+ function scanInstalledTamaguiPackages(root, configuredEvaluationPackages) {
126
+ const packageRequire = (0, import_node_module.createRequire)(import_node_path.default.join(root, "package.json"));
127
+ const externalizable = /* @__PURE__ */ new Set();
128
+ const compilerCondition = /* @__PURE__ */ new Set();
129
+ for (const modulePath of packageRequire.resolve.paths("@tamagui/core") || []) {
130
+ const scopePath = import_node_path.default.join(modulePath, "@tamagui");
131
+ if (!(0, import_node_fs.existsSync)(scopePath)) continue;
132
+ for (const entry of (0, import_node_fs.readdirSync)(scopePath, { withFileTypes: true })) {
133
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
134
+ const packageName = `@tamagui/${entry.name}`;
135
+ if (inlineEvaluationTamaguiPackage.test(packageName) || configuredEvaluationPackages.has(packageName)) continue;
136
+ if (packageDeclaresCompilerCondition(import_node_path.default.join(scopePath, entry.name))) compilerCondition.add(packageName);
137
+ else externalizable.add(packageName);
138
+ }
139
+ }
140
+ return {
141
+ externalizable,
142
+ compilerCondition
143
+ };
144
+ }
145
+ function getEvaluationResolve(resolve2, root, disableTsconfigPaths, configuredEvaluationPackages) {
146
+ const noExternal = resolve2.noExternal;
147
+ const noExternalFilter = noExternal && noExternal !== true ? (0, import_vite.createFilter)(void 0, noExternal, { resolve: false }) : void 0;
148
+ const isNoExternalPackage = noExternal === true ? () => true : noExternalFilter ? (packageName) => !noExternalFilter(packageName) : () => false;
149
+ return {
150
+ ...resolve2,
151
+ external: resolve2.external === true ? true : [.../* @__PURE__ */ new Set([...(resolve2.external || []).filter((packageName) => !isConfiguredEvaluationPackage(packageName, configuredEvaluationPackages)), ...[...scanInstalledTamaguiPackages(root, configuredEvaluationPackages).externalizable].filter((packageName) => !isNoExternalPackage(packageName))])],
152
+ ...disableTsconfigPaths && { tsconfigPaths: false }
153
+ };
61
154
  }
62
- function getSharedCacheSize() {
63
- return globalThis[CACHE_SIZE_KEY] || 0;
155
+ function isConfiguredExternalPackage(source, external) {
156
+ if (external === true) return true;
157
+ const cleanSource = source.split(/[?#]/, 1)[0];
158
+ return external?.some((packageName) => cleanSource === packageName || cleanSource.startsWith(`${packageName}/`));
64
159
  }
65
- function setSharedCacheSize(size) {
66
- ;
67
- globalThis[CACHE_SIZE_KEY] = size;
160
+ function createServeEvaluationConfig(config, configuredEvaluationPackages) {
161
+ const environment = config.environments[import_loadTamagui.TAMAGUI_EVALUATION_ENVIRONMENT];
162
+ let packageResolver;
163
+ const resolveBarePackage = async (evaluationEnvironment, source, importer) => {
164
+ const resolved = await packageResolver?.(evaluationEnvironment, source, importer);
165
+ if (!resolved) return;
166
+ const cleanResolved = resolved.split(/[?#]/, 1)[0];
167
+ if (!inlineEvaluationTamaguiPackage.test(source) && !isConfiguredEvaluationPackage(source, configuredEvaluationPackages) && isConfiguredExternalPackage(source, evaluationEnvironment.config.resolve.external)) return {
168
+ id: source,
169
+ external: true
170
+ };
171
+ if (inlineEvaluationTamaguiPackage.test(source) || isConfiguredEvaluationPackage(source, configuredEvaluationPackages) || !normalizePath(cleanResolved).includes("/node_modules/") || !externalizablePackageExtensions.has(import_node_path.default.extname(cleanResolved))) return resolved;
172
+ return {
173
+ id: source,
174
+ external: true
175
+ };
176
+ };
177
+ const plugins = environment.plugins.flatMap((plugin) => {
178
+ if (isEvaluationCorePlugin(plugin)) return [plugin];
179
+ if (isEvaluationUserPlugin(plugin)) return [createEvaluationPluginFacade(plugin, resolveBarePackage)];
180
+ return [];
181
+ });
182
+ const resolve2 = getEvaluationResolve(environment.resolve, config.root, plugins.some((plugin) => plugin.name === oneTsconfigPathsPluginName), configuredEvaluationPackages);
183
+ const evaluationConfig = {
184
+ ...config,
185
+ environments: {
186
+ ...config.environments,
187
+ [import_loadTamagui.TAMAGUI_EVALUATION_ENVIRONMENT]: {
188
+ ...environment,
189
+ plugins,
190
+ resolve: resolve2
191
+ }
192
+ }
193
+ };
194
+ packageResolver = (0, import_vite.createIdResolver)(evaluationConfig);
195
+ return evaluationConfig;
68
196
  }
69
- function clearSharedCache() {
70
- ;
71
- globalThis[CACHE_KEY] = {};
72
- globalThis[CACHE_SIZE_KEY] = 0;
197
+ async function createOwnedEvaluationConfig(config, configuredEvaluationPackages) {
198
+ const environment = config.environments[import_loadTamagui.TAMAGUI_EVALUATION_ENVIRONMENT];
199
+ const plugins = environment.plugins.filter(isEvaluationUserPlugin).map((plugin) => createEvaluationPluginFacade(plugin));
200
+ const resolve2 = getEvaluationResolve(environment.resolve, config.root, plugins.some((plugin) => plugin.name === oneTsconfigPathsPluginName), configuredEvaluationPackages);
201
+ const { createEnvironment: _createEnvironment, ...dev } = environment.dev;
202
+ return (0, import_vite.resolveConfig)({
203
+ configFile: false,
204
+ root: config.root,
205
+ mode: config.mode,
206
+ logLevel: config.logLevel,
207
+ plugins,
208
+ define: environment.define,
209
+ resolve: resolve2,
210
+ environments: { [import_loadTamagui.TAMAGUI_EVALUATION_ENVIRONMENT]: {
211
+ consumer: environment.consumer,
212
+ keepProcessEnv: environment.keepProcessEnv,
213
+ define: environment.define,
214
+ resolve: resolve2,
215
+ optimizeDeps: environment.optimizeDeps,
216
+ dev: {
217
+ ...dev,
218
+ moduleRunnerTransform: true
219
+ }
220
+ } }
221
+ }, "serve", config.mode);
222
+ }
223
+ const _pluginRequire = (0, import_node_module.createRequire)(typeof __filename === "string" ? __filename : (0, import_node_url.fileURLToPath)(import_meta.url));
224
+ const resolve = (name) => _pluginRequire.resolve(name);
225
+ const normalizePath = (value) => value.replace(/\\/g, "/");
226
+ const PLUGIN_INSTANCE_KEY = "__tamagui_vite_plugin_instance__";
227
+ function reportCompilerStats(root, reports) {
228
+ const report = (0, import_compilerStats.createCompilerStatsReport)(root, reports);
229
+ console.info((0, import_compilerStats.formatCompilerStatsReport)(report, process.env.TAMAGUI_COMPILER_STATS === "verbose"));
230
+ if (process.env.TAMAGUI_COMPILER_STATS_FILE) {
231
+ const outputPath = import_node_path.default.resolve(root, process.env.TAMAGUI_COMPILER_STATS_FILE);
232
+ (0, import_node_fs.writeFileSync)(outputPath, `${JSON.stringify(report, null, 2)}
233
+ `);
234
+ console.info(`[tamagui] compiler stats JSON: ${import_node_path.default.relative(process.cwd(), outputPath)}`);
235
+ }
236
+ }
237
+ function getNextPluginInstanceId() {
238
+ const next = (globalThis[PLUGIN_INSTANCE_KEY] || 0) + 1;
239
+ globalThis[PLUGIN_INSTANCE_KEY] = next;
240
+ return next;
73
241
  }
74
242
  function isInstalled(projectRoot, id) {
75
- try {
76
- const req = (0, import_node_module.createRequire)(import_node_path.default.join(projectRoot, "package.json"));
77
- req.resolve(id);
78
- return true;
79
- } catch {
80
- return false;
81
- }
243
+ try {
244
+ (0, import_node_module.createRequire)(import_node_path.default.join(projectRoot, "package.json")).resolve(id);
245
+ return true;
246
+ } catch {
247
+ return false;
248
+ }
82
249
  }
83
250
  function addIfInstalled(userConf, projectRoot, ids) {
84
- const root = projectRoot || process.cwd();
85
- userConf.optimizeDeps ||= {};
86
- userConf.optimizeDeps.include ||= [];
87
- for (const id of ids) {
88
- if (!userConf.optimizeDeps.include.includes(id) && isInstalled(root, id)) {
89
- userConf.optimizeDeps.include.push(id);
90
- }
91
- }
251
+ const root = projectRoot || process.cwd();
252
+ userConf.optimizeDeps ||= {};
253
+ userConf.optimizeDeps.include ||= [];
254
+ for (const id of ids) if (!userConf.optimizeDeps.include.includes(id) && isInstalled(root, id)) userConf.optimizeDeps.include.push(id);
92
255
  }
93
- function getPendingExtractions() {
94
- if (!globalThis[PENDING_KEY]) {
95
- ;
96
- globalThis[PENDING_KEY] = /* @__PURE__ */new Map();
97
- }
98
- return globalThis[PENDING_KEY];
256
+ function svgWebEntry() {
257
+ return normalizePath(import_node_path.default.join(import_node_path.default.dirname(resolve("@tamagui/react-native-svg/package.json")), "dist/esm/index.mjs"));
99
258
  }
100
259
  function tamaguiAliases(options = {}) {
101
- const aliases = [];
102
- if (options.svg) {
103
- aliases.push({
104
- find: "react-native-svg",
105
- replacement: resolve("@tamagui/react-native-svg")
106
- });
107
- }
108
- if (options.rnwLite) {
109
- const rnwlBase = import_node_path.default.dirname(resolve("@tamagui/react-native-web-lite/package.json"));
110
- const rnwl = normalizePath(import_node_path.default.join(rnwlBase, options.rnwLite === "without-animated" ? "dist/esm/without-animated.mjs" : "dist/esm/index.mjs"));
111
- const rnwlFlatModules = (0, import_node_fs.readdirSync)(import_node_path.default.join(rnwlBase, "dist/esm")).filter(file => file.endsWith(".mjs")).map(file => file.slice(0, -".mjs".length)).filter(name => /^[A-Za-z0-9_]+$/.test(name));
112
- aliases.push({
113
- // map deep RNW paths like dist/exports/StyleSheet/preprocess to rnw-lite's flat structure
114
- // extracts the final path segment (e.g. "preprocess" or "createReactDOMStyle")
115
- //
116
- // only match segments rnw-lite actually ships. it implements part of
117
- // react-native-web's export surface, not all of it, and there is no
118
- // flat StyleSheet.mjs. expo sdk 56 added
119
- // expo/src/launch/AppRegistry.web.tsx, which does
120
- // `require('react-native-web/dist/exports/StyleSheet')`; the unscoped
121
- // pattern rewrote that onto a file that does not exist and failed the
122
- // whole optimize. anything lite lacks now falls through to the real
123
- // package.
124
- find: new RegExp(`^react-native(?:-web)?\\/dist\\/(?:exports|modules)\\/(?:.*\\/)?(${rnwlFlatModules.join("|")})$`),
125
- replacement: `${normalizePath(rnwlBase)}/dist/esm/$1.mjs`
126
- }, {
127
- find: /^react-native$/,
128
- replacement: rnwl
129
- }, {
130
- find: /^react-native\/(Libraries\/Utilities\/codegenNativeComponent|Libraries\/Utilities\/codegenNativeCommand)$/,
131
- replacement: `${rnwlBase}/$1`
132
- }, {
133
- find: "react-native/package.json",
134
- replacement: resolve("@tamagui/react-native-web-lite/package.json")
135
- }, {
136
- find: /^react-native-web$/,
137
- replacement: rnwl
138
- });
139
- }
140
- return aliases;
260
+ const aliases = [];
261
+ if (options.svg) {
262
+ const svg = svgWebEntry();
263
+ aliases.push({
264
+ find: "react-native-svg",
265
+ replacement: svg
266
+ }, {
267
+ find: "@tamagui/react-native-svg",
268
+ replacement: svg
269
+ });
270
+ }
271
+ if (options.rnwLite) {
272
+ const rnwlBase = import_node_path.default.dirname(resolve("@tamagui/react-native-web-lite/package.json"));
273
+ const rnwl = normalizePath(import_node_path.default.join(rnwlBase, options.rnwLite === "without-animated" ? "dist/esm/without-animated.mjs" : "dist/esm/index.mjs"));
274
+ const rnwlFlatModules = (0, import_node_fs.readdirSync)(import_node_path.default.join(rnwlBase, "dist/esm")).filter((file) => file.endsWith(".mjs")).map((file) => file.slice(0, -4)).filter((name) => /^[A-Za-z0-9_]+$/.test(name));
275
+ aliases.push({
276
+ find: new RegExp(`^react-native(?:-web)?\\/dist\\/(?:exports|modules)\\/(?:.*\\/)?(${rnwlFlatModules.join("|")})$`),
277
+ replacement: `${normalizePath(rnwlBase)}/dist/esm/$1.mjs`
278
+ }, {
279
+ find: /^react-native$/,
280
+ replacement: rnwl
281
+ }, {
282
+ find: /^react-native\/(Libraries\/Utilities\/codegenNativeComponent|Libraries\/Utilities\/codegenNativeCommand)$/,
283
+ replacement: `${rnwlBase}/$1`
284
+ }, {
285
+ find: "react-native/package.json",
286
+ replacement: resolve("@tamagui/react-native-web-lite/package.json")
287
+ }, {
288
+ find: /^react-native-web$/,
289
+ replacement: rnwl
290
+ });
291
+ }
292
+ return aliases;
293
+ }
294
+ function createTamaguiNativePlugin(tamaguiOptionsIn, nativeContext) {
295
+ let compilerFrontend = new import_static.default.CompilerFrontend();
296
+ const projectDependencies = /* @__PURE__ */ new Set();
297
+ let root = nativeContext?.root || process.cwd();
298
+ let projectPromise = null;
299
+ let nativeOptions = null;
300
+ let rebuildProject = false;
301
+ let generation = 0;
302
+ const loadProject = async (resolveModule) => {
303
+ if (projectPromise) return projectPromise;
304
+ const shouldRebuild = rebuildProject;
305
+ rebuildProject = false;
306
+ const guarded = (async () => {
307
+ projectDependencies.clear();
308
+ const loadedOptions = await import_static.default.loadTamaguiBuildConfigAsync({
309
+ ...tamaguiOptionsIn,
310
+ root,
311
+ platform: "native",
312
+ outputCSS: void 0
313
+ });
314
+ const options = {
315
+ ...loadedOptions,
316
+ root,
317
+ outputCSS: void 0
318
+ };
319
+ nativeOptions = options;
320
+ for (const dependency of import_static.default.getTamaguiBuildConfigDependencies(loadedOptions)) projectDependencies.add(normalizePath(dependency));
321
+ if (options.disable || options.disableExtraction) return null;
322
+ const project = await import_static.default.loadCompilerProject({
323
+ root,
324
+ target: "native",
325
+ options,
326
+ rebuild: shouldRebuild,
327
+ generation: `vite-native:${generation + 1}`,
328
+ missingProjectMessage: "Unable to load the Tamagui project for Vite native compilation",
329
+ async resolveComponents(moduleNames) {
330
+ return Promise.all(moduleNames.map(async (moduleName) => {
331
+ const id = await resolveModule(moduleName);
332
+ projectDependencies.add(normalizePath(id.split(/[?#]/, 1)[0]));
333
+ return {
334
+ moduleName,
335
+ id
336
+ };
337
+ }));
338
+ }
339
+ });
340
+ for (const dependency of project.projectInfo.dependencies ?? []) projectDependencies.add(normalizePath(dependency.split(/[?#]/, 1)[0]));
341
+ const configPath = options.config || "tamagui.config.ts";
342
+ projectDependencies.add(normalizePath(import_node_path.default.isAbsolute(configPath) ? configPath : import_node_path.default.resolve(root, configPath)));
343
+ const buildFile = options.buildFile || "tamagui.build.ts";
344
+ projectDependencies.add(normalizePath(import_node_path.default.isAbsolute(buildFile) ? buildFile : import_node_path.default.resolve(root, buildFile)));
345
+ if (options.themeBuilder?.input) projectDependencies.add(normalizePath(import_node_path.default.isAbsolute(options.themeBuilder.input) ? options.themeBuilder.input : import_node_path.default.resolve(root, options.themeBuilder.input)));
346
+ generation++;
347
+ return project;
348
+ })().catch((error) => {
349
+ if (projectPromise === guarded) projectPromise = null;
350
+ rebuildProject = true;
351
+ throw error;
352
+ });
353
+ projectPromise = guarded;
354
+ return projectPromise;
355
+ };
356
+ return {
357
+ name: "tamagui-native-compiler",
358
+ enforce: "post",
359
+ configResolved(config) {
360
+ root = config.root;
361
+ },
362
+ watchChange(id) {
363
+ if (projectDependencies.has(normalizePath(id.split(/[?#]/, 1)[0]))) {
364
+ rebuildProject = true;
365
+ projectPromise = null;
366
+ compilerFrontend = new import_static.default.CompilerFrontend();
367
+ }
368
+ },
369
+ transform: {
370
+ order: "pre",
371
+ async handler(code, id) {
372
+ const environmentName = nativeContext?.platform || this.environment?.name;
373
+ if (environmentName !== "ios" && environmentName !== "android") return;
374
+ const [validId] = id.split("?");
375
+ if (!validId || !/\.[jt]sx$/.test(validId) || normalizePath(validId).split("/").includes("node_modules")) return;
376
+ const { shouldDisable } = await import_static.default.getPragmaOptions({
377
+ source: code,
378
+ path: validId
379
+ });
380
+ if (shouldDisable) return;
381
+ const resolve2 = async (specifier, importer) => {
382
+ const resolution = await this.resolve(specifier, importer, { skipSelf: true });
383
+ return resolution ? {
384
+ id: resolution.id,
385
+ external: resolution.external === true
386
+ } : null;
387
+ };
388
+ const project = await loadProject(async (specifier) => {
389
+ const resolution = await resolve2(specifier, import_node_path.default.join(root, "__tamagui_native.tsx"));
390
+ if (!resolution) throw new Error(`Unable to resolve native compiler component ${specifier}`);
391
+ return resolution.id;
392
+ });
393
+ if (!project) return;
394
+ for (const dependency of projectDependencies) this.addWatchFile(dependency);
395
+ const result = await compilerFrontend.compile({
396
+ id: validId,
397
+ source: code,
398
+ root,
399
+ target: "native",
400
+ project,
401
+ resolve: resolve2,
402
+ evaluate: async ({ id: moduleId }) => nativeOptions ? import_static.default.evaluateComponentModule(nativeOptions, moduleId) : null,
403
+ load: async (dependencyId) => {
404
+ const cleanDependencyId = dependencyId.split(/[?#]/, 1)[0];
405
+ if (!import_node_path.default.isAbsolute(cleanDependencyId)) return null;
406
+ try {
407
+ return await (0, import_promises.readFile)(cleanDependencyId, "utf8");
408
+ } catch {
409
+ return null;
410
+ }
411
+ }
412
+ });
413
+ for (const dependency of result.plan.dependencies) if (import_node_path.default.isAbsolute(dependency)) this.addWatchFile(dependency);
414
+ if (result.plan.css) throw new Error(`Native Tamagui compilation produced unexpected CSS for ${validId}`);
415
+ return result.output.changed ? {
416
+ code: result.output.code,
417
+ map: result.output.map
418
+ } : void 0;
419
+ }
420
+ }
421
+ };
141
422
  }
142
- function tamaguiPlugin({
143
- disableResolveConfig,
144
- ...tamaguiOptionsIn
145
- } = {}) {
146
- let shouldExtract = !tamaguiOptionsIn.disableExtraction;
147
- let watcher;
148
- const enableNativeEnv = !!globalThis.__vxrnEnableNativeEnv;
149
- const extensions = [`.web.mjs`, `.web.js`, `.web.jsx`, `.web.ts`, `.web.tsx`, ".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"];
150
- (0, import_loadTamagui.loadTamaguiBuildConfig)(tamaguiOptionsIn);
151
- const ensureLoaded = async () => {
152
- const promise = (0, import_loadTamagui.getLoadPromise)();
153
- if (promise) await promise;
154
- const options = (0, import_loadTamagui.getTamaguiOptions)();
155
- if (options) {
156
- shouldExtract = !options.disableExtraction;
157
- }
158
- return options;
159
- };
160
- const getHash = input => (0, import_node_crypto.createHash)("sha1").update(input).digest("base64");
161
- const memoryCache = getSharedCache();
162
- const cssMap = /* @__PURE__ */new Map();
163
- let config;
164
- let server;
165
- const virtualExt = `.tamagui.css`;
166
- const getAbsoluteVirtualFileId = filePath => {
167
- if (filePath.startsWith(config.root)) {
168
- return filePath;
169
- }
170
- return normalizePath(import_node_path.default.join(config.root, filePath));
171
- };
172
- function isNotClient(environment) {
173
- return environment?.name && environment.name !== "client";
174
- }
175
- function isNative(environment) {
176
- return environment?.name && (environment.name === "ios" || environment.name === "android");
177
- }
178
- function invalidateModule(absoluteId) {
179
- if (!server) return;
180
- const {
181
- moduleGraph
182
- } = server;
183
- const modules = moduleGraph.getModulesByFile(absoluteId);
184
- if (modules) {
185
- for (const module2 of modules) {
186
- moduleGraph.invalidateModule(module2);
187
- module2.lastHMRTimestamp = module2.lastInvalidationTimestamp || Date.now();
188
- }
189
- }
190
- }
191
- const basePlugin = {
192
- name: "tamagui",
193
- enforce: "pre",
194
- configureServer(_server) {
195
- server = _server;
196
- },
197
- async buildEnd() {
198
- await watcher?.then(res => {
199
- res?.dispose();
200
- });
201
- },
202
- async config(_, env) {
203
- const options = await ensureLoaded();
204
- if (!options) {
205
- throw new Error(`No tamagui options loaded`);
206
- }
207
- const useReactNativeWebLite = tamaguiOptionsIn.useReactNativeWebLite ?? options.useReactNativeWebLite;
208
- if (!options.disableWatchTamaguiConfig) {
209
- watcher = Static.watchTamaguiConfig({
210
- components: ["tamagui"],
211
- config: "./src/tamagui.config.ts",
212
- ...options
213
- }).catch(err => {
214
- console.error(` [Tamagui] Error watching config: ${err}`);
215
- });
216
- }
217
- return {
218
- envPrefix: ["TAMAGUI_"],
219
- environments: {
220
- client: {
221
- define: {
222
- "process.env.TAMAGUI_IS_CLIENT": JSON.stringify(true),
223
- "process.env.TAMAGUI_ENVIRONMENT": '"client"'
224
- }
225
- }
226
- },
227
- define: {
228
- // reanimated support
229
- _frameTimestamp: void 0,
230
- _WORKLET: false,
231
- __DEV__: `${env.mode === "development"}`,
232
- "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || env.mode),
233
- "process.env.ENABLE_RSC": JSON.stringify(process.env.ENABLE_RSC || ""),
234
- "process.env.ENABLE_STEPS": JSON.stringify(process.env.ENABLE_STEPS || ""),
235
- "process.env.IS_STATIC": JSON.stringify(false),
236
- ...(env.mode === "production" && {
237
- "process.env.TAMAGUI_OPTIMIZE_THEMES": JSON.stringify(true)
238
- })
239
- },
240
- resolve: disableResolveConfig || enableNativeEnv ? {} : {
241
- extensions,
242
- alias: {
243
- ...(options.platform !== "native" && {
244
- "react-native/Libraries/Renderer/shims/ReactFabric": resolve("@tamagui/proxy-worm"),
245
- "react-native/Libraries/Utilities/codegenNativeComponent": resolve("@tamagui/proxy-worm"),
246
- "react-native-svg": resolve("@tamagui/react-native-svg"),
247
- ...(!useReactNativeWebLite && {
248
- "react-native": resolve("react-native-web")
249
- })
250
- })
251
- }
252
- }
253
- };
254
- }
255
- };
256
- const rnwLitePlugin = {
257
- name: "tamagui-rnw-lite",
258
- // framework plugins may add their default react-native-web aliases from a
259
- // normal config hook. apply the explicit lite choice after those defaults.
260
- enforce: "post",
261
- config() {
262
- if (enableNativeEnv) {
263
- return {};
264
- }
265
- const options = (0, import_loadTamagui.getTamaguiOptions)();
266
- const useReactNativeWebLite = tamaguiOptionsIn.useReactNativeWebLite ?? options?.useReactNativeWebLite;
267
- if (!useReactNativeWebLite) {
268
- return {};
269
- }
270
- const include = [];
271
- for (const dependency of ["memoize-one", "@react-native/normalize-color"]) {
272
- if (isInstalled(process.cwd(), dependency)) include.push(dependency);
273
- }
274
- return {
275
- resolve: {
276
- alias: tamaguiAliases({
277
- rnwLite: useReactNativeWebLite
278
- })
279
- },
280
- optimizeDeps: {
281
- // upstream react-native-web must not be pre-bundled when aliased to lite
282
- exclude: ["react-native-web"],
283
- include
284
- }
285
- };
286
- }
287
- };
288
- const extractPlugin = {
289
- name: "tamagui-extract",
290
- enforce: "pre",
291
- async config(userConf) {
292
- const options = await ensureLoaded();
293
- userConf.optimizeDeps ||= {};
294
- userConf.optimizeDeps.include ||= [];
295
- userConf.optimizeDeps.include.push("inline-style-prefixer");
296
- addIfInstalled(userConf, userConf.root, ["@tamagui/toast", "@tamagui/toast/v2", "@tamagui/sheet", "@tamagui/sheet/controller"]);
297
- userConf.resolve ||= {};
298
- userConf.resolve.dedupe ||= [];
299
- for (const id of ["tamagui", "@tamagui/core", "@tamagui/web", "@tamagui/toast", "@tamagui/sheet"]) {
300
- if (!userConf.resolve.dedupe.includes(id) && isInstalled(userConf.root || process.cwd(), id)) {
301
- userConf.resolve.dedupe.push(id);
302
- }
303
- }
304
- if (!shouldExtract) return;
305
- userConf.optimizeDeps.include.push("@tamagui/core/inject-styles");
306
- },
307
- async configResolved(resolvedConfig) {
308
- config = resolvedConfig;
309
- },
310
- async resolveId(source) {
311
- if (!shouldExtract) return;
312
- if (isNative(this.environment)) {
313
- return;
314
- }
315
- if (isNotClient(this.environment)) {
316
- return;
317
- }
318
- const [validId, query] = source.split("?");
319
- if (!validId.endsWith(virtualExt)) {
320
- return;
321
- }
322
- const absoluteId = source.startsWith(config.root) ? source : getAbsoluteVirtualFileId(validId);
323
- if (cssMap.has(absoluteId)) {
324
- return absoluteId + (query ? `?${query}` : "");
325
- }
326
- },
327
- async load(id) {
328
- if (!shouldExtract) return;
329
- const options = (0, import_loadTamagui.getTamaguiOptions)();
330
- if (options?.disable) {
331
- return;
332
- }
333
- if (isNative(this.environment)) {
334
- return;
335
- }
336
- if (isNotClient(this.environment)) {
337
- return;
338
- }
339
- const [validId] = id.split("?");
340
- return cssMap.get(validId);
341
- },
342
- transform: {
343
- order: "pre",
344
- async handler(code, id) {
345
- const options = await ensureLoaded();
346
- await (0, import_loadTamagui.ensureFullConfigLoaded)();
347
- if (options?.disable) {
348
- return;
349
- }
350
- if (isNative(this.environment)) {
351
- return;
352
- }
353
- const [validId] = id.split("?");
354
- if (!validId.endsWith(".tsx")) {
355
- return;
356
- }
357
- const {
358
- shouldDisable,
359
- shouldPrintDebug
360
- } = await (0, import_static_worker.getPragmaOptions)({
361
- source: code,
362
- path: validId
363
- });
364
- if (shouldPrintDebug) {
365
- console.trace(`Current file: ${id} in environment: ${this.environment?.name}, shouldDisable: ${shouldDisable}`);
366
- console.info(`
367
-
368
- Original source:
369
- ${code}
370
-
423
+ function tamaguiNativePlugin(tamaguiOptionsIn = {}) {
424
+ const plugin = createTamaguiNativePlugin(tamaguiOptionsIn);
425
+ const api = plugin.api && typeof plugin.api === "object" ? plugin.api : {};
426
+ return {
427
+ ...plugin,
428
+ api: {
429
+ ...api,
430
+ vxrnNative: (context) => createTamaguiNativePlugin(tamaguiOptionsIn, context)
431
+ }
432
+ };
433
+ }
434
+ function createTamaguiPlugins({ disableResolveConfig, wrapExtractedCSS = (css) => css, zeroIslandBuild, ...tamaguiOptionsIn } = {}) {
435
+ let shouldExtract = !tamaguiOptionsIn.disableExtraction;
436
+ const enableNativeEnv = !!globalThis.__vxrnEnableNativeEnv;
437
+ const tamaguiLoader = (0, import_loadTamagui.createViteTamaguiLoader)(tamaguiOptionsIn);
438
+ const compilerFrontends = /* @__PURE__ */ new WeakMap();
439
+ const getCompilerFrontend = (environment) => {
440
+ let frontend = compilerFrontends.get(environment);
441
+ if (!frontend) {
442
+ frontend = new import_static.default.CompilerFrontend();
443
+ compilerFrontends.set(environment, frontend);
444
+ }
445
+ return frontend;
446
+ };
447
+ const pluginInstanceId = getNextPluginInstanceId();
448
+ const configuredEvaluationPackages = /* @__PURE__ */ new Set();
449
+ let buildEnvironmentPromise = null;
450
+ let buildCleanupPromise = null;
451
+ const activeBuildEnvironments = /* @__PURE__ */ new Set();
452
+ const compilerReports = process.env.TAMAGUI_COMPILER_STATS || process.env.TAMAGUI_COMPILER_STATS_FILE ? /* @__PURE__ */ new Map() : null;
453
+ const releaseBuildEnvironment = async (environment) => {
454
+ if (!activeBuildEnvironments.delete(environment) || activeBuildEnvironments.size) return;
455
+ if (compilerReports?.size) reportCompilerStats(config?.root ?? process.cwd(), compilerReports);
456
+ const currentCleanup = Promise.resolve().then(async () => {
457
+ try {
458
+ await tamaguiLoader.cleanup();
459
+ } finally {
460
+ buildEnvironmentPromise = null;
461
+ }
462
+ });
463
+ buildCleanupPromise = currentCleanup;
464
+ try {
465
+ await currentCleanup;
466
+ } finally {
467
+ if (buildCleanupPromise === currentCleanup) buildCleanupPromise = null;
468
+ }
469
+ };
470
+ const extensions = [
471
+ `.web.mjs`,
472
+ `.web.js`,
473
+ `.web.jsx`,
474
+ `.web.ts`,
475
+ `.web.tsx`,
476
+ ".mjs",
477
+ ".js",
478
+ ".mts",
479
+ ".ts",
480
+ ".jsx",
481
+ ".tsx",
482
+ ".json"
483
+ ];
484
+ const getEvaluationEnvironmentOptions = (resolvedRoot, userNoExternal) => ({
485
+ consumer: "server",
486
+ keepProcessEnv: true,
487
+ define: {
488
+ "process.env.IS_STATIC": JSON.stringify("is_static"),
489
+ "process.env.TAMAGUI_IS_CLIENT": JSON.stringify(false),
490
+ "process.env.TAMAGUI_IS_SERVER": JSON.stringify(true),
491
+ "process.env.TAMAGUI_TARGET": JSON.stringify("web"),
492
+ "process.env.TAMAGUI_ENVIRONMENT": JSON.stringify(import_loadTamagui.TAMAGUI_EVALUATION_ENVIRONMENT),
493
+ "process.env.TAMAGUI_RUNTIME": JSON.stringify("full"),
494
+ "process.env.TAMAGUI_DID_OUTPUT_CSS": JSON.stringify(""),
495
+ "process.env.VITE_ENVIRONMENT": JSON.stringify("ssr"),
496
+ "process.env.TAMAGUI_DISABLE_SLIDER_INTERVAL": JSON.stringify("1")
497
+ },
498
+ resolve: {
499
+ conditions: [TAMAGUI_COMPILER_CONDITION, ...import_vite.defaultClientConditions],
500
+ mainFields: [...import_vite.defaultClientMainFields],
501
+ noExternal: mergeEvaluationNoExternal([
502
+ inlineEvaluationTamaguiPackage,
503
+ ...configuredEvaluationPackages,
504
+ ...scanInstalledTamaguiPackages(resolvedRoot, configuredEvaluationPackages).compilerCondition
505
+ ], userNoExternal),
506
+ extensions
507
+ },
508
+ dev: {
509
+ createEnvironment(name, resolved) {
510
+ const evaluationConfig = createServeEvaluationConfig(resolved, configuredEvaluationPackages);
511
+ return (0, import_vite.createRunnableDevEnvironment)(name, evaluationConfig);
512
+ },
513
+ moduleRunnerTransform: true
514
+ }
515
+ });
516
+ tamaguiLoader.loadTamaguiBuildConfig();
517
+ const ensureLoaded = async () => {
518
+ const promise = tamaguiLoader.getLoadPromise();
519
+ if (promise) await promise;
520
+ const options = tamaguiLoader.getTamaguiOptions();
521
+ if (options) shouldExtract = !options.disableExtraction;
522
+ return options;
523
+ };
524
+ const getHash = (input) => (0, import_node_crypto.createHash)("sha1").update(input).digest("base64");
525
+ const cssMap = /* @__PURE__ */ new Map();
526
+ const transformedModuleIds = /* @__PURE__ */ new Set();
527
+ const compilerHotUpdateSignatures = /* @__PURE__ */ new Map();
528
+ const compilerHotReloadSignatures = /* @__PURE__ */ new Map();
529
+ let config;
530
+ let server;
531
+ let zero = null;
532
+ let zeroReceipt = null;
533
+ let zeroBuildFailed = false;
534
+ let globalCSS = null;
535
+ let globalCSSExpected = null;
536
+ let zeroHtmlEntries = 0;
537
+ let zeroDevIslands = Promise.resolve();
538
+ const virtualExt = `.tamagui.css`;
539
+ const getAbsoluteVirtualFileId = (filePath) => {
540
+ if (filePath.startsWith(config.root)) return filePath;
541
+ return normalizePath(import_node_path.default.join(config.root, filePath));
542
+ };
543
+ const isAppJSXSource = (filePath) => {
544
+ if (!/\.[jt]sx$/.test(filePath)) return false;
545
+ const relative = import_node_path.default.relative(config.root, filePath);
546
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${import_node_path.default.sep}`) && !relative.split(import_node_path.default.sep).includes("node_modules");
547
+ };
548
+ const isFrameworkAnalysisRequest = (id) => id.includes("__react-router-build-client-route");
549
+ function isNotClient(environment) {
550
+ return environment?.name && environment.name !== "client";
551
+ }
552
+ const isDevEnvironment = (environment) => environment.mode === "dev";
553
+ function isNative(environment) {
554
+ return environment?.name && (environment.name === "ios" || environment.name === "android");
555
+ }
556
+ function invalidateCompilerModules() {
557
+ if (server) {
558
+ const ids = /* @__PURE__ */ new Set([...transformedModuleIds, ...cssMap.keys()]);
559
+ for (const environment of Object.values(server.environments)) {
560
+ if (environment.name === import_loadTamagui.TAMAGUI_EVALUATION_ENVIRONMENT) continue;
561
+ for (const id of ids) {
562
+ const modules = environment.moduleGraph.getModulesByFile(id);
563
+ if (!modules) continue;
564
+ for (const module2 of modules) environment.moduleGraph.invalidateModule(module2);
565
+ }
566
+ }
567
+ }
568
+ cssMap.clear();
569
+ }
570
+ return {
571
+ plugins: [
572
+ {
573
+ name: "tamagui",
574
+ enforce: "pre",
575
+ configureServer(_server) {
576
+ server = _server;
577
+ const evaluationEnvironment = server.environments[import_loadTamagui.TAMAGUI_EVALUATION_ENVIRONMENT];
578
+ if (!(0, import_vite.isRunnableDevEnvironment)(evaluationEnvironment)) throw new Error(`The ${import_loadTamagui.TAMAGUI_EVALUATION_ENVIRONMENT} Vite environment must support ModuleRunner evaluation`);
579
+ tamaguiLoader.setEnvironment(evaluationEnvironment);
580
+ },
581
+ async buildEnd() {
582
+ await releaseBuildEnvironment(this.environment);
583
+ },
584
+ async config(userConfig, env) {
585
+ const options = await ensureLoaded();
586
+ if (!options) throw new Error(`No tamagui options loaded`);
587
+ const useReactNativeWebLite = tamaguiOptionsIn.useReactNativeWebLite ?? options.useReactNativeWebLite;
588
+ for (const source of [options.config, ...options.components || []]) {
589
+ const packageName = getEvaluationPackageName(source);
590
+ if (packageName) configuredEvaluationPackages.add(packageName);
591
+ }
592
+ const resolvedRoot = userConfig.root ? import_node_path.default.resolve(userConfig.root) : process.cwd();
593
+ zero = zeroIslandBuild ? null : await (0, import_zeroRuntime.createZeroRuntimeController)(options, resolvedRoot, userConfig.base || "/");
594
+ globalCSS = zeroIslandBuild || env.command !== "build" ? null : import_static.default.resolveGlobalCSSOwnership(options, resolvedRoot);
595
+ return {
596
+ envPrefix: ["TAMAGUI_"],
597
+ environments: {
598
+ client: { define: {
599
+ "process.env.TAMAGUI_IS_CLIENT": JSON.stringify(true),
600
+ "process.env.TAMAGUI_ENVIRONMENT": "\"client\"",
601
+ ...zero?.isEnforcing && { "process.env.TAMAGUI_RUNTIME": JSON.stringify("zero") },
602
+ ...globalCSS && { "process.env.TAMAGUI_DID_OUTPUT_CSS": JSON.stringify("1") }
603
+ } },
604
+ ssr: { define: { ...globalCSS && { "process.env.TAMAGUI_DID_OUTPUT_CSS": JSON.stringify("1") } } },
605
+ [import_loadTamagui.TAMAGUI_EVALUATION_ENVIRONMENT]: getEvaluationEnvironmentOptions(resolvedRoot, userConfig.environments?.[import_loadTamagui.TAMAGUI_EVALUATION_ENVIRONMENT]?.resolve?.noExternal)
606
+ },
607
+ define: {
608
+ "process.env.TAMAGUI_RUNTIME": JSON.stringify("full"),
609
+ _frameTimestamp: void 0,
610
+ _WORKLET: false,
611
+ __DEV__: `${env.mode === "development"}`,
612
+ "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || env.mode),
613
+ "process.env.ENABLE_RSC": JSON.stringify(process.env.ENABLE_RSC || ""),
614
+ "process.env.ENABLE_STEPS": JSON.stringify(process.env.ENABLE_STEPS || ""),
615
+ "process.env.IS_STATIC": JSON.stringify(false),
616
+ ...env.mode === "production" && { "process.env.TAMAGUI_OPTIMIZE_THEMES": JSON.stringify(true) }
617
+ },
618
+ resolve: disableResolveConfig || enableNativeEnv ? {} : {
619
+ extensions,
620
+ alias: { ...options.platform !== "native" && {
621
+ "react-native/Libraries/Renderer/shims/ReactFabric": resolve("@tamagui/proxy-worm"),
622
+ "react-native/Libraries/Utilities/codegenNativeComponent": resolve("@tamagui/proxy-worm"),
623
+ "react-native-svg": svgWebEntry(),
624
+ "@tamagui/react-native-svg": svgWebEntry(),
625
+ ...!useReactNativeWebLite && { "react-native": resolve("react-native-web") }
626
+ } }
627
+ }
628
+ };
629
+ }
630
+ },
631
+ {
632
+ name: "tamagui-rnw-lite",
633
+ enforce: "post",
634
+ config() {
635
+ if (enableNativeEnv) return {};
636
+ const options = tamaguiLoader.getTamaguiOptions();
637
+ const useReactNativeWebLite = tamaguiOptionsIn.useReactNativeWebLite ?? options?.useReactNativeWebLite;
638
+ if (!useReactNativeWebLite) return {};
639
+ const include = [];
640
+ for (const dependency of ["memoize-one", "@react-native/normalize-color"]) if (isInstalled(process.cwd(), dependency)) include.push(dependency);
641
+ return {
642
+ resolve: { alias: tamaguiAliases({ rnwLite: useReactNativeWebLite }) },
643
+ ssr: { noExternal: [
644
+ /^@tamagui\//,
645
+ "tamagui",
646
+ "react-native",
647
+ "react-native-web"
648
+ ] },
649
+ optimizeDeps: {
650
+ exclude: ["react-native-web"],
651
+ include
652
+ }
653
+ };
654
+ }
655
+ },
656
+ {
657
+ name: "tamagui-extract",
658
+ enforce: "pre",
659
+ async config(userConf) {
660
+ await ensureLoaded();
661
+ userConf.optimizeDeps ||= {};
662
+ userConf.optimizeDeps.include ||= [];
663
+ userConf.optimizeDeps.include.push("inline-style-prefixer");
664
+ addIfInstalled(userConf, userConf.root, ["@react-native/normalize-color"]);
665
+ addIfInstalled(userConf, userConf.root, [
666
+ "@tamagui/core",
667
+ "@tamagui/core/theme-update",
668
+ "@tamagui/web",
669
+ "@tamagui/web/theme-update",
670
+ "@tamagui/animations-css",
671
+ "@tamagui/animations-css/extras",
672
+ "@tamagui/toast",
673
+ "@tamagui/sheet",
674
+ "@tamagui/sheet/controller"
675
+ ]);
676
+ userConf.resolve ||= {};
677
+ userConf.resolve.dedupe ||= [];
678
+ for (const id of [
679
+ "tamagui",
680
+ "@tamagui/core",
681
+ "@tamagui/core/theme-update",
682
+ "@tamagui/web",
683
+ "@tamagui/web/theme-update",
684
+ "@tamagui/animations-css",
685
+ "@tamagui/toast",
686
+ "@tamagui/sheet"
687
+ ]) if (!userConf.resolve.dedupe.includes(id) && isInstalled(userConf.root || process.cwd(), id)) userConf.resolve.dedupe.push(id);
688
+ if (!shouldExtract) return;
689
+ userConf.optimizeDeps.include.push("@tamagui/core/inject-styles");
690
+ },
691
+ async configResolved(resolvedConfig) {
692
+ config = resolvedConfig;
693
+ },
694
+ async buildStart() {
695
+ const buildConfig = this.environment.getTopLevelConfig();
696
+ if (buildConfig.command !== "build") return;
697
+ const pendingCleanup = buildCleanupPromise;
698
+ if (pendingCleanup) await pendingCleanup;
699
+ const buildEnvironment = this.environment;
700
+ activeBuildEnvironments.add(buildEnvironment);
701
+ try {
702
+ if (!tamaguiLoader.getEnvironment()) {
703
+ await tamaguiLoader.loadTamaguiBuildConfig();
704
+ buildEnvironmentPromise ||= (async () => {
705
+ const evaluationConfig = await createOwnedEvaluationConfig(buildConfig, configuredEvaluationPackages);
706
+ const evaluationEnvironment = (0, import_vite.createRunnableDevEnvironment)(import_loadTamagui.TAMAGUI_EVALUATION_ENVIRONMENT, evaluationConfig, { hot: false });
707
+ try {
708
+ await evaluationEnvironment.init();
709
+ } catch (error) {
710
+ await evaluationEnvironment.close().catch(() => void 0);
711
+ throw error;
712
+ }
713
+ tamaguiLoader.setEnvironment(evaluationEnvironment, { owned: true });
714
+ })();
715
+ await buildEnvironmentPromise;
716
+ }
717
+ } catch (error) {
718
+ await releaseBuildEnvironment(buildEnvironment);
719
+ throw error;
720
+ }
721
+ },
722
+ hotUpdate: {
723
+ order: "post",
724
+ async handler(options) {
725
+ if (!tamaguiLoader.isEvaluationDependency(options.file)) {
726
+ if (this.environment.name !== "client") return;
727
+ const compilerFrontend = getCompilerFrontend(this.environment);
728
+ const source = options.type === "delete" ? null : await options.read();
729
+ const affectedModules = /* @__PURE__ */ new Set();
730
+ const compilerHmrRoots = new Set(compilerFrontend.dependentsOf(options.file));
731
+ if (compilerHmrRoots.size || compilerFrontend.has(options.file)) compilerHmrRoots.add(options.file);
732
+ if (compilerFrontend.has(options.file) || compilerHmrRoots.size > 0) {
733
+ if (!(await ensureLoaded())?.disable) {
734
+ const invalidatedIds = options.type === "delete" ? (await compilerFrontend.remove(options.file)).invalidatedIds : await compilerFrontend.update({
735
+ id: options.file,
736
+ source,
737
+ root: config.root,
738
+ target: "web",
739
+ environment: this.environment.name,
740
+ project: {
741
+ ...await tamaguiLoader.getCompilerProject(),
742
+ generation: `${pluginInstanceId}:${tamaguiLoader.getGeneration()}`
743
+ },
744
+ resolve: async (specifier, importer) => {
745
+ const resolution = await this.environment.pluginContainer.resolveId(specifier, importer);
746
+ return resolution ? {
747
+ id: resolution.id,
748
+ external: resolution.external === true
749
+ } : null;
750
+ },
751
+ load: async (dependencyId) => {
752
+ const cleanDependencyId = dependencyId.split(/[?#]/, 1)[0];
753
+ if (!import_node_path.default.isAbsolute(cleanDependencyId)) return null;
754
+ try {
755
+ return await (0, import_promises.readFile)(cleanDependencyId, "utf8");
756
+ } catch {
757
+ return null;
758
+ }
759
+ }
760
+ });
761
+ for (const invalidatedId of invalidatedIds) {
762
+ for (const module2 of this.environment.moduleGraph.getModulesByFile(invalidatedId) ?? []) {
763
+ this.environment.moduleGraph.invalidateModule(module2);
764
+ if (compilerHmrRoots.has(invalidatedId) || module2.isSelfAccepting) affectedModules.add(module2);
765
+ }
766
+ const cssId = getAbsoluteVirtualFileId(`${invalidatedId}${virtualExt}`);
767
+ const cssModule = this.environment.moduleGraph.getModuleById(cssId);
768
+ if (cssModule) {
769
+ this.environment.moduleGraph.invalidateModule(cssModule);
770
+ affectedModules.add(cssModule);
771
+ }
772
+ }
773
+ }
774
+ }
775
+ return affectedModules.size ? [...affectedModules] : void 0;
776
+ }
777
+ const signature = await (async () => {
778
+ if (options.type === "delete") return getHash(`${options.type}:${options.file}`);
779
+ try {
780
+ return getHash(`${options.type}:${options.file}:${await options.read()}`);
781
+ } catch {
782
+ return getHash(`${options.type}:${options.file}:${options.timestamp}`);
783
+ }
784
+ })();
785
+ if (compilerHotUpdateSignatures.get(options.file) !== signature) {
786
+ compilerHotUpdateSignatures.set(options.file, signature);
787
+ tamaguiLoader.invalidate(options.file);
788
+ invalidateCompilerModules();
789
+ }
790
+ if (this.environment.name === "client" && compilerHotReloadSignatures.get(options.file) !== signature) {
791
+ compilerHotReloadSignatures.set(options.file, signature);
792
+ this.environment.hot.send({
793
+ type: "full-reload",
794
+ path: "*",
795
+ triggeredBy: options.file
796
+ });
797
+ }
798
+ return [];
799
+ }
800
+ },
801
+ async watchChange(id) {
802
+ if (config.command !== "build") return;
803
+ if (tamaguiLoader.isEvaluationDependency(id)) {
804
+ tamaguiLoader.invalidate(id);
805
+ invalidateCompilerModules();
806
+ }
807
+ },
808
+ async resolveId(source) {
809
+ if (isNative(this.environment)) return;
810
+ if (isNotClient(this.environment)) return;
811
+ if (!shouldExtract) return;
812
+ const [validId, query] = source.split("?");
813
+ if (!validId.endsWith(virtualExt)) return;
814
+ const absoluteId = validId.startsWith(config.root) ? validId : getAbsoluteVirtualFileId(validId);
815
+ if (cssMap.has(absoluteId)) return absoluteId + (query ? `?${query}` : "");
816
+ },
817
+ async load(id) {
818
+ if (tamaguiLoader.getTamaguiOptions()?.disable) return;
819
+ if (isNative(this.environment)) return;
820
+ if (isNotClient(this.environment)) return;
821
+ if (!shouldExtract) return;
822
+ const [validId] = id.split("?");
823
+ if (!validId.endsWith(virtualExt)) return;
824
+ if (isDevEnvironment(this.environment)) {
825
+ const importer = this.environment.moduleGraph.getModuleById(validId.slice(0, -virtualExt.length));
826
+ if (importer && importer.transformResult == null) await this.environment.transformRequest(importer.url);
827
+ }
828
+ return cssMap.get(validId);
829
+ }
830
+ },
831
+ {
832
+ name: "tamagui-compiler",
833
+ enforce: "post",
834
+ transform: {
835
+ order: "pre",
836
+ async handler(code, id) {
837
+ if (this.environment?.name === import_loadTamagui.TAMAGUI_EVALUATION_ENVIRONMENT) return;
838
+ if (!tamaguiLoader.getEnvironment()) return;
839
+ if (isNative(this.environment)) return;
840
+ const [validId] = id.split("?");
841
+ if (isFrameworkAnalysisRequest(id) || !isAppJSXSource(validId) || !/\.[jt]sx$/.test(validId)) return;
842
+ if ((await ensureLoaded())?.disable || !shouldExtract) return;
843
+ const { shouldDisable } = await import_static.default.getPragmaOptions({
844
+ source: code,
845
+ path: validId
846
+ });
847
+ if (shouldDisable) return;
848
+ const evaluationDependencies = await tamaguiLoader.ensureFullConfigLoaded();
849
+ for (const dependency of evaluationDependencies) this.addWatchFile(dependency);
850
+ const compilerProject = await tamaguiLoader.getCompilerProject();
851
+ const result = await getCompilerFrontend(this.environment).compile({
852
+ id: validId,
853
+ source: code,
854
+ root: config.root,
855
+ target: "web",
856
+ environment: this.environment.name,
857
+ project: {
858
+ ...compilerProject,
859
+ generation: `${pluginInstanceId}:${tamaguiLoader.getGeneration()}`,
860
+ zeroRuntime: zero !== null
861
+ },
862
+ resolve: async (specifier, importer) => {
863
+ const resolution = await this.resolve(specifier, importer, { skipSelf: true });
864
+ return resolution ? {
865
+ id: resolution.id,
866
+ external: resolution.external === true
867
+ } : null;
868
+ },
869
+ evaluate: ({ id: moduleId }) => tamaguiLoader.evaluateModule(moduleId),
870
+ load: async (dependencyId) => {
871
+ const cleanDependencyId = dependencyId.split(/[?#]/, 1)[0];
872
+ if (!import_node_path.default.isAbsolute(cleanDependencyId)) return null;
873
+ try {
874
+ return await (0, import_promises.readFile)(cleanDependencyId, "utf8");
875
+ } catch {
876
+ return null;
877
+ }
878
+ }
879
+ });
880
+ transformedModuleIds.add(validId);
881
+ compilerReports?.set(validId, {
882
+ stats: result.plan.stats,
883
+ diagnostics: result.plan.diagnostics
884
+ });
885
+ for (const dependency of result.plan.dependencies) if (import_node_path.default.isAbsolute(dependency)) this.addWatchFile(dependency);
886
+ if (zeroIslandBuild) {
887
+ zeroIslandBuild.artifact.setIslandModuleCSS(zeroIslandBuild.islandId, validId, wrapExtractedCSS(result.plan.css));
888
+ return result.output.changed ? {
889
+ code: result.output.code,
890
+ map: result.output.map
891
+ } : void 0;
892
+ }
893
+ if (zero) {
894
+ const zeroResult = import_static.default.transformZeroModule({
895
+ mode: zero.isEnforcing ? "enforce" : "report",
896
+ id: validId,
897
+ root: config.root,
898
+ source: code,
899
+ plan: result.plan,
900
+ config: await tamaguiLoader.getTamaguiConfig(),
901
+ isTamaguiSpecifier: import_static.default.isTamaguiSpecifier,
902
+ resolveIslandLoader: (specifier) => {
903
+ const islandId = zero.loaderIds.get((0, import_zeroRuntime.zeroModuleKey)(import_node_path.default.resolve(import_node_path.default.dirname(validId), specifier)));
904
+ return islandId ? { islandId } : null;
905
+ },
906
+ resolveIslandModule: (specifier) => zero.islandModuleIds.get((0, import_zeroRuntime.zeroModuleKey)(import_node_path.default.resolve(import_node_path.default.dirname(validId), specifier))) ?? null
907
+ });
908
+ zero.transformed.add(validId);
909
+ if (zeroResult.erased.exports.length) zero.erasedExports.set(validId, zeroResult.erased.exports);
910
+ for (const violation of zeroResult.violations) {
911
+ const { line, column } = import_static.default.offsetToLineColumn(code, violation.span.start);
912
+ zero.violations.push({
913
+ file: import_node_path.default.relative(config.root, validId),
914
+ line,
915
+ column,
916
+ rule: violation.rule,
917
+ code: violation.code,
918
+ component: violation.component,
919
+ message: violation.message
920
+ });
921
+ }
922
+ if (zero.isEnforcing) {
923
+ import_static.default.mergeIslandBridges(zero.bridges, zeroResult.bridges);
924
+ const moduleCSS = [wrapExtractedCSS(result.plan.css), ...zeroResult.bridgeCSS.values()].filter(Boolean).join("\n");
925
+ if (config.command !== "build") {
926
+ let cssImport2 = "";
927
+ if (moduleCSS) {
928
+ const rootRelativeId = `${validId}${virtualExt}`;
929
+ cssMap.set(getAbsoluteVirtualFileId(rootRelativeId), moduleCSS);
930
+ this.addWatchFile(rootRelativeId);
931
+ cssImport2 = `
932
+ import "${rootRelativeId}";`;
933
+ }
934
+ return {
935
+ code: `${zeroResult.output.code}${cssImport2}`,
936
+ map: zeroResult.output.map
937
+ };
938
+ }
939
+ for (const [identifier, rules] of zeroResult.bridgeCSS) zero.artifact.setBridgeRules(identifier, rules);
940
+ zero.artifact.setZeroModuleCSS(validId, wrapExtractedCSS(result.plan.css));
941
+ return zeroResult.output.changed ? {
942
+ code: zeroResult.output.code,
943
+ map: zeroResult.output.map
944
+ } : void 0;
945
+ }
946
+ }
947
+ const isSSR = isNotClient(this.environment);
948
+ let cssImport = null;
949
+ if (result.plan.css) {
950
+ const rootRelativeId = `${validId}${virtualExt}`;
951
+ const absoluteId = getAbsoluteVirtualFileId(rootRelativeId);
952
+ cssMap.set(absoluteId, wrapExtractedCSS(result.plan.css));
953
+ this.addWatchFile(rootRelativeId);
954
+ if (!isSSR) cssImport = `import "${rootRelativeId}";`;
955
+ }
956
+ const finalCode = cssImport ? `${result.output.code}
957
+ ${cssImport}` : result.output.code;
958
+ return result.output.changed || cssImport ? {
959
+ code: finalCode,
960
+ map: result.output.map
961
+ } : void 0;
962
+ }
963
+ }
964
+ },
965
+ {
966
+ name: "tamagui-zero-runtime",
967
+ enforce: "post",
968
+ async buildStart() {
969
+ if (!zero || this.environment.name !== "client") return;
970
+ await tamaguiLoader.ensureFullConfigLoaded();
971
+ const tamaguiConfig = await tamaguiLoader.getTamaguiConfig();
972
+ if (!tamaguiConfig) throw new Error(`[tamagui zero-runtime] the Tamagui config did not evaluate, so no CSS artifact can be generated`);
973
+ zero.violations.length = 0;
974
+ zero.transformed.clear();
975
+ zero.erasedExports.clear();
976
+ if (!zero.isEnforcing) return;
977
+ import_static.default.assertZeroConfigDrivers(tamaguiConfig);
978
+ zero.artifact.clearGraphs();
979
+ zero.bridges.clear();
980
+ zeroHtmlEntries = 0;
981
+ zero.artifact.setConfigCSS(tamaguiConfig.getCSS());
982
+ if (config.command !== "build") {
983
+ const islands = zero;
984
+ zeroDevIslands = Promise.all(islands.resolved.islands.map((island) => (0, import_zeroRuntime.buildIsland)({
985
+ island,
986
+ controller: islands,
987
+ root: config.root,
988
+ outDir: zeroDevIslandDir(islands),
989
+ mode: "development"
990
+ })));
991
+ await zeroDevIslands;
992
+ }
993
+ },
994
+ async configureServer(devServer) {
995
+ if (!zero?.isEnforcing) return;
996
+ const islandBase = `${zero.cssHref.replace(import_zeroRuntime.ZERO_CSS_FILENAME, "")}${import_zeroRuntime.ZERO_ISLAND_DIRNAME}/`;
997
+ devServer.middlewares.use(async (request, response, next) => {
998
+ const url = (request.url || "").split("?")[0];
999
+ if (url !== zero.cssHref && !url.startsWith(islandBase)) return next();
1000
+ await zeroDevIslands;
1001
+ if (url === zero.cssHref) {
1002
+ response.setHeader("content-type", "text/css; charset=utf-8");
1003
+ response.setHeader("cache-control", "no-cache");
1004
+ response.end(zero.artifact.css());
1005
+ return;
1006
+ }
1007
+ const islandId = url.slice(islandBase.length).replace(/\.js$/, "");
1008
+ const file = import_node_path.default.join(zeroDevIslandDir(zero), import_zeroRuntime.ZERO_ISLAND_DIRNAME, `${islandId}.js`);
1009
+ if (!(0, import_node_fs.existsSync)(file)) return next();
1010
+ response.setHeader("content-type", "text/javascript; charset=utf-8");
1011
+ response.setHeader("cache-control", "no-cache");
1012
+ response.end((0, import_node_fs.readFileSync)(file));
1013
+ });
1014
+ },
1015
+ buildEnd(error) {
1016
+ if (!zero || this.environment.name !== "client") return;
1017
+ if (error) {
1018
+ zeroBuildFailed = true;
1019
+ return;
1020
+ }
1021
+ if (!zero.isEnforcing) return;
1022
+ const importers = /* @__PURE__ */ new Map();
1023
+ for (const moduleId of this.getModuleIds()) importers.set(moduleId, this.getModuleInfo(moduleId)?.importers ?? []);
1024
+ const escape = import_static.default.erasedExportEscape({
1025
+ integration: "vite",
1026
+ transformed: zero.transformed,
1027
+ erasedExports: zero.erasedExports,
1028
+ importersOf: importers
1029
+ });
1030
+ if (escape) {
1031
+ zeroBuildFailed = true;
1032
+ throw new Error(escape);
1033
+ }
1034
+ },
1035
+ transformIndexHtml: {
1036
+ order: "post",
1037
+ handler(html) {
1038
+ if (!zero?.isEnforcing) return;
1039
+ zeroHtmlEntries++;
1040
+ return {
1041
+ html,
1042
+ tags: [{
1043
+ tag: "link",
1044
+ attrs: {
1045
+ rel: "stylesheet",
1046
+ href: zero.cssHref
1047
+ },
1048
+ injectTo: "head"
1049
+ }]
1050
+ };
1051
+ }
1052
+ },
1053
+ generateBundle(_outputOptions, bundle) {
1054
+ if (!zero?.isEnforcing || this.environment.name !== "client") return;
1055
+ const importers = /* @__PURE__ */ new Map();
1056
+ for (const moduleId of this.getModuleIds()) for (const imported of this.getModuleInfo(moduleId)?.importedIds ?? []) {
1057
+ const list = importers.get(imported);
1058
+ if (list) list.push(moduleId);
1059
+ else importers.set(imported, [moduleId]);
1060
+ }
1061
+ const entries = [];
1062
+ const modules = [];
1063
+ for (const chunk of Object.values(bundle)) {
1064
+ if (chunk.type !== "chunk") continue;
1065
+ for (const moduleId of Object.keys(chunk.modules)) {
1066
+ modules.push({
1067
+ id: moduleId,
1068
+ importers: importers.get(moduleId) ?? []
1069
+ });
1070
+ if (this.getModuleInfo(moduleId)?.isEntry) entries.push(moduleId);
1071
+ }
1072
+ }
1073
+ const checked = import_static.default.checkZeroGraph({
1074
+ entries,
1075
+ modules,
1076
+ importerEdges: importers,
1077
+ root: zero.resolved.root
1078
+ });
1079
+ zeroReceipt = {
1080
+ integration: "vite",
1081
+ graph: "zero",
1082
+ entries: entries.sort(),
1083
+ moduleCount: modules.length,
1084
+ tamaguiModules: checked.tamaguiModules,
1085
+ forbidden: checked.forbidden,
1086
+ cssArtifact: null,
1087
+ identity: "",
1088
+ gzip: Object.fromEntries(Object.values(bundle).filter((chunk) => chunk.type === "chunk").map((chunk) => [chunk.fileName, (0, import_node_zlib.gzipSync)(Buffer.from(chunk.code), { level: 9 }).length]))
1089
+ };
1090
+ },
1091
+ async closeBundle() {
1092
+ if (!zero || this.environment.name !== "client") return;
1093
+ const outDir = import_node_path.default.resolve(config.root, this.environment.config.build.outDir);
1094
+ const receiptName = `vite-${import_node_path.default.basename(outDir)}`;
1095
+ import_static.default.writeZeroViolationReport(zero.resolved.outDir, receiptName, {
1096
+ integration: "vite",
1097
+ mode: zero.isEnforcing ? "enforce" : "report",
1098
+ violations: zero.violations
1099
+ });
1100
+ if (!zero.isEnforcing || zeroBuildFailed) return;
1101
+ if (zero.violations.length) throw new Error(import_static.default.formatZeroViolations(zero.violations));
1102
+ const islandOutputHashes = {};
1103
+ for (const island of zero.resolved.islands) {
1104
+ const built = await (0, import_zeroRuntime.buildIsland)({
1105
+ island,
1106
+ controller: zero,
1107
+ root: config.root,
1108
+ outDir,
1109
+ mode: config.mode
1110
+ });
1111
+ islandOutputHashes[island.id] = built.hash;
1112
+ }
1113
+ if (zeroHtmlEntries === 0) throw new Error(`[tamagui zero-runtime] the zero entry graph has no HTML entry, so the one generated CSS artifact ${zero.cssHref} is never loaded. Build a zero entry through its HTML document.`);
1114
+ const css = (0, import_zeroRuntime.finalizeZeroCSS)(zero, outDir);
1115
+ const bridgeManifest = import_static.default.canonicalizeBridgeManifest(Object.fromEntries([...zero.bridges.entries()].sort(([left], [right]) => left < right ? -1 : 1)));
1116
+ const identityInputs = {
1117
+ runtimeLiteral: "zero",
1118
+ target: "web",
1119
+ configGeneration: `${pluginInstanceId}:${tamaguiLoader.getGeneration()}`,
1120
+ cssHash: css.hash,
1121
+ compilerVersion: import_static.default.ZERO_COMPILER_VERSION,
1122
+ islandEntries: zero.resolved.islands.map((island) => island.module),
1123
+ bridgeManifestHash: import_static.default.hashBridgeManifest(bridgeManifest),
1124
+ islandOutputHashes
1125
+ };
1126
+ const identity = import_static.default.hashZeroIdentity(identityInputs);
1127
+ if (!zeroReceipt) throw new Error(`[tamagui zero-runtime] no module graph was recorded for the zero entry`);
1128
+ zeroReceipt.cssArtifact = {
1129
+ path: css.href,
1130
+ hash: css.hash
1131
+ };
1132
+ zeroReceipt.identity = identity;
1133
+ import_static.default.writeZeroGraphReceipt(zero.resolved.outDir, receiptName, zeroReceipt);
1134
+ (0, import_node_fs.writeFileSync)(import_node_path.default.join(zero.resolved.outDir, `${receiptName}.bridges.json`), `${JSON.stringify({
1135
+ identity,
1136
+ identityInputs,
1137
+ cssGzip: css.gzip,
1138
+ bridges: bridgeManifest
1139
+ }, null, 2)}
371
1140
  `);
372
- }
373
- if (shouldDisable) {
374
- return;
375
- }
376
- const isSSR = isNotClient(this.environment);
377
- const cacheKey = getHash(`${code}${id}`);
378
- const pending = getPendingExtractions();
379
- const formatResult = entry => {
380
- const finalCode = !isSSR && entry.cssImport ? `${entry.js}
381
- ${entry.cssImport}` : entry.js;
382
- return {
383
- code: finalCode,
384
- map: entry.map
385
- };
386
- };
387
- const cached = memoryCache[cacheKey];
388
- if (cached) {
389
- if (process.env.DEBUG_TAMAGUI_CACHE) {
390
- console.info(`[tamagui-cache] HIT ${this.environment?.name || "unknown"} ${id.split("/").pop()} key=${cacheKey.slice(0, 8)}`);
391
- }
392
- return formatResult(cached);
393
- }
394
- const pendingExtraction = pending.get(cacheKey);
395
- if (pendingExtraction) {
396
- if (process.env.DEBUG_TAMAGUI_CACHE) {
397
- console.info(`[tamagui-cache] WAIT ${this.environment?.name || "unknown"} ${id.split("/").pop()} key=${cacheKey.slice(0, 8)}`);
398
- }
399
- const result = await pendingExtraction;
400
- if (result) {
401
- return formatResult(result);
402
- }
403
- return;
404
- }
405
- if (process.env.DEBUG_TAMAGUI_CACHE) {
406
- console.info(`[tamagui-cache] EXTRACT ${this.environment?.name || "unknown"} ${id.split("/").pop()} key=${cacheKey.slice(0, 8)}`);
407
- }
408
- const extractionPromise = (async () => {
409
- let extracted;
410
- try {
411
- extracted = await Static.extractToClassNames({
412
- source: code,
413
- sourcePath: validId,
414
- options,
415
- shouldPrintDebug
416
- });
417
- } catch (err) {
418
- if (process.env.DEBUG_TAMAGUI_CACHE) {
419
- console.info(`[tamagui-cache] ERROR extracting ${id.split("/").pop()}:`, err);
420
- }
421
- console.error(err instanceof Error ? err.message : String(err));
422
- return null;
423
- }
424
- if (!extracted) {
425
- if (process.env.DEBUG_TAMAGUI_CACHE) {
426
- console.info(`[tamagui-cache] no extraction result for ${id.split("/").pop()}`);
427
- }
428
- return null;
429
- }
430
- const rootRelativeId = `${validId}${virtualExt}`;
431
- const absoluteId = getAbsoluteVirtualFileId(rootRelativeId);
432
- let cssImport = null;
433
- if (extracted.styles) {
434
- this.addWatchFile(rootRelativeId);
435
- if (server && cssMap.has(absoluteId)) {
436
- invalidateModule(rootRelativeId);
437
- }
438
- cssImport = `import "${rootRelativeId}";`;
439
- cssMap.set(absoluteId, extracted.styles);
440
- }
441
- const jsCode = extracted.js.toString();
442
- const cacheEntry = {
443
- js: jsCode,
444
- map: extracted.map,
445
- cssImport
446
- };
447
- const newSize = getSharedCacheSize() + jsCode.length;
448
- if (newSize > 67108864) {
449
- clearSharedCache();
450
- } else {
451
- setSharedCacheSize(newSize);
452
- }
453
- memoryCache[cacheKey] = cacheEntry;
454
- if (process.env.DEBUG_TAMAGUI_CACHE) {
455
- console.info(`[tamagui-cache] WRITE key=${cacheKey.slice(0, 8)} cacheSize=${Object.keys(memoryCache).length}`);
456
- }
457
- return cacheEntry;
458
- })();
459
- pending.set(cacheKey, extractionPromise);
460
- try {
461
- const result = await extractionPromise;
462
- if (result) {
463
- return formatResult(result);
464
- }
465
- return;
466
- } finally {
467
- pending.delete(cacheKey);
468
- }
469
- }
470
- }
471
- };
472
- return [basePlugin, rnwLitePlugin, extractPlugin];
473
- }
1141
+ (0, import_zeroRuntime.assertZeroGraph)(zeroReceipt);
1142
+ }
1143
+ },
1144
+ {
1145
+ name: "tamagui-global-css",
1146
+ enforce: "post",
1147
+ apply: "build",
1148
+ async buildStart() {
1149
+ if (!globalCSS || this.environment.name !== "client") return;
1150
+ await tamaguiLoader.ensureFullConfigLoaded();
1151
+ const tamaguiConfig = await tamaguiLoader.getTamaguiConfig();
1152
+ if (!tamaguiConfig) throw new Error(`[tamagui] outputCSS is set but the Tamagui config did not evaluate, so no CSS artifact can be generated`);
1153
+ globalCSSExpected = tamaguiConfig.getCSS();
1154
+ },
1155
+ generateBundle() {
1156
+ if (!globalCSS || this.environment.name !== "client") return;
1157
+ const failure = import_static.default.checkGlobalCSSArtifact({
1158
+ cssPath: globalCSS.cssPath,
1159
+ expectedCSS: globalCSSExpected ?? "",
1160
+ loadedModuleIds: this.getModuleIds(),
1161
+ importHint: `Import it once from your client entry: import ${JSON.stringify(relativeImportSpecifier(config.root, globalCSS.cssPath))}`
1162
+ });
1163
+ if (failure) throw new Error(failure.message);
1164
+ }
1165
+ },
1166
+ tamaguiNativePlugin(tamaguiOptionsIn)
1167
+ ],
1168
+ loader: tamaguiLoader
1169
+ };
1170
+ }
1171
+ function zeroDevIslandDir(zero) {
1172
+ return import_node_path.default.join(zero.resolved.outDir, "dev");
1173
+ }
1174
+ function relativeImportSpecifier(from, to) {
1175
+ const relative = normalizePath(import_node_path.default.relative(from, to));
1176
+ return relative.startsWith(".") ? relative : `./${relative}`;
1177
+ }
1178
+ function tamaguiPlugin(options = {}) {
1179
+ return createTamaguiPlugins(options).plugins;
1180
+ }