@tenphi/tasty 0.0.0-snapshot.fdb16ea → 0.0.0-snapshot.fde6cf3

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 (87) hide show
  1. package/dist/astro-Dj8YpRd7.js +301 -0
  2. package/dist/astro-Dj8YpRd7.js.map +1 -0
  3. package/dist/{babel-CMYf4JZ2.d.ts → babel-Cbp2C2bj.d.ts} +2 -2
  4. package/dist/{collector-Ctn5s74s.d.ts → collector-DBY6liC2.d.ts} +94 -11
  5. package/dist/collector-NjmUiB8f.js +529 -0
  6. package/dist/collector-NjmUiB8f.js.map +1 -0
  7. package/dist/{config-B23gZrfP.js → config-Bd2vOF0Z.js} +454 -105
  8. package/dist/config-Bd2vOF0Z.js.map +1 -0
  9. package/dist/{config-CZx8_DCu.d.ts → config-CA7iAlEI.d.ts} +112 -22
  10. package/dist/core/index.d.ts +5 -5
  11. package/dist/core/index.js +6 -6
  12. package/dist/{core-B1tyn69d.js → core-ClInK6YG.js} +386 -107
  13. package/dist/core-ClInK6YG.js.map +1 -0
  14. package/dist/css-resources-Cyl_axbI.js +149 -0
  15. package/dist/css-resources-Cyl_axbI.js.map +1 -0
  16. package/dist/{css-writer-CvAxkR6S.js → css-writer-BDQXG9Jo.js} +3 -3
  17. package/dist/{css-writer-CvAxkR6S.js.map → css-writer-BDQXG9Jo.js.map} +1 -1
  18. package/dist/{format-rules-BCTWVvcS.js → format-rules-CGhgoVLR.js} +22 -32
  19. package/dist/format-rules-CGhgoVLR.js.map +1 -0
  20. package/dist/{hydrate-BCPvkJj3.js → hydrate-CqbxwVh_.js} +2 -2
  21. package/dist/{hydrate-BCPvkJj3.js.map → hydrate-CqbxwVh_.js.map} +1 -1
  22. package/dist/{index-B3o0aCYV.d.ts → index-C8RFYeFW.d.ts} +61 -12
  23. package/dist/{index-CsvB0EXZ.d.ts → index-FpYK0H5g.d.ts} +49 -8
  24. package/dist/index.d.ts +5 -5
  25. package/dist/index.js +43 -27
  26. package/dist/index.js.map +1 -1
  27. package/dist/{keyframes-Dxdx3KOo.js → keyframes-BjfNVhaB.js} +45 -3
  28. package/dist/keyframes-BjfNVhaB.js.map +1 -0
  29. package/dist/{merge-styles-DJTSfz_M.d.ts → merge-styles-BQv7d3fx.d.ts} +2 -2
  30. package/dist/{merge-styles-C-uwpoNW.js → merge-styles-BbJhjesV.js} +2 -2
  31. package/dist/{merge-styles-C-uwpoNW.js.map → merge-styles-BbJhjesV.js.map} +1 -1
  32. package/dist/precompile/index.d.ts +11 -0
  33. package/dist/precompile/index.js +72 -0
  34. package/dist/precompile/index.js.map +1 -0
  35. package/dist/precompile/register.d.ts +13 -0
  36. package/dist/precompile/register.js +2 -0
  37. package/dist/register-BkC-8Zuy.js +333 -0
  38. package/dist/register-BkC-8Zuy.js.map +1 -0
  39. package/dist/{resolve-recipes-BuOvSEa2.js → resolve-recipes-B2Sf36AH.js} +3 -3
  40. package/dist/{resolve-recipes-BuOvSEa2.js.map → resolve-recipes-B2Sf36AH.js.map} +1 -1
  41. package/dist/ssr/astro-client.js +1 -1
  42. package/dist/ssr/astro-middleware-extract-static.d.ts +11 -0
  43. package/dist/ssr/astro-middleware-extract-static.js +9 -0
  44. package/dist/ssr/astro-middleware-extract-static.js.map +1 -0
  45. package/dist/ssr/astro-middleware-extract.d.ts +11 -0
  46. package/dist/ssr/astro-middleware-extract.js +9 -0
  47. package/dist/ssr/astro-middleware-extract.js.map +1 -0
  48. package/dist/ssr/astro-middleware-static.d.ts +3 -1
  49. package/dist/ssr/astro-middleware-static.js +1 -1
  50. package/dist/ssr/astro-middleware.d.ts +3 -1
  51. package/dist/ssr/astro-middleware.js +1 -1
  52. package/dist/ssr/astro.d.ts +45 -3
  53. package/dist/ssr/astro.js +1 -156
  54. package/dist/ssr/index.d.ts +2 -2
  55. package/dist/ssr/index.js +3 -3
  56. package/dist/ssr/index.js.map +1 -1
  57. package/dist/ssr/next-config.d.ts +66 -0
  58. package/dist/ssr/next-config.js +115 -0
  59. package/dist/ssr/next-config.js.map +1 -0
  60. package/dist/ssr/next.d.ts +9 -2
  61. package/dist/ssr/next.js +26 -9
  62. package/dist/ssr/next.js.map +1 -1
  63. package/dist/ssr-collector-ref-COs_ioWl.js +29 -0
  64. package/dist/ssr-collector-ref-COs_ioWl.js.map +1 -0
  65. package/dist/static/index.d.ts +2 -2
  66. package/dist/static/index.js +1 -1
  67. package/dist/types-Bo5ePLZh.d.ts +111 -0
  68. package/dist/zero/babel.d.ts +1 -1
  69. package/dist/zero/babel.js +4 -4
  70. package/dist/zero/babel.js.map +1 -1
  71. package/dist/zero/index.d.ts +1 -1
  72. package/dist/zero/index.js +1 -1
  73. package/dist/zero/next.d.ts +1 -1
  74. package/docs/README.md +3 -1
  75. package/docs/debug.md +17 -6
  76. package/docs/injector.md +23 -3
  77. package/docs/precompile.md +202 -0
  78. package/docs/runtime-benchmarks.md +143 -72
  79. package/docs/ssr.md +179 -20
  80. package/package.json +44 -10
  81. package/dist/collector-DMSR6ANK.js +0 -304
  82. package/dist/collector-DMSR6ANK.js.map +0 -1
  83. package/dist/config-B23gZrfP.js.map +0 -1
  84. package/dist/core-B1tyn69d.js.map +0 -1
  85. package/dist/format-rules-BCTWVvcS.js.map +0 -1
  86. package/dist/keyframes-Dxdx3KOo.js.map +0 -1
  87. package/dist/ssr/astro.js.map +0 -1
