@yak/react 0.0.0-stage → 10.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +102 -2
  3. package/dist/context/baseContext.cjs +9 -0
  4. package/dist/context/baseContext.cjs.map +1 -0
  5. package/dist/context/baseContext.d.cts +6 -0
  6. package/dist/context/baseContext.d.ts +6 -0
  7. package/dist/context/baseContext.js +8 -0
  8. package/dist/context/baseContext.js.map +1 -0
  9. package/dist/context/index.cjs +45 -0
  10. package/dist/context/index.cjs.map +1 -0
  11. package/dist/context/index.d.cts +21 -0
  12. package/dist/context/index.d.ts +21 -0
  13. package/dist/context/index.js +15 -0
  14. package/dist/context/index.js.map +1 -0
  15. package/dist/context/index.server.cjs +47 -0
  16. package/dist/context/index.server.cjs.map +1 -0
  17. package/dist/context/index.server.d.cts +10 -0
  18. package/dist/context/index.server.d.ts +10 -0
  19. package/dist/context/index.server.js +17 -0
  20. package/dist/context/index.server.js.map +1 -0
  21. package/dist/cross-file-resolver/index.d.ts +199 -0
  22. package/dist/cross-file-resolver/index.js +535 -0
  23. package/dist/cross-file-resolver/index.js.map +1 -0
  24. package/dist/index.cjs +2 -0
  25. package/dist/index.cjs.map +1 -0
  26. package/dist/index.d.cts +320 -0
  27. package/dist/index.d.ts +320 -0
  28. package/dist/index.js +2 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/internal.cjs +544 -0
  31. package/dist/internal.cjs.map +1 -0
  32. package/dist/internal.d.cts +452 -0
  33. package/dist/internal.d.ts +452 -0
  34. package/dist/internal.js +363 -0
  35. package/dist/internal.js.map +1 -0
  36. package/dist/isolated-source-eval/index.d.ts +30 -0
  37. package/dist/isolated-source-eval/index.js +317 -0
  38. package/dist/isolated-source-eval/index.js.map +1 -0
  39. package/dist/isolated-source-eval/worker.js +59 -0
  40. package/dist/isolated-source-eval/worker.js.map +1 -0
  41. package/dist/jsx-dev-runtime.cjs +2 -0
  42. package/dist/jsx-dev-runtime.cjs.map +1 -0
  43. package/dist/jsx-dev-runtime.d.cts +7 -0
  44. package/dist/jsx-dev-runtime.d.ts +7 -0
  45. package/dist/jsx-dev-runtime.js +2 -0
  46. package/dist/jsx-dev-runtime.js.map +1 -0
  47. package/dist/jsx-runtime.cjs +2 -0
  48. package/dist/jsx-runtime.cjs.map +1 -0
  49. package/dist/jsx-runtime.d.cts +38 -0
  50. package/dist/jsx-runtime.d.ts +38 -0
  51. package/dist/jsx-runtime.js +2 -0
  52. package/dist/jsx-runtime.js.map +1 -0
  53. package/dist/loaders/turbo-loader.cjs +803 -0
  54. package/dist/loaders/turbo-loader.cjs.map +1 -0
  55. package/dist/loaders/turbo-loader.d.cts +15 -0
  56. package/dist/loaders/vite-plugin.d.ts +111 -0
  57. package/dist/loaders/vite-plugin.js +878 -0
  58. package/dist/loaders/vite-plugin.js.map +1 -0
  59. package/dist/loaders/webpack-loader.cjs +697 -0
  60. package/dist/loaders/webpack-loader.cjs.map +1 -0
  61. package/dist/loaders/webpack-loader.d.cts +12 -0
  62. package/dist/rsbuild/index.d.ts +29 -0
  63. package/dist/rsbuild/index.js +52 -0
  64. package/dist/rsbuild/index.js.map +1 -0
  65. package/dist/static/chunk-DK3Fl9T5.js +1 -0
  66. package/dist/static/index.cjs +2 -0
  67. package/dist/static/index.cjs.map +1 -0
  68. package/dist/static/index.d.cts +28 -0
  69. package/dist/static/index.d.ts +28 -0
  70. package/dist/static/index.js +2 -0
  71. package/dist/static/index.js.map +1 -0
  72. package/dist/withYak/index.cjs +208 -0
  73. package/dist/withYak/index.cjs.map +1 -0
  74. package/dist/withYak/index.d.cts +121 -0
  75. package/dist/withYak/index.d.ts +121 -0
  76. package/dist/withYak/index.js +177 -0
  77. package/dist/withYak/index.js.map +1 -0
  78. package/loaders/lib/resolveCrossFileSelectors.ts +162 -0
  79. package/loaders/turbo-evaluator.ts +134 -0
  80. package/loaders/turbo-loader.ts +180 -0
  81. package/loaders/vite-plugin.ts +28 -0
  82. package/loaders/webpack-loader.ts +44 -0
  83. package/package.json +214 -3
  84. package/rsbuild/index.ts +92 -0
  85. package/runtime/__tests__/atoms.test.tsx +48 -0
  86. package/runtime/__tests__/attrs.test.tsx +490 -0
  87. package/runtime/__tests__/cssLiteral.test.tsx +503 -0
  88. package/runtime/__tests__/cssProp.test.tsx +392 -0
  89. package/runtime/__tests__/cssPropTest.tsx +227 -0
  90. package/runtime/__tests__/foldedJsxParity.test.tsx +117 -0
  91. package/runtime/__tests__/styled.test.tsx +653 -0
  92. package/runtime/__tests__/tsconfig.json +18 -0
  93. package/runtime/__tests__/typeTest.tsx +374 -0
  94. package/runtime/atoms.tsx +36 -0
  95. package/runtime/context/README.md +84 -0
  96. package/runtime/context/baseContext.tsx +5 -0
  97. package/runtime/context/index.server.tsx +22 -0
  98. package/runtime/context/index.tsx +36 -0
  99. package/runtime/cssLiteral.tsx +214 -0
  100. package/runtime/globalStyle.tsx +54 -0
  101. package/runtime/index.ts +37 -0
  102. package/runtime/internal.ts +42 -0
  103. package/runtime/internals/mergeClassNames.ts +23 -0
  104. package/runtime/internals/mergeCssProp.ts +69 -0
  105. package/runtime/internals/propMarkers.ts +20 -0
  106. package/runtime/internals/unitPostFix.ts +34 -0
  107. package/runtime/jsx-dev-runtime.ts +6 -0
  108. package/runtime/jsx-runtime.ts +48 -0
  109. package/runtime/keyframes.tsx +30 -0
  110. package/runtime/mocks/cssLiteral.ts +74 -0
  111. package/runtime/mocks/globalStyle.ts +14 -0
  112. package/runtime/mocks/keyframes.ts +29 -0
  113. package/runtime/mocks/styled.ts +8 -0
  114. package/runtime/publicStyledApi.ts +159 -0
  115. package/runtime/styled.tsx +372 -0
  116. package/runtime/styledDom.tsx +139 -0
  117. package/withYak/allow-global-css.ts +94 -0
  118. package/withYak/index.ts +282 -0
