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

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