package/dist/ssr/astro.js CHANGED
@@ -1,157 +1,2 @@
1
- import { n as getConfig } from "../config-B23gZrfP.js";
2
- import { a as registerSSRCollectorGetterGlobal } from "../format-rules-BCTWVvcS.js";
3
- import { t as ServerStyleCollector } from "../collector-DMSR6ANK.js";
4
- import { n as runWithCollector, t as getSSRCollector } from "../async-storage-DKK-wTD4.js";
5
- //#region src/ssr/astro.ts
6
- /**
7
- * Astro integration for Tasty SSR.
8
- *
9
- * Provides:
10
- * - tastyIntegration() — Astro Integration API (recommended)
11
- * - tastyMiddleware() — manual middleware for advanced composition
12
- *
13
- * Import from '@tenphi/tasty/ssr/astro'.
14
- */
15
- registerSSRCollectorGetterGlobal(getSSRCollector);
16
- /**
17
- * Create an Astro middleware that collects Tasty styles during SSR.
18
- *
19
- * All React components rendered during the request will have their
20
- * computeStyles() calls captured by the collector via AsyncLocalStorage.
21
- * After rendering, the middleware injects the collected CSS into </head>.
22
- *
23
- * @example Manual middleware setup
24
- * ```ts
25
- * // src/middleware.ts
26
- * import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';
27
- * export const onRequest = tastyMiddleware();
28
- * ```
29
- *
30
- * @example Composing with other middleware
31
- * ```ts
32
- * // src/middleware.ts
33
- * import { sequence } from 'astro:middleware';
34
- * import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';
35
- *
36
- * export const onRequest = sequence(
37
- * tastyMiddleware(),
38
- * myOtherMiddleware,
39
- * );
40
- * ```
41
- */
42
- function tastyMiddleware(options) {
43
- return async (_context, next) => {
44
- const transferCache = options?.transferCache ?? true;
45
- const collector = new ServerStyleCollector();
46
- const rendered = await runWithCollector(collector, async () => {
47
- const response = await next();
48
- const body = response.body;
49
- const contentType = response.headers.get("content-type") ?? "";
50
- if (!body || !contentType.includes("text/html")) return { response };
51
- const reader = body.pipeThrough(new TextDecoderStream()).getReader();
52
- const parts = [];
53
- for (;;) {
54
- const { done, value } = await reader.read();
55
- if (done) break;
56
- parts.push(value);
57
- }
58
- return {
59
- html: parts.join(""),
60
- status: response.status,
61
- headers: response.headers
62
- };
63
- });
64
- if ("response" in rendered) return rendered.response;
65
- if (!rendered.html) return new Response(null, {
66
- status: rendered.status,
67
- headers: rendered.headers
68
- });
69
- let { html } = rendered;
70
- const css = collector.getCSS();
71
- if (!css) return new Response(html, {
72
- status: rendered.status,
73
- headers: rendered.headers
74
- });
75
- const nonce = getConfig().nonce;
76
- const nonceAttr = nonce ? ` nonce="${nonce}"` : "";
77
- const styleTag = `<style data-tasty-ssr${nonceAttr}>${css}</style>`;
78
- let cacheTag = "";
79
- if (transferCache) {
80
- const classNames = collector.getRenderedClassNames();
81
- if (classNames.length > 0) cacheTag = `<script${nonceAttr}>(window.__TASTY__=window.__TASTY__||[]).push(${classNames.map((n) => `"${n}"`).join(",")})<\/script>`;
82
- }
83
- const injection = styleTag + cacheTag;
84
- const idx = html.indexOf("</head>");
85
- if (idx !== -1) html = html.slice(0, idx) + injection + html.slice(idx);
86
- else html = injection + html;
87
- const headers = new Headers(rendered.headers);
88
- headers.delete("content-length");
89
- return new Response(html, {
90
- status: rendered.status,
91
- headers
92
- });
93
- };
94
- }
95
- /**
96
- * Package subpaths of the middleware entrypoints registered by
97
- * `tastyIntegration()`.
98
- *
99
- * These must be bare specifiers rather than
100
- * `new URL('./astro-middleware.js', import.meta.url)`. The bundler is free to
101
- * hoist `tastyIntegration` into a shared chunk at a different directory depth
102
- * than `dist/ssr/`, which makes a relative URL resolve to a file that does not
103
- * exist and breaks the build for every consumer. A package subpath is resolved
104
- * by the consumer through our `exports` map, so it never depends on the
105
- * chunk layout.
106
- *
107
- * There are two entrypoints instead of one parameterised entrypoint because
108
- * `addMiddleware()` cannot pass options: the integration runs when the Astro
109
- * config is loaded, while the middleware module is evaluated in the server
110
- * runtime — a different process for built output — so module-level state set
111
- * by the integration is not visible to the middleware.
112
- */
113
- const MIDDLEWARE_ENTRYPOINT = "@tenphi/tasty/ssr/astro-middleware";
114
- const MIDDLEWARE_ENTRYPOINT_STATIC = "@tenphi/tasty/ssr/astro-middleware-static";
115
- /**
116
- * Astro integration that automatically sets up Tasty SSR.
117
- *
118
- * Registers middleware for cross-component CSS deduplication and
119
- * optionally injects a client hydration script for island support.
120
- *
121
- * @example Basic setup (with islands)
122
- * ```ts
123
- * // astro.config.mjs
124
- * import { tastyIntegration } from '@tenphi/tasty/ssr/astro';
125
- *
126
- * export default defineConfig({
127
- * integrations: [tastyIntegration()],
128
- * });
129
- * ```
130
- *
131
- * @example Static-only (no client JS)
132
- * ```ts
133
- * // astro.config.mjs
134
- * import { tastyIntegration } from '@tenphi/tasty/ssr/astro';
135
- *
136
- * export default defineConfig({
137
- * integrations: [tastyIntegration({ islands: false })],
138
- * });
139
- * ```
140
- */
141
- function tastyIntegration(options) {
142
- const { islands = true } = options ?? {};
143
- return {
144
- name: "@tenphi/tasty",
145
- hooks: { "astro:config:setup": ({ addMiddleware, injectScript }) => {
146
- addMiddleware({
147
- entrypoint: islands ? MIDDLEWARE_ENTRYPOINT : MIDDLEWARE_ENTRYPOINT_STATIC,
148
- order: "pre"
149
- });
150
- if (islands) injectScript("before-hydration", `import "@tenphi/tasty/ssr/astro-client";`);
151
- } }
152
- };
153
- }
154
- //#endregion
1
+ import { n as tastyMiddleware, t as tastyIntegration } from "../astro-Dj8YpRd7.js";
155
2
  export { tastyIntegration, tastyMiddleware };
156
-
157
- //# sourceMappingURL=astro.js.map
@@ -1,4 +1,4 @@
1
- import { n as createServerStyleCollector, t as ServerStyleCollector } from "../collector-Ctn5s74s.js";
1
+ import { i as createServerStyleCollector, n as ServerStyleArtifactKind, r as ServerStyleCollector, t as ServerStyleArtifact } from "../collector-DBY6liC2.js";
2
2
 
3
3
  //#region src/ssr/async-storage.d.ts
4
4
  /**
@@ -33,5 +33,5 @@ declare function getSSRCollector(): ServerStyleCollector | null;
33
33
  */
34
34
  declare function hydrateTastyClasses(classes?: string[]): void;
35
35
  //#endregion
