@csszyx/unplugin 0.9.0 → 0.9.2

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.
Files changed (43) hide show
  1. package/dist/index.cjs +19 -2
  2. package/dist/index.d.cts +91 -5
  3. package/dist/index.d.mts +90 -3
  4. package/dist/index.mjs +4 -2
  5. package/dist/next-prebuild.cjs +148 -0
  6. package/dist/next-prebuild.d.cts +66 -0
  7. package/dist/next-prebuild.d.mts +66 -0
  8. package/dist/next-prebuild.mjs +131 -0
  9. package/dist/next-turbo-loader.cjs +210 -0
  10. package/dist/next-turbo-loader.d.cts +68 -0
  11. package/dist/next-turbo-loader.d.mts +66 -0
  12. package/dist/next-turbo-loader.mjs +190 -0
  13. package/dist/next-watcher.cjs +237 -0
  14. package/dist/next-watcher.d.cts +106 -0
  15. package/dist/next-watcher.d.mts +106 -0
  16. package/dist/next-watcher.mjs +219 -0
  17. package/dist/shared/unplugin.8er8o6rn.mjs +276 -0
  18. package/dist/shared/unplugin.B_U4rZvG.cjs +281 -0
  19. package/dist/shared/{unplugin.BEOG6ePC.mjs → unplugin.BbtspS8t.mjs} +1436 -324
  20. package/dist/shared/unplugin.BceVw1eW.mjs +184 -0
  21. package/dist/shared/unplugin.BtQzlC2C.mjs +567 -0
  22. package/dist/shared/{unplugin.CL0F6RZa.cjs → unplugin.CFp386gH.cjs} +1456 -327
  23. package/dist/shared/unplugin.CPEWNSA0.d.cts +77 -0
  24. package/dist/shared/unplugin.CPEWNSA0.d.mts +77 -0
  25. package/dist/shared/unplugin.CScQRdTp.d.cts +15 -0
  26. package/dist/shared/unplugin.CScQRdTp.d.mts +15 -0
  27. package/dist/shared/unplugin.CdZxp0x-.d.mts +16 -0
  28. package/dist/shared/unplugin.DLrBgECN.d.cts +282 -0
  29. package/dist/shared/unplugin.DLrBgECN.d.mts +282 -0
  30. package/dist/shared/unplugin.DUxdYaSG.cjs +205 -0
  31. package/dist/shared/unplugin.s62yJbu1.cjs +591 -0
  32. package/dist/shared/unplugin.xeED_qwh.d.cts +16 -0
  33. package/dist/vite.cjs +3 -1
  34. package/dist/vite.d.cts +2 -1
  35. package/dist/vite.d.mts +2 -1
  36. package/dist/vite.mjs +3 -1
  37. package/dist/webpack.cjs +3 -1
  38. package/dist/webpack.d.cts +2 -1
  39. package/dist/webpack.d.mts +2 -1
  40. package/dist/webpack.mjs +3 -1
  41. package/package.json +41 -8
  42. package/dist/shared/unplugin.DUbr5w-N.d.cts +0 -49
  43. package/dist/shared/unplugin.DUbr5w-N.d.mts +0 -49
