@tamagui/vite-plugin-cjs 2.7.7 → 3.0.0-beta.643.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,473 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all) __defProp(target, name, {
9
- get: all[name],
10
- enumerable: true
11
- });
12
- };
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;
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
30
- }) : target, mod));
31
- var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
32
- value: true
33
- }), mod);
34
- var plugin_exports = {};
35
- __export(plugin_exports, {
36
- tamaguiAliases: () => tamaguiAliases,
37
- tamaguiPlugin: () => tamaguiPlugin
38
- });
39
- module.exports = __toCommonJS(plugin_exports);
40
- var Static = __toESM(require("@tamagui/static-worker"), 1);
41
- var import_static_worker = require("@tamagui/static-worker");
42
- var import_node_crypto = require("node:crypto");
43
- var import_node_fs = require("node:fs");
44
- var import_node_module = require("node:module");
45
- var import_node_path = __toESM(require("node:path"), 1);
46
- var import_node_url = require("node:url");
47
- var import_loadTamagui = require("./loadTamagui.cjs");
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];
61
- }
62
- function getSharedCacheSize() {
63
- return globalThis[CACHE_SIZE_KEY] || 0;
64
- }
65
- function setSharedCacheSize(size) {
66
- ;
67
- globalThis[CACHE_SIZE_KEY] = size;
68
- }
69
- function clearSharedCache() {
70
- ;
71
- globalThis[CACHE_KEY] = {};
72
- globalThis[CACHE_SIZE_KEY] = 0;
73
- }
74
- 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
- }
82
- }
83
- 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];
99
- }
100
- 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;
141
- }
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
-
371
- `);
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
- }