36
- export { ServerStyleCollector, createServerStyleCollector, getSSRCollector, hydrateTastyClasses, runWithCollector };
36
+ export { type ServerStyleArtifact, type ServerStyleArtifactKind, ServerStyleCollector, createServerStyleCollector, getSSRCollector, hydrateTastyClasses, runWithCollector };
37
37
  //# sourceMappingURL=index.d.ts.map
package/dist/ssr/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { a as registerSSRCollectorGetterGlobal } from "../format-rules-BCTWVvcS.js";
2
- import { n as createServerStyleCollector, t as ServerStyleCollector } from "../collector-DMSR6ANK.js";
1
+ import { r as registerSSRCollectorGetterGlobal } from "../ssr-collector-ref-COs_ioWl.js";
2
+ import { n as createServerStyleCollector, t as ServerStyleCollector } from "../collector-NjmUiB8f.js";
3
3
  import { n as runWithCollector, t as getSSRCollector } from "../async-storage-DKK-wTD4.js";
4
- import { t as hydrateTastyClasses } from "../hydrate-BCPvkJj3.js";
4
+ import { t as hydrateTastyClasses } from "../hydrate-CqbxwVh_.js";
5
5
  //#region src/ssr/index.ts
6
6
  registerSSRCollectorGetterGlobal(getSSRCollector);