@@ -0,0 +1,131 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { r as readPackageVersion, t as transformNextSource, c as collectNextTransformMetadata, a as createNextSafelistShardFromMetadata } from './shared/unplugin.8er8o6rn.mjs';
5
+ import { c as createNextStateContext, w as writeNextSafelistShard, r as runNextWatcherCycle } from './shared/unplugin.BtQzlC2C.mjs';
6
+ import { r as resolveTransformCacheDir } from './shared/unplugin.BceVw1eW.mjs';
7
+ import '@csszyx/compiler';
8
+ import 'node:os';
9
+ import 'proper-lockfile';
10
+
11
+ function runNextPrebuild(options) {
12
+ assertProductionManglingBoundary(options);
13
+ const csszyxVersion = options.csszyxVersion ?? readPackageVersion("../package.json", import.meta.url);
14
+ const compilerVersion = options.compilerVersion ?? readPackageVersion("../../compiler/package.json", import.meta.url);
15
+ const nativeVersion = options.nativeVersion ?? compilerVersion;
16
+ const nextVersion = options.nextVersion ?? "unknown-next";
17
+ const context = createNextStateContext({
18
+ explicitRoot: options.explicitRoot,
19
+ loaderRootContext: options.loaderRootContext,
20
+ loaderContext: options.loaderContext,
21
+ cwd: options.cwd,
22
+ cacheDir: options.cacheDir,
23
+ safelistOutputFile: options.safelistOutputFile,
24
+ config: options.config ?? {},
25
+ env: options.env ?? process.env,
26
+ envKeys: options.envKeys,
27
+ nextVersion,
28
+ csszyxVersion,
29
+ nativeVersion,
30
+ mode: options.mode ?? "production"
31
+ });
32
+ const cacheRoot = resolveTransformCacheDir(
33
+ context.root,
34
+ path.relative(context.root, context.cacheDir)
35
+ );
36
+ const files = [];
37
+ let scannedCount = 0;
38
+ let transformedCount = 0;
39
+ let skippedMissingCount = 0;
40
+ for (const filename of uniqueFiles(options.files)) {
41
+ scannedCount++;
42
+ if (!existsSync(filename)) {
43
+ skippedMissingCount++;
44
+ continue;
45
+ }
46
+ const source = readFileSync(filename, "utf8");
47
+ const transform = transformNextSource({
48
+ source,
49
+ filename,
50
+ parserMode: options.parserMode ?? "rust",
51
+ compilerOptions: options.compilerOptions,
52
+ cacheRoot,
53
+ pluginVersion: csszyxVersion,
54
+ compilerVersion,
55
+ astBudget: options.astBudget,
56
+ allowBabelFallback: options.allowBabelFallback
57
+ });
58
+ const metadata = collectNextTransformMetadata(transform.result, source, filename);
59
+ transformedCount++;
60
+ const shardResult = writeNextSafelistShard(
61
+ context.safelist.shardsDir,
62
+ createNextSafelistShardFromMetadata(metadata, createShardCacheKey(context, metadata)),
63
+ options.writeOptions
64
+ );
65
+ files.push({
66
+ filename,
67
+ shardPath: shardResult.filePath,
68
+ classCount: metadata.classes.length,
69
+ cacheStatus: transform.cacheStatus,
70
+ producer: transform.producer
71
+ });
72
+ }
73
+ const cycle = runNextWatcherCycle(context, {
74
+ writeOptions: options.writeOptions,
75
+ lockOptions: {
76
+ root: context.root,
77
+ mode: context.manifestExpectation.mode,
78
+ command: "csszyx next prebuild"
79
+ },
80
+ createdAt: options.createdAt
81
+ });
82
+ return {
83
+ context,
84
+ scannedCount,
85
+ transformedCount,
86
+ skippedMissingCount,
87
+ classCount: cycle.materialize.classCount,
88
+ sourceCount: cycle.materialize.sourceCount,
89
+ manifestPath: context.manifestPath,
90
+ safelistOutputPath: context.safelist.outputPath,
91
+ files,
92
+ cycle
93
+ };
94
+ }
95
+ function assertProductionManglingBoundary(options) {
96
+ if (options.allowProductionMangling) {
97
+ return;
98
+ }
99
+ if ((options.mode ?? "production") !== "production") {
100
+ return;
101
+ }
102
+ if (options.compilerOptions?.mangleVars === true || hasEnabledMangleVars(options.config)) {
103
+ throw new Error(
104
+ "[csszyx] Next prebuild does not support production CSS variable mangling. Use Next Webpack mode for full csszyx parity."
105
+ );
106
+ }
107
+ }
108
+ function hasEnabledMangleVars(config) {
109
+ if (config === null || typeof config !== "object" || Array.isArray(config)) {
110
+ return false;
111
+ }
112
+ return config.mangleVars === true;
113
+ }
114
+ function uniqueFiles(files) {
115
+ const seen = /* @__PURE__ */ new Set();
116
+ const result = [];
117
+ for (const file of files) {
118
+ const resolved = path.resolve(file);
119
+ if (seen.has(resolved)) {
120
+ continue;
121
+ }
122
+ seen.add(resolved);
123
+ result.push(resolved);
124
+ }
125
+ return result;
126
+ }
127
+ function createShardCacheKey(context, metadata) {
128
+ return createHash("sha256").update(context.identity.generation).update("\0").update(path.relative(context.root, metadata.sourcePath).replace(/\\/g, "/")).digest("hex");
129
+ }
130
+
131
+ export { runNextPrebuild };
@@ -0,0 +1,210 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const node_crypto = require('node:crypto');
6
+ const path = require('node:path');
7
+ const nextWatcherCycle = require('./shared/unplugin.s62yJbu1.cjs');
8
+ const nextTransformMetadata = require('./shared/unplugin.B_U4rZvG.cjs');
9
+ const transformCache = require('./shared/unplugin.DUxdYaSG.cjs');
10
+ require('node:fs');
11
+ require('node:os');
12
+ require('proper-lockfile');
13
+ require('@csszyx/compiler');
14
+
15
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
16
+ function _interopNamespaceCompat(e) {
17
+ if (e && typeof e === 'object' && 'default' in e) return e;
18
+ const n = Object.create(null);
19
+ if (e) {
20
+ for (const k in e) {
21
+ n[k] = e[k];
22
+ }
23
+ }
24
+ n.default = e;
25
+ return n;
26
+ }
27
+
28
+ const path__namespace = /*#__PURE__*/_interopNamespaceCompat(path);
29
+
30
+ const DIRECTIVE_PROLOGUE_PREFIX_RE = /^((?:\s|\/\/[^\n]*\n|\/\*(?:[^*]|\*(?!\/))*\*\/)*)(['"]use (?:client|server)['"];?\s*)/;
31
+ const RUNTIME_HELPER_IMPORT_RE = {
32
+ _sz: /\{[^}]*\b_sz\b[^}]*\}\s*from\s*['"]@csszyx\/runtime['"]/,
33
+ _szMerge: /\{[^}]*\b_szMerge\b[^}]*\}\s*from\s*['"]@csszyx\/runtime['"]/,
34
+ __szColorVar: /\{[^}]*\b__szColorVar\b[^}]*\}\s*from\s*['"]@csszyx\/runtime['"]/
35
+ };
36
+ function injectNextRuntimeImports(code, usage) {
37
+ const helpers = runtimeHelpersFromUsage(usage);
38
+ if (helpers.length === 0) {
39
+ return { code, injected: [] };
40
+ }
41
+ const hasRuntimeImport = code.includes("@csszyx/runtime");
42
+ const missing = hasRuntimeImport ? helpers.filter((helper) => !RUNTIME_HELPER_IMPORT_RE[helper].test(code)) : helpers;
43
+ if (missing.length === 0) {
44
+ return { code, injected: [] };
45
+ }
46
+ return {
47
+ code: insertRuntimeImport(
48
+ code,
49
+ `import { ${missing.join(", ")} } from '@csszyx/runtime';
50
+ `
51
+ ),
52
+ injected: missing
53
+ };
54
+ }
55
+ function runtimeHelpersFromUsage(usage) {
56
+ const helpers = [];
57
+ if (usage.usesRuntime) {
58
+ helpers.push("_sz");
59
+ }
60
+ if (usage.usesMerge) {
61
+ helpers.push("_szMerge");
62
+ }
63
+ if (usage.usesColorVar) {
64
+ helpers.push("__szColorVar");
65
+ }
66
+ return helpers;
67
+ }
68
+ function insertRuntimeImport(code, importStmt) {
69
+ const directiveMatch = code.match(DIRECTIVE_PROLOGUE_PREFIX_RE);
70
+ if (!directiveMatch) {
71
+ return `${importStmt}${code}`;
72
+ }
73
+ return code.replace(directiveMatch[0], `${directiveMatch[1]}${directiveMatch[2]}${importStmt}`);
74
+ }
75
+
76
+ function runNextTurboLoader(source, loaderContext, explicitOptions = {}) {
77
+ const options = normalizeOptions(loaderContext, explicitOptions);
78
+ assertTurbopackMangleBoundary(options, loaderContext.resourcePath);
79
+ const context = nextWatcherCycle.createNextStateContext({
80
+ explicitRoot: options.root,
81
+ loaderRootContext: loaderContext.rootContext,
82
+ loaderContext: loaderContext.context,
83
+ cacheDir: options.cacheDir,
84
+ safelistOutputFile: options.safelistOutputFile,
85
+ config: options.config ?? {},
86
+ env: options.env ?? process.env,
87
+ envKeys: options.envKeys,
88
+ nextVersion: options.nextVersion ?? "unknown-next",
89
+ csszyxVersion: options.csszyxVersion ?? nextTransformMetadata.readPackageVersion("../package.json", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next-turbo-loader.cjs', document.baseURI).href))),
90
+ nativeVersion: options.nativeVersion ?? options.compilerVersion ?? nextTransformMetadata.readPackageVersion("../../compiler/package.json", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next-turbo-loader.cjs', document.baseURI).href))),
91
+ mode: options.mode ?? normalizeMode(loaderContext.mode)
92
+ });
93
+ assertProductionManifestReady(context, options);
94
+ const transform = nextTransformMetadata.transformNextSource({
95
+ source,
96
+ filename: loaderContext.resourcePath,
97
+ parserMode: options.parserMode ?? "rust",
98
+ compilerOptions: options.compilerOptions,
99
+ cacheRoot: transformCache.resolveTransformCacheDir(
100
+ context.root,
101
+ path__namespace.relative(context.root, context.cacheDir)
102
+ ),
103
+ pluginVersion: options.csszyxVersion ?? nextTransformMetadata.readPackageVersion("../package.json", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next-turbo-loader.cjs', document.baseURI).href))),
104
+ compilerVersion: options.compilerVersion ?? nextTransformMetadata.readPackageVersion("../../compiler/package.json", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next-turbo-loader.cjs', document.baseURI).href))),
105
+ astBudget: options.astBudget,
106
+ allowBabelFallback: options.allowBabelFallback
107
+ });
108
+ const injected = injectNextRuntimeImports(transform.result.code, transform.result);
109
+ const metadata = nextTransformMetadata.collectNextTransformMetadata(
110
+ transform.result,
111
+ source,
112
+ loaderContext.resourcePath
113
+ );
114
+ let shardPath = null;
115
+ let materialized = false;
116
+ const shardResult = nextWatcherCycle.writeNextSafelistShard(
117
+ context.safelist.shardsDir,
118
+ nextTransformMetadata.createNextSafelistShardFromMetadata(metadata, createShardCacheKey(context, metadata)),
119
+ options.writeOptions
120
+ );
121
+ shardPath = shardResult.filePath;
122
+ if (options.materializeSafelist !== false && shardResult.changed) {
123
+ nextWatcherCycle.runNextWatcherCycle(context, {
124
+ writeOptions: options.writeOptions,
125
+ lockOptions: {
126
+ root: context.root,
127
+ mode: context.manifestExpectation.mode,
128
+ command: "csszyx next turbo-loader"
129
+ }
130
+ });
131
+ materialized = true;
132
+ }
133
+ return {
134
+ code: injected.code,
135
+ context,
136
+ transform,
137
+ shardPath,
138
+ materialized,
139
+ dependencies: []
140
+ };
141
+ }
142
+ function nextTurboLoader(source) {
143
+ try {
144
+ const result = runNextTurboLoader(source, this);
145
+ if (this.callback) {
146
+ this.callback(null, result.code, result.map);
147
+ return;
148
+ }
149
+ return result.code;
150
+ } catch (error) {
151
+ if (this.callback) {
152
+ this.callback(error instanceof Error ? error : new Error(String(error)));
153
+ return;
154
+ }
155
+ throw error;
156
+ }
157
+ }
158
+ function normalizeOptions(loaderContext, explicitOptions) {
159
+ const contextOptions = loaderContext.getOptions?.() ?? parseQueryOptions(loaderContext.query);
160
+ return { ...contextOptions, ...explicitOptions };
161
+ }
162
+ function parseQueryOptions(query) {
163
+ if (!query || typeof query !== "object" || Array.isArray(query)) {
164
+ return {};
165
+ }
166
+ return query;
167
+ }
168
+ function normalizeMode(mode) {
169
+ return mode === "production" || process.env.NODE_ENV === "production" ? "production" : "development";
170
+ }
171
+ function assertProductionManifestReady(context, options) {
172
+ if ((options.mode ?? context.manifestExpectation.mode) !== "production") {
173
+ return;
174
+ }
175
+ const validation = nextWatcherCycle.validateNextGenerationManifest(
176
+ nextWatcherCycle.readNextGenerationManifest(context.manifestPath),
177
+ context.manifestExpectation
178
+ );
179
+ if (!validation.ok) {
180
+ throw new Error(
181
+ `[csszyx] Next Turbopack production cache is not ready for ${context.root}: ${validation.reason}. Run csszyx next prebuild before next build --turbo.`
182
+ );
183
+ }
184
+ }
185
+ function assertTurbopackMangleBoundary(options, resourcePath) {
186
+ if (options.allowProductionMangling) {
187
+ return;
188
+ }
189
+ const productionMode = options.mode === "production" || process.env.NODE_ENV === "production";
190
+ if (!productionMode) {
191
+ return;
192
+ }
193
+ if (options.compilerOptions?.mangleVars === true || hasEnabledMangleVars(options.config)) {
194
+ throw new Error(
195
+ `[csszyx] Next Turbopack does not support production CSS variable mangling for ${resourcePath}. Use Next Webpack mode for full csszyx parity.`
196
+ );
197
+ }
198
+ }
199
+ function hasEnabledMangleVars(config) {
200
+ if (config === null || typeof config !== "object" || Array.isArray(config)) {
201
+ return false;
202
+ }
203
+ return config.mangleVars === true;
204
+ }
205
+ function createShardCacheKey(context, metadata) {
206
+ return node_crypto.createHash("sha256").update(context.identity.generation).update("\0").update(path__namespace.relative(context.root, metadata.sourcePath).replace(/\\/g, "/")).digest("hex");
207
+ }
208
+
209
+ exports.default = nextTurboLoader;
210
+ exports.runNextTurboLoader = runNextTurboLoader;
@@ -0,0 +1,68 @@
1
+ import { TransformSourceCodeOptions } from '@csszyx/compiler';
2
+ import { J as JsonLike, A as AtomicWriteOptions, N as NextStateContext } from './shared/unplugin.CPEWNSA0.cjs';
3
+ import { N as NextSourceParserMode, a as NextSourceTransformOutput } from './shared/unplugin.CScQRdTp.cjs';
4
+
5
+ /** Serializable options accepted by the Next Turbopack csszyx loader. */
6
+ interface NextTurboLoaderOptions {
7
+ root?: string;
8
+ cacheDir?: string;
9
+ safelistOutputFile?: string;
10
+ parserMode?: NextSourceParserMode;
11
+ compilerOptions?: TransformSourceCodeOptions;
12
+ config?: JsonLike;
13
+ env?: Record<string, string | undefined>;
14
+ envKeys?: readonly string[];
15
+ nextVersion?: string;
16
+ csszyxVersion?: string;
17
+ compilerVersion?: string;
18
+ nativeVersion?: string;
19
+ mode?: 'development' | 'production';
20
+ astBudget?: number;
21
+ allowBabelFallback?: boolean;
22
+ allowProductionMangling?: boolean;
23
+ materializeSafelist?: boolean;
24
+ writeOptions?: AtomicWriteOptions;
25
+ }
26
+ /** Minimal Webpack-compatible loader context used by Turbopack. */
27
+ interface NextTurboLoaderContext {
28
+ resourcePath: string;
29
+ rootContext?: string;
30
+ context?: string;
31
+ mode?: string;
32
+ query?: unknown;
33
+ getOptions?: () => NextTurboLoaderOptions;
34
+ addDependency?: (file: string) => void;
35
+ callback?: (error: Error | null, code?: string, map?: unknown) => void;
36
+ }
37
+ /** Testable result produced by the loader core before callback adaptation. */
38
+ interface NextTurboLoaderResult {
39
+ code: string;
40
+ map?: unknown;
41
+ context: NextStateContext;
42
+ transform: NextSourceTransformOutput;
43
+ shardPath: string | null;
44
+ materialized: boolean;
45
+ dependencies: string[];
46
+ }
47
+ /**
48
+ * Run the csszyx Next Turbopack loader as a pure, synchronous operation.
49
+ *
50
+ * @param source Source module contents.
51
+ * @param loaderContext Webpack-compatible loader context from Turbopack.
52
+ * @param explicitOptions Serializable loader options.
53
+ * @returns Transformed code plus state metadata for tests and diagnostics.
54
+ */
55
+ declare function runNextTurboLoader(source: string, loaderContext: NextTurboLoaderContext, explicitOptions?: NextTurboLoaderOptions): NextTurboLoaderResult;
56
+ /**
57
+ * Webpack-compatible loader entry consumed by Next `turbopack.rules`.
58
+ *
59
+ * @param this Loader context.
60
+ * @param source Source module contents.
61
+ * @returns Transformed source when callback mode is unavailable.
62
+ */
63
+ declare function nextTurboLoader(this: NextTurboLoaderContext, source: string): string | undefined;
64
+
65
+ // @ts-ignore
66
+ export = nextTurboLoader;
67
+ export { runNextTurboLoader };
68
+ export type { NextTurboLoaderContext, NextTurboLoaderOptions, NextTurboLoaderResult };
@@ -0,0 +1,66 @@
1
+ import { TransformSourceCodeOptions } from '@csszyx/compiler';
2
+ import { J as JsonLike, A as AtomicWriteOptions, N as NextStateContext } from './shared/unplugin.CPEWNSA0.mjs';
3
+ import { N as NextSourceParserMode, a as NextSourceTransformOutput } from './shared/unplugin.CScQRdTp.mjs';
4
+
5
+ /** Serializable options accepted by the Next Turbopack csszyx loader. */
6
+ interface NextTurboLoaderOptions {
7
+ root?: string;
8
+ cacheDir?: string;
9
+ safelistOutputFile?: string;
10
+ parserMode?: NextSourceParserMode;
11
+ compilerOptions?: TransformSourceCodeOptions;
12
+ config?: JsonLike;
13
+ env?: Record<string, string | undefined>;
14
+ envKeys?: readonly string[];
15
+ nextVersion?: string;
16
+ csszyxVersion?: string;
17
+ compilerVersion?: string;
18
+ nativeVersion?: string;
19
+ mode?: 'development' | 'production';
20
+ astBudget?: number;
21
+ allowBabelFallback?: boolean;
22
+ allowProductionMangling?: boolean;
23
+ materializeSafelist?: boolean;
24
+ writeOptions?: AtomicWriteOptions;
25
+ }
26
+ /** Minimal Webpack-compatible loader context used by Turbopack. */
27
+ interface NextTurboLoaderContext {
28
+ resourcePath: string;
29
+ rootContext?: string;
30
+ context?: string;
31
+ mode?: string;
32
+ query?: unknown;
33
+ getOptions?: () => NextTurboLoaderOptions;
34
+ addDependency?: (file: string) => void;
35
+ callback?: (error: Error | null, code?: string, map?: unknown) => void;
36
+ }
37
+ /** Testable result produced by the loader core before callback adaptation. */
38
+ interface NextTurboLoaderResult {
39
+ code: string;
40
+ map?: unknown;
41
+ context: NextStateContext;
42
+ transform: NextSourceTransformOutput;
43
+ shardPath: string | null;
44
+ materialized: boolean;
45
+ dependencies: string[];
46
+ }
47
+ /**
48
+ * Run the csszyx Next Turbopack loader as a pure, synchronous operation.
49
+ *
50
+ * @param source Source module contents.
51
+ * @param loaderContext Webpack-compatible loader context from Turbopack.
52
+ * @param explicitOptions Serializable loader options.
53
+ * @returns Transformed code plus state metadata for tests and diagnostics.
54
+ */
55
+ declare function runNextTurboLoader(source: string, loaderContext: NextTurboLoaderContext, explicitOptions?: NextTurboLoaderOptions): NextTurboLoaderResult;
56
+ /**
57
+ * Webpack-compatible loader entry consumed by Next `turbopack.rules`.
58
+ *
59
+ * @param this Loader context.
60
+ * @param source Source module contents.
61
+ * @returns Transformed source when callback mode is unavailable.
62
+ */
63
+ declare function nextTurboLoader(this: NextTurboLoaderContext, source: string): string | undefined;
64
+
65
+ export { nextTurboLoader as default, runNextTurboLoader };
66
+ export type { NextTurboLoaderContext, NextTurboLoaderOptions, NextTurboLoaderResult };
@@ -0,0 +1,190 @@
1
+ import { createHash } from 'node:crypto';
2
+ import * as path from 'node:path';
3
+ import { c as createNextStateContext, w as writeNextSafelistShard, r as runNextWatcherCycle, v as validateNextGenerationManifest, a as readNextGenerationManifest } from './shared/unplugin.BtQzlC2C.mjs';
4
+ import { r as readPackageVersion, t as transformNextSource, c as collectNextTransformMetadata, a as createNextSafelistShardFromMetadata } from './shared/unplugin.8er8o6rn.mjs';
5
+ import { r as resolveTransformCacheDir } from './shared/unplugin.BceVw1eW.mjs';
6
+ import 'node:fs';
7
+ import 'node:os';
8
+ import 'proper-lockfile';
9
+ import '@csszyx/compiler';
10
+
11
+ const DIRECTIVE_PROLOGUE_PREFIX_RE = /^((?:\s|\/\/[^\n]*\n|\/\*(?:[^*]|\*(?!\/))*\*\/)*)(['"]use (?:client|server)['"];?\s*)/;
12
+ const RUNTIME_HELPER_IMPORT_RE = {
13
+ _sz: /\{[^}]*\b_sz\b[^}]*\}\s*from\s*['"]@csszyx\/runtime['"]/,
14
+ _szMerge: /\{[^}]*\b_szMerge\b[^}]*\}\s*from\s*['"]@csszyx\/runtime['"]/,
15
+ __szColorVar: /\{[^}]*\b__szColorVar\b[^}]*\}\s*from\s*['"]@csszyx\/runtime['"]/
16
+ };
17
+ function injectNextRuntimeImports(code, usage) {
18
+ const helpers = runtimeHelpersFromUsage(usage);
19
+ if (helpers.length === 0) {
20
+ return { code, injected: [] };
21
+ }
22
+ const hasRuntimeImport = code.includes("@csszyx/runtime");
23
+ const missing = hasRuntimeImport ? helpers.filter((helper) => !RUNTIME_HELPER_IMPORT_RE[helper].test(code)) : helpers;
24
+ if (missing.length === 0) {
25
+ return { code, injected: [] };
26
+ }
27
+ return {
28
+ code: insertRuntimeImport(
29
+ code,
30
+ `import { ${missing.join(", ")} } from '@csszyx/runtime';
31
+ `
32
+ ),
33
+ injected: missing
34
+ };
35
+ }
36
+ function runtimeHelpersFromUsage(usage) {
37
+ const helpers = [];
38
+ if (usage.usesRuntime) {
39
+ helpers.push("_sz");
40
+ }
41
+ if (usage.usesMerge) {
42
+ helpers.push("_szMerge");
43
+ }
44
+ if (usage.usesColorVar) {
45
+ helpers.push("__szColorVar");
46
+ }
47
+ return helpers;
48
+ }
49
+ function insertRuntimeImport(code, importStmt) {
50
+ const directiveMatch = code.match(DIRECTIVE_PROLOGUE_PREFIX_RE);
51
+ if (!directiveMatch) {
52
+ return `${importStmt}${code}`;
53
+ }
54
+ return code.replace(directiveMatch[0], `${directiveMatch[1]}${directiveMatch[2]}${importStmt}`);
55
+ }
56
+
57
+ function runNextTurboLoader(source, loaderContext, explicitOptions = {}) {
58
+ const options = normalizeOptions(loaderContext, explicitOptions);
59
+ assertTurbopackMangleBoundary(options, loaderContext.resourcePath);
60
+ const context = createNextStateContext({
61
+ explicitRoot: options.root,
62
+ loaderRootContext: loaderContext.rootContext,
63
+ loaderContext: loaderContext.context,
64
+ cacheDir: options.cacheDir,
65
+ safelistOutputFile: options.safelistOutputFile,
66
+ config: options.config ?? {},
67
+ env: options.env ?? process.env,
68
+ envKeys: options.envKeys,
69
+ nextVersion: options.nextVersion ?? "unknown-next",
70
+ csszyxVersion: options.csszyxVersion ?? readPackageVersion("../package.json", import.meta.url),
71
+ nativeVersion: options.nativeVersion ?? options.compilerVersion ?? readPackageVersion("../../compiler/package.json", import.meta.url),
72
+ mode: options.mode ?? normalizeMode(loaderContext.mode)
73
+ });
74
+ assertProductionManifestReady(context, options);
75
+ const transform = transformNextSource({
76
+ source,
77
+ filename: loaderContext.resourcePath,
78
+ parserMode: options.parserMode ?? "rust",
79
+ compilerOptions: options.compilerOptions,
80
+ cacheRoot: resolveTransformCacheDir(
81
+ context.root,
82
+ path.relative(context.root, context.cacheDir)
83
+ ),
84
+ pluginVersion: options.csszyxVersion ?? readPackageVersion("../package.json", import.meta.url),
85
+ compilerVersion: options.compilerVersion ?? readPackageVersion("../../compiler/package.json", import.meta.url),
86
+ astBudget: options.astBudget,
87
+ allowBabelFallback: options.allowBabelFallback
88
+ });
89
+ const injected = injectNextRuntimeImports(transform.result.code, transform.result);
90
+ const metadata = collectNextTransformMetadata(
91
+ transform.result,
92
+ source,
93
+ loaderContext.resourcePath
94
+ );
95
+ let shardPath = null;
96
+ let materialized = false;
97
+ const shardResult = writeNextSafelistShard(
98
+ context.safelist.shardsDir,
99
+ createNextSafelistShardFromMetadata(metadata, createShardCacheKey(context, metadata)),
100
+ options.writeOptions
101
+ );
102
+ shardPath = shardResult.filePath;
103
+ if (options.materializeSafelist !== false && shardResult.changed) {
104
+ runNextWatcherCycle(context, {
105
+ writeOptions: options.writeOptions,
106
+ lockOptions: {
107
+ root: context.root,
108
+ mode: context.manifestExpectation.mode,
109
+ command: "csszyx next turbo-loader"
110
+ }
111
+ });
112
+ materialized = true;
113
+ }
114
+ return {
115
+ code: injected.code,
116
+ context,
117
+ transform,
118
+ shardPath,
119
+ materialized,
120
+ dependencies: []
121
+ };
122
+ }
123
+ function nextTurboLoader(source) {
124
+ try {
125
+ const result = runNextTurboLoader(source, this);
126
+ if (this.callback) {
127
+ this.callback(null, result.code, result.map);
128
+ return;
129
+ }
130
+ return result.code;
131
+ } catch (error) {
132
+ if (this.callback) {
133
+ this.callback(error instanceof Error ? error : new Error(String(error)));
134
+ return;
135
+ }
136
+ throw error;
137
+ }
138
+ }
139
+ function normalizeOptions(loaderContext, explicitOptions) {
140
+ const contextOptions = loaderContext.getOptions?.() ?? parseQueryOptions(loaderContext.query);
141
+ return { ...contextOptions, ...explicitOptions };
142
+ }
143
+ function parseQueryOptions(query) {
144
+ if (!query || typeof query !== "object" || Array.isArray(query)) {
145
+ return {};
146
+ }
147
+ return query;
148
+ }
149
+ function normalizeMode(mode) {
150
+ return mode === "production" || process.env.NODE_ENV === "production" ? "production" : "development";
151
+ }
152
+ function assertProductionManifestReady(context, options) {
153
+ if ((options.mode ?? context.manifestExpectation.mode) !== "production") {
154
+ return;
155
+ }
156
+ const validation = validateNextGenerationManifest(
157
+ readNextGenerationManifest(context.manifestPath),
158
+ context.manifestExpectation
159
+ );
160
+ if (!validation.ok) {
161
+ throw new Error(
162
+ `[csszyx] Next Turbopack production cache is not ready for ${context.root}: ${validation.reason}. Run csszyx next prebuild before next build --turbo.`
163
+ );
164
+ }
165
+ }
166
+ function assertTurbopackMangleBoundary(options, resourcePath) {
167
+ if (options.allowProductionMangling) {
168
+ return;
169
+ }
170
+ const productionMode = options.mode === "production" || process.env.NODE_ENV === "production";
171
+ if (!productionMode) {
172
+ return;
173
+ }
174
+ if (options.compilerOptions?.mangleVars === true || hasEnabledMangleVars(options.config)) {
175
+ throw new Error(
176
+ `[csszyx] Next Turbopack does not support production CSS variable mangling for ${resourcePath}. Use Next Webpack mode for full csszyx parity.`
177
+ );
178
+ }
179
+ }
180
+ function hasEnabledMangleVars(config) {
181
+ if (config === null || typeof config !== "object" || Array.isArray(config)) {
182
+ return false;
183
+ }
184
+ return config.mangleVars === true;
185
+ }
186
+ function createShardCacheKey(context, metadata) {
187
+ return createHash("sha256").update(context.identity.generation).update("\0").update(path.relative(context.root, metadata.sourcePath).replace(/\\/g, "/")).digest("hex");
188
+ }
189
+
190
+ export { nextTurboLoader as default, runNextTurboLoader };