@@ -0,0 +1,803 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __esmMin = (fn, res, err) => () => {
4
+ if (err) throw err[0];
5
+ try {
6
+ return fn && (res = fn(fn = 0)), res;
7
+ } catch (e) {
8
+ throw err = [e], e;
9
+ }
10
+ };
11
+ var __exportAll = (all, no_symbols) => {
12
+ let target = {};
13
+ for (var name in all) {
14
+ __defProp(target, name, {
15
+ get: all[name],
16
+ enumerable: true
17
+ });
18
+ }
19
+ if (!no_symbols) {
20
+ __defProp(target, Symbol.toStringTag, { value: "Module" });
21
+ }
22
+ return target;
23
+ };
24
+
25
+ //#endregion
26
+ let _swc_core = require("@swc/core");
27
+ let node_module = require("node:module");
28
+ let node_path = require("node:path");
29
+ let path = require("path");
30
+ let _babel_parser = require("@babel/parser");
31
+ let node_fs = require("node:fs");
32
+
33
+ //#region ../yak-internals/cross-file-resolver/parseModule.ts
34
+ async function parseModule(context, modulePath) {
35
+ try {
36
+ if ((modulePath.endsWith(".yak.ts") || modulePath.endsWith(".yak.tsx") || modulePath.endsWith(".yak.js") || modulePath.endsWith(".yak.jsx")) && context.evaluateYakModule) return {
37
+ type: "yak",
38
+ exports: {
39
+ importYak: false,
40
+ named: objectToModuleExport(await context.evaluateYakModule(modulePath)),
41
+ all: []
42
+ },
43
+ path: modulePath
44
+ };
45
+ if (context.cache?.parse === void 0) return await uncachedParseModule(context, modulePath);
46
+ const cached = context.cache.parse.get(modulePath);
47
+ if (cached === void 0) {
48
+ const parsedModule = await uncachedParseModule(context, modulePath);
49
+ context.cache.parse.set(modulePath, parsedModule);
50
+ if (context.cache.parse.addDependency) context.cache.parse.addDependency(modulePath, modulePath);
51
+ return parsedModule;
52
+ }
53
+ return cached;
54
+ } catch (error) {
55
+ const causeMessage = error instanceof Error ? error.message : String(error);
56
+ throw new Error(`Error parsing file "${modulePath}"\n Caused by: ${causeMessage}`);
57
+ }
58
+ }
59
+ async function uncachedParseModule(context, modulePath) {
60
+ const exports = await context.extractExports(modulePath);
61
+ if (!exports.importYak) return {
62
+ type: "regular",
63
+ path: modulePath,
64
+ exports
65
+ };
66
+ const transformed = await context.getTransformed(modulePath);
67
+ const mixins = parseMixins(transformed.code);
68
+ return {
69
+ type: "regular",
70
+ path: modulePath,
71
+ js: transformed,
72
+ exports,
73
+ styledComponents: parseStyledComponents(transformed.code, context.transpilationMode),
74
+ mixins
75
+ };
76
+ }
77
+ function parseMixins(sourceContents) {
78
+ const mixinParts = sourceContents.split("/*YAK EXPORTED MIXIN:");
79
+ let mixins = {};
80
+ for (let i = 1; i < mixinParts.length; i++) {
81
+ const [comment] = mixinParts[i].split("*/", 1);
82
+ const position = comment.indexOf("\n");
83
+ const name = comment.slice(0, position);
84
+ mixins[name] = {
85
+ type: "mixin",
86
+ value: comment.slice(position + 1),
87
+ nameParts: name.split(":").map((part) => decodeURIComponent(part))
88
+ };
89
+ }
90
+ return mixins;
91
+ }
92
+ function parseStyledComponents(sourceContents, transpilationMode) {
93
+ const styledParts = sourceContents.split("/*YAK EXPORTED STYLED:");
94
+ let styledComponents = {};
95
+ for (let i = 1; i < styledParts.length; i++) {
96
+ const [comment] = styledParts[i].split("*/", 1);
97
+ const [componentName, className] = comment.split(":");
98
+ styledComponents[componentName] = {
99
+ type: "styled-component",
100
+ nameParts: componentName.split("."),
101
+ value: transpilationMode === "Css" ? `.${className}` : `:global(.${className})`
102
+ };
103
+ }
104
+ return styledComponents;
105
+ }
106
+ function objectToModuleExport(object) {
107
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => {
108
+ if (typeof value === "string" || typeof value === "number") return [key, {
109
+ type: "constant",
110
+ value
111
+ }];
112
+ else if (value && (typeof value === "object" || Array.isArray(value))) return [key, {
113
+ type: "record",
114
+ value: objectToModuleExport(value)
115
+ }];
116
+ else return [key, {
117
+ type: "unsupported",
118
+ hint: String(value)
119
+ }];
120
+ }));
121
+ }
122
+
123
+ //#endregion
124
+ //#region ../yak-internals/cross-file-resolver/Errors.ts
125
+ var CauseError = class CauseError extends Error {
126
+ constructor(message, options) {
127
+ super(`${message}${options?.cause ? `\n Caused by: ${typeof options.cause === "object" && options.cause !== null && "message" in options.cause ? options.cause.message : String(options.cause)}` : ""}`);
128
+ if (options?.cause instanceof CauseError && options.cause.circular) this.circular = true;
129
+ }
130
+ };
131
+ var ResolveError = class extends CauseError {};
132
+ var UnsupportedExportError = class extends ResolveError {};
133
+ var CircularDependencyError = class extends CauseError {
134
+ constructor(message, options) {
135
+ super(message, options);
136
+ this.circular = true;
137
+ }
138
+ };
139
+
140
+ //#endregion
141
+ //#region ../yak-internals/cross-file-resolver/resolveCrossFileConstant.ts
142
+ const yakCssImportRegex = /--yak-css-import:\s*url\("([^"]+)",?(|mixin|selector)\)(;?)/g;
143
+ async function resolveCrossFileConstant(context, filePath, css) {
144
+ const resolveCrossFileConstant = context.cache?.resolveCrossFileConstant;
145
+ if (resolveCrossFileConstant === void 0) return uncachedResolveCrossFileConstant(context, filePath, css);
146
+ const cacheKey = await sha1(filePath + ":" + css);
147
+ const cached = resolveCrossFileConstant.get(cacheKey);
148
+ if (cached === void 0) {
149
+ const resolvedCrossFilConstantPromise = uncachedResolveCrossFileConstant(context, filePath, css);
150
+ resolveCrossFileConstant.set(cacheKey, resolvedCrossFilConstantPromise);
151
+ if (resolveCrossFileConstant.addDependency) {
152
+ resolveCrossFileConstant.addDependency(cacheKey, filePath);
153
+ resolvedCrossFilConstantPromise.then((value) => {
154
+ for (const dep of value.dependencies) resolveCrossFileConstant.addDependency(cacheKey, dep);
155
+ });
156
+ }
157
+ return resolvedCrossFilConstantPromise;
158
+ }
159
+ return cached;
160
+ }
161
+ async function uncachedResolveCrossFileConstant(context, filePath, css) {
162
+ const yakImports = await parseYakCssImport(context, filePath, css);
163
+ if (yakImports.length === 0) return {
164
+ resolved: css,
165
+ dependencies: []
166
+ };
167
+ try {
168
+ const dependencies = /* @__PURE__ */ new Set();
169
+ const resolvedValues = await Promise.all(yakImports.map(async ({ moduleSpecifier, specifier }) => {
170
+ const { resolved: resolvedModule } = await resolveModule(context, moduleSpecifier);
171
+ const resolvedValue = await resolveModuleSpecifierRecursively(context, resolvedModule, specifier);
172
+ for (const dependency of resolvedValue.from) dependencies.add(dependency);
173
+ return resolvedValue;
174
+ }));
175
+ let result = css;
176
+ for (let i = yakImports.length - 1; i >= 0; i--) {
177
+ const { position, size, importKind, specifier, semicolon } = yakImports[i];
178
+ const resolved = resolvedValues[i];
179
+ let replacement;
180
+ if (resolved.type === "unresolved-tag") replacement = importKind === "mixin" ? "" : "undefined";
181
+ else {
182
+ if (importKind === "selector") {
183
+ if (resolved.type !== "styled-component" && resolved.type !== "constant") throw new Error(`Found "${resolved.type}" but expected a selector - did you forget a semicolon after "${specifier.join(".")}"?`);
184
+ }
185
+ replacement = resolved.type === "styled-component" ? resolved.value : resolved.value + (["}", ";"].includes(String(resolved.value).trimEnd().slice(-1)) ? "" : semicolon);
186
+ }
187
+ result = result.slice(0, position) + String(replacement) + result.slice(position + size);
188
+ }
189
+ return {
190
+ resolved: result,
191
+ dependencies: Array.from(dependencies)
192
+ };
193
+ } catch (error) {
194
+ throw new CauseError(`Error while resolving cross-file selectors in file "${filePath}"`, { cause: error });
195
+ }
196
+ }
197
+ async function parseYakCssImport(context, filePath, css) {
198
+ const yakImports = [];
199
+ for (const match of css.matchAll(yakCssImportRegex)) {
200
+ const [fullMatch, encodedArguments, importKind, semicolon] = match;
201
+ const [moduleSpecifier, ...specifier] = encodedArguments.split(":").map((entry) => decodeURIComponent(entry));
202
+ yakImports.push({
203
+ encodedArguments,
204
+ moduleSpecifier: await context.resolve(moduleSpecifier, filePath),
205
+ specifier,
206
+ importKind,
207
+ semicolon,
208
+ position: match.index,
209
+ size: fullMatch.length
210
+ });
211
+ }
212
+ return yakImports;
213
+ }
214
+ async function resolveModule(context, filePath) {
215
+ if (context.cache?.resolve === void 0) return uncachedResolveModule(context, filePath);
216
+ const cached = context.cache.resolve.get(filePath);
217
+ if (cached === void 0) {
218
+ const resolvedPromise = uncachedResolveModule(context, filePath);
219
+ context.cache.resolve.set(filePath, resolvedPromise);
220
+ if (context.cache.resolve.addDependency) {
221
+ context.cache.resolve.addDependency(filePath, filePath);
222
+ resolvedPromise.then((value) => {
223
+ for (const dep of value.dependencies) context.cache.resolve.addDependency(filePath, dep);
224
+ });
225
+ }
226
+ return resolvedPromise;
227
+ }
228
+ return cached;
229
+ }
230
+ async function uncachedResolveModule(context, filePath) {
231
+ const parsedModule = await context.parse(filePath);
232
+ const exports = parsedModule.exports;
233
+ if (parsedModule.type !== "regular") return {
234
+ resolved: {
235
+ path: parsedModule.path,
236
+ exports
237
+ },
238
+ dependencies: []
239
+ };
240
+ const dependencies = /* @__PURE__ */ new Set();
241
+ if (parsedModule.styledComponents) Object.values(parsedModule.styledComponents).map((styledComponent) => {
242
+ if (styledComponent.nameParts.length === 1) exports.named[styledComponent.nameParts[0]] = {
243
+ type: "styled-component",
244
+ className: styledComponent.value
245
+ };
246
+ else {
247
+ let exportEntry = exports.named[styledComponent.nameParts[0]];
248
+ if (!exportEntry) {
249
+ exportEntry = {
250
+ type: "record",
251
+ value: {}
252
+ };
253
+ exports.named[styledComponent.nameParts[0]] = exportEntry;
254
+ } else if (exportEntry.type !== "record") throw new CauseError(`Error parsing file "${parsedModule.path}"`, { cause: `"${styledComponent.nameParts[0]}" is not a record` });
255
+ let current = exportEntry.value;
256
+ for (let i = 1; i < styledComponent.nameParts.length - 1; i++) {
257
+ let next = current[styledComponent.nameParts[i]];
258
+ if (!next) {
259
+ next = {
260
+ type: "record",
261
+ value: {}
262
+ };
263
+ current[styledComponent.nameParts[i]] = next;
264
+ } else if (next.type !== "record") throw new CauseError(`Error parsing file "${parsedModule.path}"`, { cause: `"${styledComponent.nameParts.slice(0, i + 1).join(".")}" is not a record` });
265
+ current = next.value;
266
+ }
267
+ current[styledComponent.nameParts[styledComponent.nameParts.length - 1]] = {
268
+ type: "styled-component",
269
+ className: styledComponent.value
270
+ };
271
+ }
272
+ });
273
+ if (parsedModule.mixins) await Promise.all(Object.values(parsedModule.mixins).map(async (mixin) => {
274
+ const { resolved, dependencies: deps } = await resolveCrossFileConstant(context, parsedModule.path, mixin.value);
275
+ for (const dep of deps) dependencies.add(dep);
276
+ if (mixin.nameParts.length === 1) exports.named[mixin.nameParts[0]] = {
277
+ type: "mixin",
278
+ value: resolved
279
+ };
280
+ else {
281
+ let exportEntry = exports.named[mixin.nameParts[0]];
282
+ if (!exportEntry) {
283
+ exportEntry = {
284
+ type: "record",
285
+ value: {}
286
+ };
287
+ exports.named[mixin.nameParts[0]] = exportEntry;
288
+ } else if (exportEntry.type !== "record") throw new CauseError(`Error parsing file "${parsedModule.path}"`, { cause: `"${mixin.nameParts[0]}" is not a record` });
289
+ let current = exportEntry.value;
290
+ for (let i = 1; i < mixin.nameParts.length - 1; i++) {
291
+ let next = current[mixin.nameParts[i]];
292
+ if (!next) {
293
+ next = {
294
+ type: "record",
295
+ value: {}
296
+ };
297
+ current[mixin.nameParts[i]] = next;
298
+ } else if (next.type !== "record") throw new CauseError(`Error parsing file "${parsedModule.path}"`, { cause: `"${mixin.nameParts.slice(0, i + 1).join(".")}" is not a record` });
299
+ current = next.value;
300
+ }
301
+ current[mixin.nameParts[mixin.nameParts.length - 1]] = {
302
+ type: "mixin",
303
+ value: resolved
304
+ };
305
+ }
306
+ }));
307
+ return {
308
+ resolved: {
309
+ path: parsedModule.path,
310
+ exports
311
+ },
312
+ dependencies: Array.from(dependencies)
313
+ };
314
+ }
315
+ async function resolveModuleSpecifierRecursively(context, resolvedModule, specifiers, seen = /* @__PURE__ */ new Set()) {
316
+ const exportName = specifiers[0];
317
+ const exportValue = resolvedModule.exports.named[exportName];
318
+ if (exportValue !== void 0) {
319
+ if (seen.has(resolvedModule.path + ":" + exportName)) throw new CircularDependencyError(`Unable to resolve "${specifiers.join(".")}" in module "${resolvedModule.path}"`, { cause: "Circular dependency detected" });
320
+ seen.add(resolvedModule.path + ":" + exportName);
321
+ return resolveModuleExport(context, resolvedModule.path, exportValue, specifiers, seen);
322
+ }
323
+ let i = 1;
324
+ for (const from of resolvedModule.exports.all) {
325
+ if (context.exportAllLimit && i++ > context.exportAllLimit) throw new ResolveError(`Unable to resolve "${specifiers.join(".")}" in module "${resolvedModule.path}"`, { cause: `More than ${context.exportAllLimit} star exports are not supported for performance reasons` });
326
+ try {
327
+ const resolved = await resolveModuleExport(context, resolvedModule.path, {
328
+ type: "re-export",
329
+ from,
330
+ name: exportName
331
+ }, specifiers, seen);
332
+ if (seen.has(resolvedModule.path + ":*")) throw new CircularDependencyError(`Unable to resolve "${specifiers.join(".")}" in module "${resolvedModule.path}"`, { cause: "Circular dependency detected" });
333
+ seen.add(resolvedModule.path + ":*");
334
+ return resolved;
335
+ } catch (error) {
336
+ if (!(error instanceof ResolveError)) throw error;
337
+ if (error.circular) throw error;
338
+ }
339
+ }
340
+ throw new ResolveError(`Unable to resolve "${specifiers.join(".")}"`, { cause: `no matching export found in module "${resolvedModule.path}"` });
341
+ }
342
+ async function resolveModuleExport(context, filePath, moduleExport, specifiers, seen) {
343
+ const failureMessage = `Unable to resolve "${specifiers.join(".")}" in module "${filePath}"`;
344
+ try {
345
+ switch (moduleExport.type) {
346
+ case "re-export": {
347
+ const { resolved: reExportedModule } = await resolveModule(context, await context.resolve(moduleExport.from, filePath));
348
+ const resolved = await resolveModuleSpecifierRecursively(context, reExportedModule, [moduleExport.name, ...specifiers.slice(1)], seen);
349
+ if (resolved) resolved.from.push(filePath);
350
+ return resolved;
351
+ }
352
+ case "namespace-re-export": {
353
+ const { resolved: reExportedModule } = await resolveModule(context, await context.resolve(moduleExport.from, filePath));
354
+ const resolved = await resolveModuleSpecifierRecursively(context, reExportedModule, specifiers.slice(1), seen);
355
+ if (resolved) resolved.from.push(filePath);
356
+ return resolved;
357
+ }
358
+ case "styled-component": return {
359
+ type: "styled-component",
360
+ from: [filePath],
361
+ source: filePath,
362
+ name: specifiers[specifiers.length - 1],
363
+ value: moduleExport.className
364
+ };
365
+ case "tag-template": return {
366
+ type: "unresolved-tag",
367
+ from: [filePath],
368
+ source: filePath,
369
+ name: specifiers[specifiers.length - 1]
370
+ };
371
+ case "constant": return {
372
+ type: "constant",
373
+ from: [filePath],
374
+ source: filePath,
375
+ value: moduleExport.value
376
+ };
377
+ case "record": return resolveModuleExport(context, filePath, resolveSpecifierInRecord(moduleExport, specifiers[0], specifiers.slice(1)), specifiers, seen);
378
+ case "mixin": return {
379
+ type: "mixin",
380
+ from: [filePath],
381
+ source: filePath,
382
+ value: moduleExport.value
383
+ };
384
+ case "unsupported": throw new UnsupportedExportError(failureMessage, { cause: explainUnsupported(filePath, specifiers.join("."), moduleExport.hint, moduleExport.source) });
385
+ }
386
+ } catch (error) {
387
+ if (error instanceof UnsupportedExportError) throw error;
388
+ throw new ResolveError(failureMessage, { cause: error });
389
+ }
390
+ }
391
+ function explainUnsupported(filePath, specifier, hint, source) {
392
+ const isYakFile = /\.yak\.(?:ts|tsx|js|jsx)$/.test(filePath);
393
+ const docs = "https://yak.js.org/docs/migration-from-styled-components#move-some-code-to-yak-files";
394
+ const snippet = source ? renderSourceSnippet(filePath, source, hint ?? "") : void 0;
395
+ const lines = [];
396
+ if (isYakFile) {
397
+ const got = hint ? ` (got \`${hint}\`)` : "";
398
+ lines.push(`\`${specifier}\` evaluated to a value that cannot be inlined into CSS${got}.`);
399
+ if (snippet) lines.push(snippet);
400
+ lines.push(` help: replace it with a string, number, or plain object/array of those`, ` see: ${docs}`);
401
+ return lines.join("\n");
402
+ }
403
+ const got = hint ? ` (got a ${hint})` : "";
404
+ lines.push(`\`${specifier}\` is not a string or number literal${got}.`);
405
+ if (snippet) lines.push(snippet);
406
+ lines.push(` help: rename "${filePath}" to "${suggestYakFileName(filePath)}" so its exports run at build time`, ` (or replace \`${specifier}\` with a literal value)`, ` see: ${docs}`);
407
+ return lines.join("\n");
408
+ }
409
+ function suggestYakFileName(filePath) {
410
+ const match = filePath.match(/^(.*)\.(ts|tsx|js|jsx)$/);
411
+ if (!match) return filePath;
412
+ return `${match[1]}.yak.${match[2]}`;
413
+ }
414
+ function renderSourceSnippet(filePath, source, label) {
415
+ const startLine = source.start.line;
416
+ const startCol = source.start.column;
417
+ const caretLen = source.end.line === startLine ? Math.max(1, source.end.column - startCol) : Math.max(1, source.lineText.length - startCol);
418
+ const lineNumStr = String(startLine);
419
+ const gutterPad = " ".repeat(lineNumStr.length);
420
+ return [
421
+ ` --> ${filePath}:${startLine}:${startCol + 1}`,
422
+ ` ${gutterPad} |`,
423
+ ` ${lineNumStr} | ${source.lineText}`,
424
+ ` ${gutterPad} | ${" ".repeat(startCol)}${"^".repeat(caretLen)} ${label}`
425
+ ].join("\n");
426
+ }
427
+ function resolveSpecifierInRecord(record, name, specifiers) {
428
+ if (specifiers.length === 0) throw new ResolveError("did not expect an object");
429
+ let depth = 0;
430
+ let current = record;
431
+ while (current && current.type === "record" && depth < specifiers.length) {
432
+ current = current.value[specifiers[depth]];
433
+ depth += 1;
434
+ }
435
+ if (current === void 0 || depth !== specifiers.length) throw new ResolveError(`Unable to resolve "${specifiers.join(".")}" in object/array "${name}"`, { cause: "path not found" });
436
+ if (current.type === "constant" || current.type === "styled-component" || current.type === "mixin") return current;
437
+ if (current.type === "record" && "__yak" in current.value && current.value.__yak.type === "constant") return {
438
+ type: "mixin",
439
+ value: String(current.value.__yak.value)
440
+ };
441
+ throw new ResolveError(`Unable to resolve "${specifiers.join(".")}" in object/array "${name}"`, { cause: "only string and numbers are supported" });
442
+ }
443
+ async function sha1(message) {
444
+ const resultBuffer = await globalThis.crypto.subtle.digest("SHA-1", new TextEncoder().encode(message));
445
+ return Array.from(new Uint8Array(resultBuffer), (byte) => byte.toString(16).padStart(2, "0")).join("");
446
+ }
447
+
448
+ //#endregion
449
+ //#region ../yak-internals/loaders/lib/debugLogger.ts
450
+ function createDebugLogger(debugOptions, rootPath) {
451
+ if (!debugOptions) return () => {};
452
+ throwOnDeprecatedDebugOptions(debugOptions);
453
+ const pattern = debugOptions === true ? void 0 : debugOptions.pattern;
454
+ const typesArray = debugOptions === true ? void 0 : debugOptions.types;
455
+ let compiledPattern = null;
456
+ if (pattern) try {
457
+ compiledPattern = new RegExp(pattern);
458
+ } catch (error) {
459
+ throw new Error(`Invalid debug pattern: "${pattern}" is not a valid regular expression. ${error instanceof Error ? error.message : ""}`);
460
+ }
461
+ const types = typesArray ? new Set(typesArray) : null;
462
+ return (messageType, message, filePath) => {
463
+ if (types && !types.has(messageType)) return;
464
+ const relativePath = (0, path.relative)(rootPath, filePath);
465
+ if (!compiledPattern || compiledPattern.test(relativePath)) console.log("🐮 Yak", `[${messageType}]`, relativePath, "\n\n", message);
466
+ };
467
+ }
468
+ function throwOnDeprecatedDebugOptions(debugOptions) {
469
+ if (typeof debugOptions === "string") {
470
+ const suggestion = suggestTypesForExtensionPattern(debugOptions) ?? `debug: { pattern: "${debugOptions}" }`;
471
+ throw new Error(`The debug option no longer accepts a string. Please update your config:\n Before: debug: "${debugOptions}"\n After: ${suggestion}`);
472
+ }
473
+ if (typeof debugOptions === "object" && "filter" in debugOptions) throw new Error("The debug option no longer accepts { filter, type }. Please update your config:\n Before: debug: { filter: ..., type: \"...\" }\n After: debug: { pattern: \"...\", types: [\"ts\", \"css\", \"css-resolved\"] }");
474
+ if (typeof debugOptions === "object" && debugOptions.pattern) {
475
+ const suggestion = suggestTypesForExtensionPattern(debugOptions.pattern);
476
+ if (suggestion) throw new Error(`The debug pattern "${debugOptions.pattern}" looks like it's filtering by output type using the old file extension convention.\nThe pattern now only matches file paths. Use the "types" option to filter by output type:\n Before: debug: { pattern: "${debugOptions.pattern}" }\n After: ${suggestion}`);
477
+ }
478
+ }
479
+ function suggestTypesForExtensionPattern(pattern) {
480
+ const extensionMatch = pattern.match(/\.\(?(?:css-resolved|css)\)?\$?$/);
481
+ if (!extensionMatch) return null;
482
+ const type = extensionMatch[0].includes("css-resolved") ? "css-resolved" : "css";
483
+ const remaining = pattern.slice(0, extensionMatch.index);
484
+ return remaining ? `debug: { pattern: "${remaining}", types: ["${type}"] }` : `debug: { types: ["${type}"] }`;
485
+ }
486
+
487
+ //#endregion
488
+ //#region ../yak-internals/loaders/lib/extractCss.ts
489
+ function extractCss(code, transpilationMode) {
490
+ let codeString;
491
+ if (typeof code === "string") codeString = code;
492
+ else if (code instanceof Buffer) codeString = code.toString("utf-8");
493
+ else if (code instanceof ArrayBuffer) codeString = new TextDecoder("utf-8").decode(code);
494
+ else throw new Error("Invalid input type: code must be string, Buffer, or ArrayBuffer");
495
+ const codeParts = codeString.split("/*YAK Extracted CSS:\n");
496
+ let result = "";
497
+ for (let i = 1; i < codeParts.length; i++) {
498
+ const codeUntilEnd = codeParts[i].split("*/")[0];
499
+ result += codeUntilEnd;
500
+ }
501
+ if (result && transpilationMode !== "Css") result = "/* cssmodules-pure-no-check */\n" + result;
502
+ return result;
503
+ }
504
+
505
+ //#endregion
506
+ //#region ../yak-internals/packageNames.ts
507
+ const yakPackageNames = ["@yak/react", "@yak/solid"];
508
+
509
+ //#endregion
510
+ //#region ../yak-internals/loaders/lib/parseExports.ts
511
+ async function parseExports(sourceContents) {
512
+ try {
513
+ const ast = (0, _babel_parser.parse)(sourceContents, {
514
+ sourceType: "module",
515
+ plugins: ["jsx", "typescript"]
516
+ });
517
+ const moduleExports = {
518
+ importYak: ast.program.body.some((node) => node.type === "ImportDeclaration" && yakPackageNames.includes(node.source.value)),
519
+ named: {},
520
+ all: []
521
+ };
522
+ const variableDeclarations = {};
523
+ let defaultIdentifier = null;
524
+ for (const node of ast.program.body) {
525
+ if (node.type === "VariableDeclaration") {
526
+ for (const decl of node.declarations) if (decl.id.type === "Identifier" && decl.init) variableDeclarations[decl.id.name] = decl.init;
527
+ }
528
+ if (node.type === "ExportNamedDeclaration") {
529
+ if (node.source) for (const specifier of node.specifiers) {
530
+ if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.local.type === "Identifier") moduleExports.named[specifier.exported.name] = {
531
+ type: "re-export",
532
+ from: node.source.value,
533
+ name: specifier.local.name
534
+ };
535
+ if (specifier.type === "ExportNamespaceSpecifier" && specifier.exported.type === "Identifier") moduleExports.named[specifier.exported.name] = {
536
+ type: "namespace-re-export",
537
+ from: node.source.value
538
+ };
539
+ }
540
+ else if (node.declaration?.type === "VariableDeclaration") {
541
+ for (const declaration of node.declaration.declarations) if (declaration.id.type === "Identifier" && declaration.init) {
542
+ variableDeclarations[declaration.id.name] = declaration.init;
543
+ const parsed = parseExportValueExpression(declaration.init, sourceContents);
544
+ if (parsed) moduleExports.named[declaration.id.name] = parsed;
545
+ }
546
+ }
547
+ }
548
+ if (node.type === "ExportDefaultDeclaration") {
549
+ if (node.declaration.type === "Identifier") defaultIdentifier = node.declaration.name;
550
+ else if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") moduleExports.named["default"] = {
551
+ type: "unsupported",
552
+ hint: node.declaration.type,
553
+ source: extractUnsupportedSource(node.declaration.loc, sourceContents)
554
+ };
555
+ else moduleExports.named["default"] = parseExportValueExpression(node.declaration, sourceContents);
556
+ }
557
+ if (node.type === "ExportAllDeclaration") moduleExports.all.push(node.source.value);
558
+ }
559
+ if (defaultIdentifier && variableDeclarations[defaultIdentifier]) moduleExports.named["default"] = parseExportValueExpression(variableDeclarations[defaultIdentifier], sourceContents);
560
+ return moduleExports;
561
+ } catch (error) {
562
+ throw new Error(`Error parsing exports: ${error.message}`);
563
+ }
564
+ }
565
+ function unpackTSAsExpression(node) {
566
+ if (node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression") return unpackTSAsExpression(node.expression);
567
+ return node;
568
+ }
569
+ function parseExportValueExpression(node, code) {
570
+ const expression = unpackTSAsExpression(node);
571
+ if (expression.type === "CallExpression" || expression.type === "TaggedTemplateExpression") return { type: "tag-template" };
572
+ else if (expression.type === "StringLiteral" || expression.type === "NumericLiteral") return {
573
+ type: "constant",
574
+ value: expression.value
575
+ };
576
+ else if (expression.type === "UnaryExpression" && expression.operator === "-" && expression.argument.type === "NumericLiteral") return {
577
+ type: "constant",
578
+ value: -expression.argument.value
579
+ };
580
+ else if (expression.type === "TemplateLiteral" && expression.quasis.length === 1) return {
581
+ type: "constant",
582
+ value: expression.quasis[0].value.raw
583
+ };
584
+ else if (expression.type === "ObjectExpression") return {
585
+ type: "record",
586
+ value: parseObjectExpression(expression, code)
587
+ };
588
+ return {
589
+ type: "unsupported",
590
+ hint: expression.type,
591
+ source: extractUnsupportedSource(expression.loc, code)
592
+ };
593
+ }
594
+ function parseObjectExpression(node, code) {
595
+ let result = {};
596
+ for (const property of node.properties) if (property.type === "ObjectProperty" && property.key.type === "Identifier") {
597
+ const key = property.key.name;
598
+ const parsed = parseExportValueExpression(property.value, code);
599
+ if (parsed) result[key] = parsed;
600
+ }
601
+ return result;
602
+ }
603
+ function extractUnsupportedSource(loc, code) {
604
+ if (!loc || !code) return void 0;
605
+ const lineText = code.split(/\r?\n/)[loc.start.line - 1];
606
+ if (lineText === void 0) return void 0;
607
+ return {
608
+ start: {
609
+ line: loc.start.line,
610
+ column: loc.start.column
611
+ },
612
+ end: {
613
+ line: loc.end.line,
614
+ column: loc.end.column
615
+ },
616
+ lineText
617
+ };
618
+ }
619
+
620
+ //#endregion
621
+ //#region ../yak-internals/loaders/lib/swcParserOptions.ts
622
+ const typeScriptWithoutJsx = /\.[mc]?ts$/;
623
+ const typeScriptWithJsx = /\.tsx$/;
624
+ function getSwcParserOptions(filename) {
625
+ const [path] = filename.split("?");
626
+ if (typeScriptWithoutJsx.test(path)) return {
627
+ syntax: "typescript",
628
+ tsx: false,
629
+ dynamicImport: true
630
+ };
631
+ if (typeScriptWithJsx.test(path)) return {
632
+ syntax: "typescript",
633
+ tsx: true,
634
+ dynamicImport: true
635
+ };
636
+ return {
637
+ syntax: "ecmascript",
638
+ jsx: true,
639
+ dynamicImport: true
640
+ };
641
+ }
642
+
643
+ //#endregion
644
+ //#region loaders/turbo-evaluator.ts
645
+ var turbo_evaluator_exports = /* @__PURE__ */ __exportAll({
646
+ createCompilationEvaluator: () => createCompilationEvaluator,
647
+ getEvaluatorSingleton: () => getEvaluatorSingleton
648
+ });
649
+ function invalidateDependenciesWithDiskModifications(evaluator) {
650
+ const modificationTimes = getFileModificationTimes();
651
+ const modifiedDependencies = [];
652
+ for (const [dep, lastModificationTime] of modificationTimes) try {
653
+ const currentModificationTime = (0, node_fs.statSync)(dep).mtimeMs;
654
+ if (currentModificationTime !== lastModificationTime) {
655
+ modifiedDependencies.push(dep);
656
+ modificationTimes.set(dep, currentModificationTime);
657
+ }
658
+ } catch {
659
+ modifiedDependencies.push(dep);
660
+ modificationTimes.delete(dep);
661
+ }
662
+ if (modifiedDependencies.length > 0) evaluator.invalidate(...modifiedDependencies);
663
+ }
664
+ function recordModificationTimes(deps) {
665
+ const modificationTimes = getFileModificationTimes();
666
+ for (const dep of deps) try {
667
+ modificationTimes.set(dep, (0, node_fs.statSync)(dep).mtimeMs);
668
+ } catch {}
669
+ }
670
+ async function createCompilationEvaluator() {
671
+ const evaluator = await getEvaluatorSingleton();
672
+ invalidateDependenciesWithDiskModifications(evaluator);
673
+ return async (modulePath, onDependency) => {
674
+ const result = await evaluator.evaluate(modulePath);
675
+ if (!result.ok) {
676
+ const error = new Error(result.error.message);
677
+ if (result.error.stack) error.stack = result.error.stack;
678
+ throw error;
679
+ }
680
+ recordModificationTimes(result.dependencies);
681
+ if (onDependency) for (const dep of result.dependencies) onDependency(dep);
682
+ return result.value;
683
+ };
684
+ }
685
+ var EVALUATOR_KEY, MTIMES_KEY, getFileModificationTimes, getEvaluatorSingleton;
686
+ var init_turbo_evaluator = __esmMin((() => {
687
+ EVALUATOR_KEY = Symbol.for("@yak/react-evaluator");
688
+ MTIMES_KEY = Symbol.for("@yak/react-mtimes");
689
+ getFileModificationTimes = () => globalThis[MTIMES_KEY] ??= /* @__PURE__ */ new Map();
690
+ getEvaluatorSingleton = async () => {
691
+ const processGlobal = globalThis;
692
+ if (!processGlobal[EVALUATOR_KEY]) {
693
+ processGlobal[EVALUATOR_KEY] = import("../isolated-source-eval/index.js").then(({ createEvaluator }) => createEvaluator());
694
+ process.on("beforeExit", async () => {
695
+ await (await processGlobal[EVALUATOR_KEY]).dispose();
696
+ });
697
+ }
698
+ return processGlobal[EVALUATOR_KEY];
699
+ };
700
+ }));
701
+
702
+ //#endregion
703
+ //#region loaders/turbo-loader.ts
704
+ const yakSwcPluginPath = (typeof require === "undefined" ? (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href) : require).resolve("@yak/swc");
705
+ const dataUrlImportPrefix = "import \"data:text/css;base64,";
706
+ async function cssExtractLoader(code, sourceMap) {
707
+ const callback = this.async();
708
+ if (!code.includes("@yak/react")) return callback(null, code, sourceMap);
709
+ const { yakPluginOptions, yakOptions: { experiments } } = this.getOptions();
710
+ const debugLog = createDebugLogger(experiments?.debug, this.rootContext);
711
+ const resolveTurbopack = this.getResolve({});
712
+ const transform = createTransform(yakPluginOptions, yakSwcPluginPath);
713
+ const resolveFn = (specifier, importer) => {
714
+ return new Promise((resolve, reject) => {
715
+ resolveTurbopack((0, node_path.dirname)(importer), specifier, (err, result) => {
716
+ if (err) return reject(err);
717
+ if (!result) return reject(/* @__PURE__ */ new Error(`Could not resolve ${specifier}`));
718
+ resolve(result);
719
+ });
720
+ });
721
+ };
722
+ const crossFileDeps = /* @__PURE__ */ new Set();
723
+ let evaluate;
724
+ const fsReadFile = (filePath) => {
725
+ crossFileDeps.add(filePath);
726
+ return new Promise((resolve, reject) => this.fs.readFile(filePath, "utf-8", (err, result) => {
727
+ if (err) return reject(err);
728
+ if (!result) return reject(/* @__PURE__ */ new Error(`File not found: ${filePath}`));
729
+ resolve(result);
730
+ }));
731
+ };
732
+ try {
733
+ const result = await transform(code, this.resourcePath, this.rootContext, sourceMap);
734
+ debugLog("ts", result.code, this.resourcePath);
735
+ let css = extractCss(result.code, "Css");
736
+ debugLog("css", css, this.resourcePath);
737
+ const { resolved } = await resolveCrossFileConstant({
738
+ parse: (modulePath) => {
739
+ return parseModule({
740
+ transpilationMode: "Css",
741
+ extractExports: async (modulePath) => {
742
+ const sourceContents = await fsReadFile(modulePath);
743
+ return parseExports(sourceContents);
744
+ },
745
+ getTransformed: async (modulePath) => {
746
+ const sourceContent = await fsReadFile(modulePath);
747
+ return transform(sourceContent, modulePath, this.rootContext);
748
+ },
749
+ evaluateYakModule: async (modulePath) => {
750
+ crossFileDeps.add(modulePath);
751
+ evaluate ??= await (await Promise.resolve().then(() => (init_turbo_evaluator(), turbo_evaluator_exports))).createCompilationEvaluator();
752
+ return evaluate(modulePath, (dep) => crossFileDeps.add(dep));
753
+ }
754
+ }, modulePath);
755
+ },
756
+ resolve: resolveFn
757
+ }, this.resourcePath, css);
758
+ for (const dep of crossFileDeps) this.addDependency(dep);
759
+ const codeWithCrossFileResolved = replaceDataUrlImport(result.code, resolved);
760
+ debugLog("css-resolved", resolved, this.resourcePath);
761
+ return callback(null, codeWithCrossFileResolved, result.map);
762
+ } catch (error) {
763
+ for (const dep of crossFileDeps) this.addDependency(dep);
764
+ return callback(error instanceof Error ? error : new Error(String(error)));
765
+ }
766
+ }
767
+ function replaceDataUrlImport(code, resolvedCss) {
768
+ const lines = code.split("\n");
769
+ const lineIndex = lines.findIndex((line) => line.trimStart().startsWith(dataUrlImportPrefix));
770
+ if (lineIndex === -1) return code;
771
+ lines[lineIndex] = `${dataUrlImportPrefix}${Buffer.from(resolvedCss).toString("base64")}";`;
772
+ return lines.join("\n");
773
+ }
774
+ function createTransform(yakPluginOptions, yakSwcPluginPath) {
775
+ return (data, modulePath, rootPath, sourceMap) => (0, _swc_core.transform)(data, {
776
+ filename: modulePath,
777
+ inputSourceMap: sourceMap,
778
+ sourceMaps: true,
779
+ sourceFileName: modulePath,
780
+ sourceRoot: rootPath,
781
+ jsc: {
782
+ parser: getSwcParserOptions(modulePath),
783
+ experimental: {
784
+ keepImportAttributes: true,
785
+ plugins: [[yakSwcPluginPath, yakPluginOptions]]
786
+ },
787
+ transform: { react: { runtime: "preserve" } },
788
+ target: "es2022",
789
+ loose: false,
790
+ minify: {
791
+ compress: false,
792
+ mangle: false
793
+ },
794
+ preserveAllComments: true
795
+ },
796
+ minify: false,
797
+ isModule: true
798
+ });
799
+ }
800
+
801
+ //#endregion
802
+ module.exports = cssExtractLoader;
803
+ //# sourceMappingURL=turbo-loader.cjs.map