7
7
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/ssr/index.ts"],"sourcesContent":["/**\n * SSR entry point for @tenphi/tasty.\n *\n * Provides the core SSR infrastructure: ServerStyleCollector,\n * AsyncLocalStorage integration, and cache hydration.\n *\n * Import from '@tenphi/tasty/ssr'.\n */\n\n// Core collector\nexport { ServerStyleCollector, createServerStyleCollector } from './collector';\n\n// AsyncLocalStorage integration for Astro / generic frameworks\nexport { runWithCollector, getSSRCollector } from './async-storage';\n\n// Client-side cache hydration\nexport { hydrateTastyClasses } from './hydrate';\n\n// Register the ALS getter so hooks can find the collector\n// without importing 'node:async_hooks' in the browser bundle.\n// Uses globalThis so the getter is visible across separate module graphs.\nimport { getSSRCollector } from './async-storage';\nimport { registerSSRCollectorGetterGlobal } from './ssr-collector-ref';\n\nregisterSSRCollectorGetterGlobal(getSSRCollector);\n"],"mappings":";;;;;AAwBA,iCAAiC,eAAe"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/ssr/index.ts"],"sourcesContent":["/**\n * SSR entry point for @tenphi/tasty.\n *\n * Provides the core SSR infrastructure: ServerStyleCollector,\n * AsyncLocalStorage integration, and cache hydration.\n *\n * Import from '@tenphi/tasty/ssr'.\n */\n\n// Core collector\nexport { ServerStyleCollector, createServerStyleCollector } from './collector';\nexport type { ServerStyleArtifact, ServerStyleArtifactKind } from './collector';\n\n// AsyncLocalStorage integration for Astro / generic frameworks\nexport { runWithCollector, getSSRCollector } from './async-storage';\n\n// Client-side cache hydration\nexport { hydrateTastyClasses } from './hydrate';\n\n// Register the ALS getter so hooks can find the collector\n// without importing 'node:async_hooks' in the browser bundle.\n// Uses globalThis so the getter is visible across separate module graphs.\nimport { getSSRCollector } from './async-storage';\nimport { registerSSRCollectorGetterGlobal } from './ssr-collector-ref';\n\nregisterSSRCollectorGetterGlobal(getSSRCollector);\n"],"mappings":";;;;;AAyBA,iCAAiC,eAAe"}
@@ -0,0 +1,66 @@
1
+ import { t as TastyConfig } from "../config-CA7iAlEI.js";
2
+
3
+ //#region src/ssr/next-config.d.ts
4
+ interface NextConfig {
5
+ basePath?: string;
6
+ env?: Record<string, string | undefined>;
7
+ headers?: () => Promise<NextHeader[]>;
8
+ output?: string;
9
+ [key: string]: unknown;
10
+ }
11
+ interface NextHeader {
12
+ source: string;
13
+ headers: {
14
+ key: string;
15
+ value: string;
16
+ }[];
17
+ [key: string]: unknown;
18
+ }
19
+ interface TastyNextOptions {
20
+ /**
21
+ * Next.js project directory. Useful when the build command runs from a
22
+ * monorepo root rather than the app directory.
23
+ *
24
+ * @default process.cwd()
25
+ */
26
+ rootDir?: string;
27
+ /**
28
+ * Tasty configuration used to generate the shared stylesheet.
29
+ * `config` takes precedence when both config sources are provided.
30
+ */
31
+ config?: TastyConfig;
32
+ /**
33
+ * Project-relative path to a TypeScript/JavaScript module whose default
34
+ * export is a Tasty configuration object.
35
+ *
36
+ * @example './app/tasty.config.ts'
37
+ */
38
+ configFile?: string;
39
+ /**
40
+ * Filesystem directory for generated stylesheets. When it is inside the
41
+ * project's `public` directory, its public URL is inferred automatically.
42
+ *
43
+ * @default 'public/_tasty'
44
+ */
45
+ outputDir?: string;
46
+ /**
47
+ * Root-relative URL path corresponding to `outputDir`. This is required
48
+ * when `outputDir` is outside the project's `public` directory.
49
+ * The Next.js `basePath` is prepended automatically.
50
+ *
51
+ * @default inferred from outputDir
52
+ * @example '/assets/tasty'
53
+ */
54
+ publicPath?: string;
55
+ /** Whether to generate and register the shared stylesheet. @default true */
56
+ enabled?: boolean;
57
+ }
58
+ /**
59
+ * Add a cacheable, content-hashed stylesheet for Tasty configuration globals.
60
+ * Route-dependent component and hook styles continue to stream through
61
+ * `TastyRegistry` so App Router navigation and Suspense remain correct.
62
+ */
63
+ declare function withTastyNext(options: TastyNextOptions): (nextConfig?: NextConfig) => NextConfig;
64
+ //#endregion
65
+ export { TastyNextOptions, withTastyNext };
66
+ //# sourceMappingURL=next-config.d.ts.map
@@ -0,0 +1,115 @@
1
+ import { t as configure, x as resetConfig } from "../config-Bd2vOF0Z.js";
2
+ import { t as ServerStyleCollector } from "../collector-NjmUiB8f.js";
3
+ import { t as findUnsafeCSSResource } from "../css-resources-Cyl_axbI.js";
4
+ import { createHash } from "node:crypto";
5
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { createRequire } from "node:module";
7
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
8
+ //#region src/ssr/next-config.ts
9
+ /**
10
+ * Next.js configuration wrapper for extracting Tasty's configured global CSS.
11
+ *
12
+ * Import this Node-only module from `next.config.ts`. The client-safe registry
13
+ * remains available from `@tenphi/tasty/ssr/next`.
14
+ */
15
+ const ENV_KEY = "TASTY_NEXT_SHARED_CSS_HREF";
16
+ const packageRequire = createRequire(import.meta.url);
17
+ function loadConfig(projectDir, options) {
18
+ if (options.config) return options.config;
19
+ if (!options.configFile) throw new Error("[Tasty] withTastyNext() requires either `config` or `configFile`.");
20
+ const configPath = resolve(projectDir, options.configFile);
21
+ let jitiPath;
22
+ try {
23
+ jitiPath = packageRequire.resolve("jiti");
24
+ } catch (error) {
25
+ if (error instanceof Error && "code" in error && error.code === "MODULE_NOT_FOUND") throw new Error("[Tasty] `configFile` requires the optional `jiti` package. Install `jiti` or pass the imported config through `config` instead.", { cause: error });
26
+ throw error;
27
+ }
28
+ const { createJiti } = packageRequire(jitiPath);
29
+ const loaded = createJiti(projectDir, { moduleCache: false })(configPath);
30
+ return loaded && typeof loaded === "object" && "default" in loaded ? loaded.default : loaded;
31
+ }
32
+ function collectSharedCSS(config) {
33
+ resetConfig();
34
+ try {
35
+ configure(config);
36
+ const collector = new ServerStyleCollector();
37
+ collector.collectInternals();
38
+ const artifacts = collector.getArtifacts();
39
+ for (const artifact of artifacts) {
40
+ const unsafe = findUnsafeCSSResource(artifact.css, false);
41
+ if (unsafe) throw new Error(`[Tasty] Next.js shared CSS extraction cannot preserve page-relative CSS URL "${unsafe.url}" in ${artifact.kind} artifact ${artifact.id}. Use an absolute URL, a data URL, or a root-relative URL such as url(/path/to/asset).`);
42
+ }
43
+ return artifacts.map(({ css }) => css).join("\n");
44
+ } finally {
45
+ resetConfig();
46
+ }
47
+ }
48
+ function inferPublicPath(projectDir, outputDir) {
49
+ const relativePath = relative(resolve(projectDir, "public"), outputDir);
50
+ if (relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) throw new Error("[Tasty] `publicPath` is required when `outputDir` is outside the Next.js public directory.");
51
+ return `/${relativePath.split(sep).filter(Boolean).join("/")}`;
52
+ }
53
+ function normalizeURLPath(path, option) {
54
+ if (!path.startsWith("/") || path.startsWith("//") || path.includes("?") || path.includes("#") || path.includes("\\")) throw new Error(`[Tasty] \`${option}\` must be a root-relative URL path.`);
55
+ let end = path.length;
56
+ while (end > 0 && path[end - 1] === "/") end--;
57
+ return path.slice(0, end);
58
+ }
59
+ function writeSharedCSS(outputDir, css) {
60
+ mkdirSync(outputDir, { recursive: true });
61
+ const filename = `tasty.shared.${createHash("sha256").update(css).digest("hex").slice(0, 12)}.css`;
62
+ const outputPath = join(outputDir, filename);
63
+ let existing;
64
+ try {
65
+ existing = readFileSync(outputPath, "utf8");
66
+ } catch {}
67
+ if (existing !== css) writeFileSync(outputPath, css);
68
+ return filename;
69
+ }
70
+ /**
71
+ * Add a cacheable, content-hashed stylesheet for Tasty configuration globals.
72
+ * Route-dependent component and hook styles continue to stream through
73
+ * `TastyRegistry` so App Router navigation and Suspense remain correct.
74
+ */
75
+ function withTastyNext(options) {
76
+ return (nextConfig = {}) => {
77
+ if (options.enabled === false) return nextConfig;
78
+ const projectDir = resolve(process.cwd(), options.rootDir ?? ".");
79
+ const outputDir = resolve(projectDir, options.outputDir ?? "public/_tasty");
80
+ const publicPath = normalizeURLPath(options.publicPath ?? inferPublicPath(projectDir, outputDir), "publicPath");
81
+ const basePath = normalizeURLPath(nextConfig.basePath || "/", "basePath");
82
+ const css = collectSharedCSS(loadConfig(projectDir, options));
83
+ if (!css) return nextConfig;
84
+ const filename = writeSharedCSS(outputDir, css);
85
+ const href = `${basePath}${publicPath}/${filename}`;
86
+ const headerSource = `${publicPath}/${filename}`;
87
+ const existingEnv = nextConfig.env ?? {};
88
+ const existingHeaders = nextConfig.headers;
89
+ if (existingEnv[ENV_KEY] && existingEnv[ENV_KEY] !== href) throw new Error(`[Tasty] Next.js env key ${ENV_KEY} is reserved by withTastyNext().`);
90
+ const generatedConfig = {
91
+ ...nextConfig,
92
+ env: {
93
+ ...existingEnv,
94
+ [ENV_KEY]: href
95
+ }
96
+ };
97
+ if (nextConfig.output === "export") return generatedConfig;
98
+ return {
99
+ ...generatedConfig,
100
+ async headers() {
101
+ return [...existingHeaders ? await existingHeaders() : [], {
102
+ source: headerSource,
103
+ headers: [{
104
+ key: "Cache-Control",
105
+ value: "public, max-age=31536000, immutable"
106
+ }]
107
+ }];
108
+ }
109
+ };
110
+ };
111
+ }
112
+ //#endregion
113
+ export { withTastyNext };
114
+
115
+ //# sourceMappingURL=next-config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next-config.js","names":[],"sources":["../../src/ssr/next-config.ts"],"sourcesContent":["/**\n * Next.js configuration wrapper for extracting Tasty's configured global CSS.\n *\n * Import this Node-only module from `next.config.ts`. The client-safe registry\n * remains available from `@tenphi/tasty/ssr/next`.\n */\n\nimport { createHash } from 'node:crypto';\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport type { createJiti as createJitiType } from 'jiti';\n\nimport { configure, resetConfig, type TastyConfig } from '../config';\nimport { ServerStyleCollector } from './collector';\nimport { findUnsafeCSSResource } from './css-resources';\n\nconst ENV_KEY = 'TASTY_NEXT_SHARED_CSS_HREF';\nconst packageRequire = createRequire(import.meta.url);\n\ninterface NextConfig {\n basePath?: string;\n env?: Record<string, string | undefined>;\n headers?: () => Promise<NextHeader[]>;\n output?: string;\n [key: string]: unknown;\n}\n\ninterface NextHeader {\n source: string;\n headers: { key: string; value: string }[];\n [key: string]: unknown;\n}\n\nexport interface TastyNextOptions {\n /**\n * Next.js project directory. Useful when the build command runs from a\n * monorepo root rather than the app directory.\n *\n * @default process.cwd()\n */\n rootDir?: string;\n\n /**\n * Tasty configuration used to generate the shared stylesheet.\n * `config` takes precedence when both config sources are provided.\n */\n config?: TastyConfig;\n\n /**\n * Project-relative path to a TypeScript/JavaScript module whose default\n * export is a Tasty configuration object.\n *\n * @example './app/tasty.config.ts'\n */\n configFile?: string;\n\n /**\n * Filesystem directory for generated stylesheets. When it is inside the\n * project's `public` directory, its public URL is inferred automatically.\n *\n * @default 'public/_tasty'\n */\n outputDir?: string;\n\n /**\n * Root-relative URL path corresponding to `outputDir`. This is required\n * when `outputDir` is outside the project's `public` directory.\n * The Next.js `basePath` is prepended automatically.\n *\n * @default inferred from outputDir\n * @example '/assets/tasty'\n */\n publicPath?: string;\n\n /** Whether to generate and register the shared stylesheet. @default true */\n enabled?: boolean;\n}\n\nfunction loadConfig(\n projectDir: string,\n options: TastyNextOptions,\n): TastyConfig {\n if (options.config) return options.config;\n if (!options.configFile) {\n throw new Error(\n '[Tasty] withTastyNext() requires either `config` or `configFile`.',\n );\n }\n\n const configPath = resolve(projectDir, options.configFile);\n let jitiPath: string;\n try {\n jitiPath = packageRequire.resolve('jiti');\n } catch (error) {\n if (\n error instanceof Error &&\n 'code' in error &&\n error.code === 'MODULE_NOT_FOUND'\n ) {\n throw new Error(\n '[Tasty] `configFile` requires the optional `jiti` package. Install `jiti` or pass the imported config through `config` instead.',\n { cause: error },\n );\n }\n throw error;\n }\n const { createJiti } = packageRequire(jitiPath) as {\n createJiti: typeof createJitiType;\n };\n const jiti = createJiti(projectDir, { moduleCache: false });\n const loaded = jiti(configPath) as TastyConfig | { default: TastyConfig };\n\n return loaded && typeof loaded === 'object' && 'default' in loaded\n ? loaded.default\n : loaded;\n}\n\nfunction collectSharedCSS(config: TastyConfig): string {\n resetConfig();\n try {\n configure(config);\n const collector = new ServerStyleCollector();\n collector.collectInternals();\n const artifacts = collector.getArtifacts();\n\n for (const artifact of artifacts) {\n const unsafe = findUnsafeCSSResource(artifact.css, false);\n if (unsafe) {\n throw new Error(\n `[Tasty] Next.js shared CSS extraction cannot preserve page-relative CSS URL \"${unsafe.url}\" in ${artifact.kind} artifact ${artifact.id}. Use an absolute URL, a data URL, or a root-relative URL such as url(/path/to/asset).`,\n );\n }\n }\n\n return artifacts.map(({ css }) => css).join('\\n');\n } finally {\n resetConfig();\n }\n}\n\nfunction inferPublicPath(projectDir: string, outputDir: string): string {\n const publicDir = resolve(projectDir, 'public');\n const relativePath = relative(publicDir, outputDir);\n if (\n relativePath === '..' ||\n relativePath.startsWith(`..${sep}`) ||\n isAbsolute(relativePath)\n ) {\n throw new Error(\n '[Tasty] `publicPath` is required when `outputDir` is outside the Next.js public directory.',\n );\n }\n\n return `/${relativePath.split(sep).filter(Boolean).join('/')}`;\n}\n\nfunction normalizeURLPath(path: string, option: string): string {\n if (\n !path.startsWith('/') ||\n path.startsWith('//') ||\n path.includes('?') ||\n path.includes('#') ||\n path.includes('\\\\')\n ) {\n throw new Error(`[Tasty] \\`${option}\\` must be a root-relative URL path.`);\n }\n\n let end = path.length;\n while (end > 0 && path[end - 1] === '/') end--;\n return path.slice(0, end);\n}\n\nfunction writeSharedCSS(outputDir: string, css: string): string {\n mkdirSync(outputDir, { recursive: true });\n const hash = createHash('sha256').update(css).digest('hex').slice(0, 12);\n const filename = `tasty.shared.${hash}.css`;\n\n const outputPath = join(outputDir, filename);\n let existing: string | undefined;\n try {\n existing = readFileSync(outputPath, 'utf8');\n } catch {\n // The file does not exist yet (or is unreadable); write it below.\n }\n if (existing !== css) writeFileSync(outputPath, css);\n\n return filename;\n}\n\n/**\n * Add a cacheable, content-hashed stylesheet for Tasty configuration globals.\n * Route-dependent component and hook styles continue to stream through\n * `TastyRegistry` so App Router navigation and Suspense remain correct.\n */\nexport function withTastyNext(options: TastyNextOptions) {\n return (nextConfig: NextConfig = {}): NextConfig => {\n if (options.enabled === false) return nextConfig;\n\n const projectDir = resolve(process.cwd(), options.rootDir ?? '.');\n const outputDir = resolve(projectDir, options.outputDir ?? 'public/_tasty');\n const publicPath = normalizeURLPath(\n options.publicPath ?? inferPublicPath(projectDir, outputDir),\n 'publicPath',\n );\n const basePath = normalizeURLPath(nextConfig.basePath || '/', 'basePath');\n const css = collectSharedCSS(loadConfig(projectDir, options));\n\n if (!css) return nextConfig;\n\n const filename = writeSharedCSS(outputDir, css);\n const href = `${basePath}${publicPath}/${filename}`;\n const headerSource = `${publicPath}/${filename}`;\n const existingEnv = nextConfig.env ?? {};\n const existingHeaders = nextConfig.headers;\n if (existingEnv[ENV_KEY] && existingEnv[ENV_KEY] !== href) {\n throw new Error(\n `[Tasty] Next.js env key ${ENV_KEY} is reserved by withTastyNext().`,\n );\n }\n\n const generatedConfig: NextConfig = {\n ...nextConfig,\n env: {\n ...existingEnv,\n [ENV_KEY]: href,\n },\n };\n\n // `headers()` is not emitted by Next's static export. Avoid introducing an\n // unsupported-config warning; the content hash still makes the asset safe\n // for the static host to cache immutably.\n if (nextConfig.output === 'export') return generatedConfig;\n\n return {\n ...generatedConfig,\n async headers() {\n const headers = existingHeaders ? await existingHeaders() : [];\n return [\n ...headers,\n {\n source: headerSource,\n headers: [\n {\n key: 'Cache-Control',\n value: 'public, max-age=31536000, immutable',\n },\n ],\n },\n ];\n },\n };\n };\n}\n"],"mappings":"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"}
@@ -1,4 +1,4 @@
1
- import { t as ServerStyleCollector } from "../collector-Ctn5s74s.js";
1
+ import { r as ServerStyleCollector } from "../collector-DBY6liC2.js";
2
2
  import { ReactNode } from "react";
3
3
 
4
4
  //#region src/ssr/next.d.ts
@@ -11,6 +11,12 @@ interface TastyRegistryProps {
11
11
  * in server-rendered `<style>` tags. Default: true.
12
12
  */
13
13
  transferCache?: boolean;
14
+ /**
15
+ * URL of a stylesheet containing Tasty's configured global CSS.
16
+ * `withTastyNext()` sets this automatically. Pass false to disable it for
17
+ * this registry, or a URL to use a manually generated stylesheet.
18
+ */
19
+ sharedStylesheet?: string | false;
14
20
  }
15
21
  /**
16
22
  * Next.js App Router registry for Tasty SSR.
@@ -38,7 +44,8 @@ interface TastyRegistryProps {
38
44
  */
39
45
  declare function TastyRegistry({
40
46
  children,
41
- transferCache
47
+ transferCache,
48
+ sharedStylesheet
42
49
  }: TastyRegistryProps): import("react").FunctionComponentElement<import("react").ProviderProps<ServerStyleCollector | null>>;
43
50
  //#endregion
44
51
  export { TastyRegistry, TastyRegistryProps };
package/dist/ssr/next.js CHANGED
@@ -1,9 +1,9 @@
1
1
  "use client";
2
- import { n as getConfig } from "../config-B23gZrfP.js";
3
- import { i as registerSSRCollectorGetter } from "../format-rules-BCTWVvcS.js";
2
+ import { n as getConfig } from "../config-Bd2vOF0Z.js";
3
+ import { n as registerSSRCollectorGetter } from "../ssr-collector-ref-COs_ioWl.js";
4
4
  import { t as getTastySSRContext } from "../context-CA8YKeMn.js";
5
- import { t as ServerStyleCollector } from "../collector-DMSR6ANK.js";
6
- import { t as hydrateTastyClasses } from "../hydrate-BCPvkJj3.js";
5
+ import { t as ServerStyleCollector } from "../collector-NjmUiB8f.js";
6
+ import { t as hydrateTastyClasses } from "../hydrate-CqbxwVh_.js";
7
7
  import { Fragment, createElement, useState } from "react";
8
8
  import { useServerInsertedHTML } from "next/navigation";
9
9
  //#region src/ssr/next.ts
@@ -39,32 +39,49 @@ if (typeof window !== "undefined") hydrateTastyClasses();
39
39
  * }
40
40
  * ```
41
41
  */
42
- function TastyRegistry({ children, transferCache = true }) {
42
+ function TastyRegistry({ children, transferCache = true, sharedStylesheet = process.env.TASTY_NEXT_SHARED_CSS_HREF }) {
43
43
  const isClient = typeof window !== "undefined";
44
44
  const [collector] = useState(() => {
45
45
  if (isClient) return null;
46
46
  const instance = new ServerStyleCollector();
47
47
  registerSSRCollectorGetter(() => instance);
48
+ if (sharedStylesheet) {
49
+ instance.collectInternals();
50
+ instance.flushCSS();
51
+ }
48
52
  return instance;
49
53
  });
54
+ const [streamState] = useState(() => ({ sharedStylesheetFlushed: false }));
50
55
  const nonce = getConfig().nonce;
51
56
  useServerInsertedHTML(() => {
52
57
  if (!collector) return null;
53
58
  const css = collector.flushCSS();
54
59
  const classNames = collector.getRenderedClassNames();
55
- if (!css) return null;
60
+ let linkEl = null;
61
+ if (sharedStylesheet && !streamState.sharedStylesheetFlushed) {
62
+ streamState.sharedStylesheetFlushed = true;
63
+ linkEl = createElement("link", {
64
+ key: "tasty-shared-styles",
65
+ rel: "stylesheet",
66
+ href: sharedStylesheet,
67
+ "data-tasty-ssr": "",
68
+ nonce
69
+ });
70
+ }
71
+ if (!css) return linkEl;
56
72
  const styleEl = createElement("style", {
57
73
  key: "tasty-ssr-styles",
58
74
  "data-tasty-ssr": "",
59
75
  nonce,
60
76
  dangerouslySetInnerHTML: { __html: css }
61
77
  });
62
- if (!transferCache || classNames.length === 0) return styleEl;
63
- return createElement(Fragment, null, styleEl, createElement("script", {
78
+ if (!transferCache || classNames.length === 0) return linkEl ? createElement(Fragment, null, linkEl, styleEl) : styleEl;
79
+ const scriptEl = createElement("script", {
64
80
  key: "tasty-ssr-cache",
65
81
  nonce,
66
82
  dangerouslySetInnerHTML: { __html: `(window.__TASTY__=window.__TASTY__||[]).push(${classNames.map((n) => `"${n}"`).join(",")})` }
67
- }));
83
+ });
84
+ return createElement(Fragment, null, linkEl, styleEl, scriptEl);
68
85
  });
69
86
  return createElement(getTastySSRContext().Provider, { value: collector }, children);
70
87
  }
@@ -1 +1 @@
1
- {"version":3,"file":"next.js","names":[],"sources":["../../src/ssr/next.ts"],"sourcesContent":["/**\n * Next.js integration for Tasty SSR.\n *\n * Provides TastyRegistry for App Router (streaming via useServerInsertedHTML).\n *\n * Import from '@tenphi/tasty/ssr/next'.\n */\n\n'use client';\n\n/// <reference path=\"./next-navigation.d.ts\" />\n\nimport { createElement, Fragment, useState, type ReactNode } from 'react';\nimport { useServerInsertedHTML } from 'next/navigation';\n\nimport { getConfig } from '../config';\nimport { ServerStyleCollector } from './collector';\nimport { getTastySSRContext } from './context';\nimport { hydrateTastyClasses } from './hydrate';\nimport { registerSSRCollectorGetter } from './ssr-collector-ref';\n\n// Auto-hydrate on module load (client only).\n// Reads the class name list from `window.__TASTY__` populated by streaming scripts.\nif (typeof window !== 'undefined') {\n hydrateTastyClasses();\n}\n\nexport interface TastyRegistryProps {\n children: ReactNode;\n /**\n * Whether to embed the class-list script for client hydration.\n * Set to false to skip class transfer (e.g. for CSP restrictions).\n * Without it, client components may re-inject CSS that already exists\n * in server-rendered `<style>` tags. Default: true.\n */\n transferCache?: boolean;\n}\n\n/**\n * Next.js App Router registry for Tasty SSR.\n *\n * Wraps the component tree with a ServerStyleCollector and flushes\n * collected CSS into the HTML stream via useServerInsertedHTML.\n *\n * @example\n * ```tsx\n * // app/tasty-registry.tsx\n * 'use client';\n * import { TastyRegistry } from '@tenphi/tasty/ssr/next';\n * export default function TastyStyleRegistry({ children }) {\n * return <TastyRegistry>{children}</TastyRegistry>;\n * }\n *\n * // app/layout.tsx\n * import TastyStyleRegistry from './tasty-registry';\n * export default function RootLayout({ children }) {\n * return <html><body>\n * <TastyStyleRegistry>{children}</TastyStyleRegistry>\n * </body></html>;\n * }\n * ```\n */\nexport function TastyRegistry({\n children,\n transferCache = true,\n}: TastyRegistryProps) {\n const isClient = typeof window !== 'undefined';\n\n const [collector] = useState(() => {\n if (isClient) return null;\n\n const instance = new ServerStyleCollector();\n\n registerSSRCollectorGetter(() => instance);\n\n return instance;\n });\n const nonce = getConfig().nonce;\n\n useServerInsertedHTML(() => {\n if (!collector) return null;\n\n const css = collector.flushCSS();\n const classNames = collector.getRenderedClassNames();\n\n if (!css) return null;\n\n const styleEl = createElement('style', {\n key: 'tasty-ssr-styles',\n 'data-tasty-ssr': '',\n nonce,\n dangerouslySetInnerHTML: { __html: css },\n });\n\n if (!transferCache || classNames.length === 0) return styleEl;\n\n const classListJSON = classNames.map((n) => `\"${n}\"`).join(',');\n\n const scriptEl = createElement('script', {\n key: 'tasty-ssr-cache',\n nonce,\n dangerouslySetInnerHTML: {\n __html: `(window.__TASTY__=window.__TASTY__||[]).push(${classListJSON})`,\n },\n });\n\n return createElement(Fragment, null, styleEl, scriptEl);\n });\n\n return createElement(\n getTastySSRContext().Provider,\n { value: collector },\n children,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,IAAI,OAAO,WAAW,aACpB,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;AAsCtB,SAAgB,cAAc,EAC5B,UACA,gBAAgB,QACK;CACrB,MAAM,WAAW,OAAO,WAAW;CAEnC,MAAM,CAAC,aAAa,eAAe;EACjC,IAAI,UAAU,OAAO;EAErB,MAAM,WAAW,IAAI,qBAAqB;EAE1C,iCAAiC,QAAQ;EAEzC,OAAO;CACT,CAAC;CACD,MAAM,QAAQ,UAAU,CAAC,CAAC;CAE1B,4BAA4B;EAC1B,IAAI,CAAC,WAAW,OAAO;EAEvB,MAAM,MAAM,UAAU,SAAS;EAC/B,MAAM,aAAa,UAAU,sBAAsB;EAEnD,IAAI,CAAC,KAAK,OAAO;EAEjB,MAAM,UAAU,cAAc,SAAS;GACrC,KAAK;GACL,kBAAkB;GAClB;GACA,yBAAyB,EAAE,QAAQ,IAAI;EACzC,CAAC;EAED,IAAI,CAAC,iBAAiB,WAAW,WAAW,GAAG,OAAO;EAYtD,OAAO,cAAc,UAAU,MAAM,SARpB,cAAc,UAAU;GACvC,KAAK;GACL;GACA,yBAAyB,EACvB,QAAQ,gDANU,WAAW,KAAK,MAAM,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,GAMa,EAAE,GACxE;EACF,CAEqD,CAAC;CACxD,CAAC;CAED,OAAO,cACL,mBAAmB,CAAC,CAAC,UACrB,EAAE,OAAO,UAAU,GACnB,QACF;AACF"}
1
+ {"version":3,"file":"next.js","names":[],"sources":["../../src/ssr/next.ts"],"sourcesContent":["/**\n * Next.js integration for Tasty SSR.\n *\n * Provides TastyRegistry for App Router (streaming via useServerInsertedHTML).\n *\n * Import from '@tenphi/tasty/ssr/next'.\n */\n\n'use client';\n\n/// <reference path=\"./next-navigation.d.ts\" />\n\nimport { createElement, Fragment, useState, type ReactNode } from 'react';\nimport { useServerInsertedHTML } from 'next/navigation';\n\nimport { getConfig } from '../config';\nimport { ServerStyleCollector } from './collector';\nimport { getTastySSRContext } from './context';\nimport { hydrateTastyClasses } from './hydrate';\nimport { registerSSRCollectorGetter } from './ssr-collector-ref';\n\n// Auto-hydrate on module load (client only).\n// Reads the class name list from `window.__TASTY__` populated by streaming scripts.\nif (typeof window !== 'undefined') {\n hydrateTastyClasses();\n}\n\nexport interface TastyRegistryProps {\n children: ReactNode;\n /**\n * Whether to embed the class-list script for client hydration.\n * Set to false to skip class transfer (e.g. for CSP restrictions).\n * Without it, client components may re-inject CSS that already exists\n * in server-rendered `<style>` tags. Default: true.\n */\n transferCache?: boolean;\n /**\n * URL of a stylesheet containing Tasty's configured global CSS.\n * `withTastyNext()` sets this automatically. Pass false to disable it for\n * this registry, or a URL to use a manually generated stylesheet.\n */\n sharedStylesheet?: string | false;\n}\n\n/**\n * Next.js App Router registry for Tasty SSR.\n *\n * Wraps the component tree with a ServerStyleCollector and flushes\n * collected CSS into the HTML stream via useServerInsertedHTML.\n *\n * @example\n * ```tsx\n * // app/tasty-registry.tsx\n * 'use client';\n * import { TastyRegistry } from '@tenphi/tasty/ssr/next';\n * export default function TastyStyleRegistry({ children }) {\n * return <TastyRegistry>{children}</TastyRegistry>;\n * }\n *\n * // app/layout.tsx\n * import TastyStyleRegistry from './tasty-registry';\n * export default function RootLayout({ children }) {\n * return <html><body>\n * <TastyStyleRegistry>{children}</TastyStyleRegistry>\n * </body></html>;\n * }\n * ```\n */\nexport function TastyRegistry({\n children,\n transferCache = true,\n sharedStylesheet = process.env.TASTY_NEXT_SHARED_CSS_HREF,\n}: TastyRegistryProps) {\n const isClient = typeof window !== 'undefined';\n\n const [collector] = useState(() => {\n if (isClient) return null;\n\n const instance = new ServerStyleCollector();\n\n registerSSRCollectorGetter(() => instance);\n\n // The generated stylesheet already contains configured global artifacts.\n // Mark that first batch as flushed so only request-specific styles stream.\n if (sharedStylesheet) {\n instance.collectInternals();\n instance.flushCSS();\n }\n\n return instance;\n });\n const [streamState] = useState(() => ({ sharedStylesheetFlushed: false }));\n const nonce = getConfig().nonce;\n\n useServerInsertedHTML(() => {\n if (!collector) return null;\n\n const css = collector.flushCSS();\n const classNames = collector.getRenderedClassNames();\n\n let linkEl = null;\n if (sharedStylesheet && !streamState.sharedStylesheetFlushed) {\n streamState.sharedStylesheetFlushed = true;\n linkEl = createElement('link', {\n key: 'tasty-shared-styles',\n rel: 'stylesheet',\n href: sharedStylesheet,\n 'data-tasty-ssr': '',\n nonce,\n });\n }\n\n if (!css) return linkEl;\n\n const styleEl = createElement('style', {\n key: 'tasty-ssr-styles',\n 'data-tasty-ssr': '',\n nonce,\n dangerouslySetInnerHTML: { __html: css },\n });\n\n if (!transferCache || classNames.length === 0) {\n return linkEl ? createElement(Fragment, null, linkEl, styleEl) : styleEl;\n }\n\n const classListJSON = classNames.map((n) => `\"${n}\"`).join(',');\n\n const scriptEl = createElement('script', {\n key: 'tasty-ssr-cache',\n nonce,\n dangerouslySetInnerHTML: {\n __html: `(window.__TASTY__=window.__TASTY__||[]).push(${classListJSON})`,\n },\n });\n\n return createElement(Fragment, null, linkEl, styleEl, scriptEl);\n });\n\n return createElement(\n getTastySSRContext().Provider,\n { value: collector },\n children,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,IAAI,OAAO,WAAW,aACpB,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;AA4CtB,SAAgB,cAAc,EAC5B,UACA,gBAAgB,MAChB,mBAAmB,QAAQ,IAAI,8BACV;CACrB,MAAM,WAAW,OAAO,WAAW;CAEnC,MAAM,CAAC,aAAa,eAAe;EACjC,IAAI,UAAU,OAAO;EAErB,MAAM,WAAW,IAAI,qBAAqB;EAE1C,iCAAiC,QAAQ;EAIzC,IAAI,kBAAkB;GACpB,SAAS,iBAAiB;GAC1B,SAAS,SAAS;EACpB;EAEA,OAAO;CACT,CAAC;CACD,MAAM,CAAC,eAAe,gBAAgB,EAAE,yBAAyB,MAAM,EAAE;CACzE,MAAM,QAAQ,UAAU,CAAC,CAAC;CAE1B,4BAA4B;EAC1B,IAAI,CAAC,WAAW,OAAO;EAEvB,MAAM,MAAM,UAAU,SAAS;EAC/B,MAAM,aAAa,UAAU,sBAAsB;EAEnD,IAAI,SAAS;EACb,IAAI,oBAAoB,CAAC,YAAY,yBAAyB;GAC5D,YAAY,0BAA0B;GACtC,SAAS,cAAc,QAAQ;IAC7B,KAAK;IACL,KAAK;IACL,MAAM;IACN,kBAAkB;IAClB;GACF,CAAC;EACH;EAEA,IAAI,CAAC,KAAK,OAAO;EAEjB,MAAM,UAAU,cAAc,SAAS;GACrC,KAAK;GACL,kBAAkB;GAClB;GACA,yBAAyB,EAAE,QAAQ,IAAI;EACzC,CAAC;EAED,IAAI,CAAC,iBAAiB,WAAW,WAAW,GAC1C,OAAO,SAAS,cAAc,UAAU,MAAM,QAAQ,OAAO,IAAI;EAKnE,MAAM,WAAW,cAAc,UAAU;GACvC,KAAK;GACL;GACA,yBAAyB,EACvB,QAAQ,gDANU,WAAW,KAAK,MAAM,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,GAMa,EAAE,GACxE;EACF,CAAC;EAED,OAAO,cAAc,UAAU,MAAM,QAAQ,SAAS,QAAQ;CAChE,CAAC;CAED,OAAO,cACL,mBAAmB,CAAC,CAAC,UACrB,EAAE,OAAO,UAAU,GACnB,QACF;AACF"}
@@ -0,0 +1,29 @@
1
+ //#region src/ssr/ssr-collector-ref.ts
2
+ const GETTER_KEY = "__tasty_ssr_collector_getter__";
3
+ let _getSSRCollector = null;
4
+ /**
5
+ * Register the collector getter in the current module graph only.
6
+ * Used by Next.js TastyRegistry.
7
+ */
8
+ function registerSSRCollectorGetter(fn) {
9
+ _getSSRCollector = fn;
10
+ }
11
+ /**
12
+ * Register the collector getter on globalThis so it is visible across
13
+ * separate module graphs (e.g. Astro middleware ↔ page components).
14
+ */
15
+ function registerSSRCollectorGetterGlobal(fn) {
16
+ globalThis[GETTER_KEY] = fn;
17
+ }
18
+ /**
19
+ * Retrieve the SSR collector: module-level first, globalThis fallback.
20
+ */
21
+ function getRegisteredSSRCollector() {
22
+ if (_getSSRCollector) return _getSSRCollector();
23
+ const getter = globalThis[GETTER_KEY];
24
+ return getter ? getter() : null;
25
+ }
26
+ //#endregion
27
+ export { registerSSRCollectorGetter as n, registerSSRCollectorGetterGlobal as r, getRegisteredSSRCollector as t };
28
+
29
+ //# sourceMappingURL=ssr-collector-ref-COs_ioWl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssr-collector-ref-COs_ioWl.js","names":[],"sources":["../src/ssr/ssr-collector-ref.ts"],"sourcesContent":["/**\n * Global reference to the SSR collector getter function.\n *\n * This indirection avoids importing 'node:async_hooks' in the browser bundle.\n * The SSR entry point sets this ref when loaded on the server. The useStyles\n * hook calls it if set; on the client it stays null and is never called.\n *\n * Uses a module-level variable as the primary mechanism. In Next.js App\n * Router the RSC and SSR module graphs load separate copies of this module,\n * so the getter registered by TastyRegistry (SSR layer) is invisible to\n * server components (RSC layer) — which correctly fall through to inline\n * RSC styles.\n *\n * A globalThis fallback (`registerSSRCollectorGetterGlobal`) is provided\n * for frameworks like Astro where middleware and page components live in\n * different module graphs and must share the getter across them.\n */\n\nimport type { ServerStyleCollector } from './collector';\n\ntype SSRCollectorGetter = () => ServerStyleCollector | null;\n\nconst GETTER_KEY = '__tasty_ssr_collector_getter__';\n\nlet _getSSRCollector: SSRCollectorGetter | null = null;\n\n/**\n * Register the collector getter in the current module graph only.\n * Used by Next.js TastyRegistry.\n */\nexport function registerSSRCollectorGetter(fn: SSRCollectorGetter): void {\n _getSSRCollector = fn;\n}\n\n/**\n * Register the collector getter on globalThis so it is visible across\n * separate module graphs (e.g. Astro middleware ↔ page components).\n */\nexport function registerSSRCollectorGetterGlobal(fn: SSRCollectorGetter): void {\n (globalThis as Record<string, unknown>)[GETTER_KEY] = fn;\n}\n\n/**\n * Retrieve the SSR collector: module-level first, globalThis fallback.\n */\nexport function getRegisteredSSRCollector(): ServerStyleCollector | null {\n if (_getSSRCollector) return _getSSRCollector();\n const getter = (globalThis as Record<string, unknown>)[GETTER_KEY] as\n SSRCollectorGetter | undefined;\n return getter ? getter() : null;\n}\n"],"mappings":";AAsBA,MAAM,aAAa;AAEnB,IAAI,mBAA8C;;;;;AAMlD,SAAgB,2BAA2B,IAA8B;CACvE,mBAAmB;AACrB;;;;;AAMA,SAAgB,iCAAiC,IAA8B;CAC7E,WAAwC,cAAc;AACxD;;;;AAKA,SAAgB,4BAAyD;CACvE,IAAI,kBAAkB,OAAO,iBAAiB;CAC9C,MAAM,SAAU,WAAuC;CAEvD,OAAO,SAAS,OAAO,IAAI;AAC7B"}
@@ -1,5 +1,5 @@
1
- import { b as Styles } from "../index-B3o0aCYV.js";
2
- import { t as mergeStyles } from "../merge-styles-DJTSfz_M.js";
1
+ import { b as Styles } from "../index-C8RFYeFW.js";
2
+ import { t as mergeStyles } from "../merge-styles-BQv7d3fx.js";
3
3
 
4
4
  //#region src/static/types.d.ts
5
5
  /**
@@ -1,4 +1,4 @@
1
- import { t as mergeStyles } from "../merge-styles-C-uwpoNW.js";
1
+ import { t as mergeStyles } from "../merge-styles-BbJhjesV.js";
2
2
  //#region src/static/types.ts
3
3
  /**
4
4
  * Create a StaticStyle object.