@tenphi/tasty 3.9.8 → 3.9.10
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.
- package/dist/{babel-C5mN2_fA.d.ts → babel-rZcEwPLM.d.ts} +2 -3
- package/dist/chunks/{build-config-iyzPTrZa.js → build-config-CL4eRu2z.js} +6 -6
- package/dist/chunks/{build-config-iyzPTrZa.js.map → build-config-CL4eRu2z.js.map} +1 -1
- package/dist/chunks/{collector-C4ouIOgI.js → collector-D2ARGT2L.js} +4 -4
- package/dist/chunks/{collector-C4ouIOgI.js.map → collector-D2ARGT2L.js.map} +1 -1
- package/dist/chunks/{config-engine-BAldIMv7.js → config-engine-DEmmPPdp.js} +17 -12
- package/dist/chunks/{config-engine-BAldIMv7.js.map → config-engine-DEmmPPdp.js.map} +1 -1
- package/dist/chunks/{css-definitions-BIgGXRLz.js → css-definitions-DotDkIXt.js} +6 -5
- package/dist/chunks/{css-definitions-BIgGXRLz.js.map → css-definitions-DotDkIXt.js.map} +1 -1
- package/dist/chunks/{css-resources-BN8apgxt.js → css-resources-P7IBUUZs.js} +2 -2
- package/dist/chunks/{css-resources-BN8apgxt.js.map → css-resources-P7IBUUZs.js.map} +1 -1
- package/dist/chunks/{debug-CUDFFYpM.js → debug-D8pg9RGI.js} +20 -19
- package/dist/chunks/{debug-CUDFFYpM.js.map → debug-D8pg9RGI.js.map} +1 -1
- package/dist/chunks/{dsl-C5yuAn41.js → dsl-DRhFWQzo.js} +42 -37
- package/dist/chunks/{dsl-C5yuAn41.js.map → dsl-DRhFWQzo.js.map} +1 -1
- package/dist/chunks/{react-runtime-46TyXx9v.js → react-runtime-BpxlOTbO.js} +28 -23
- package/dist/chunks/{react-runtime-46TyXx9v.js.map → react-runtime-BpxlOTbO.js.map} +1 -1
- package/dist/chunks/{runtime-engine-B_4lx2DJ.js → runtime-engine-CKFXUH-A.js} +27 -19
- package/dist/chunks/runtime-engine-CKFXUH-A.js.map +1 -0
- package/dist/chunks/{runtime-state-BMtykrat.js → runtime-state-BxaLhVdP.js} +2 -2
- package/dist/chunks/{runtime-state-BMtykrat.js.map → runtime-state-BxaLhVdP.js.map} +1 -1
- package/dist/chunks/{shared-utils-DWA4LjIa.js → shared-utils-y-HjvPN4.js} +16 -12
- package/dist/chunks/{shared-utils-DWA4LjIa.js.map → shared-utils-y-HjvPN4.js.map} +1 -1
- package/dist/chunks/{style-engine-BpgmapBp.js → style-engine-BBbBuSkT.js} +87 -75
- package/dist/chunks/{style-engine-BpgmapBp.js.map → style-engine-BBbBuSkT.js.map} +1 -1
- package/dist/chunks/{zero-engine-DcjMs3WX.js → zero-engine-gJrKBRiw.js} +6 -4
- package/dist/chunks/{zero-engine-DcjMs3WX.js.map → zero-engine-gJrKBRiw.js.map} +1 -1
- package/dist/{collector-CViSMO84.d.ts → collector-w4mBj5gd.d.ts} +2 -3
- package/dist/{config-CbDtZzZy.d.ts → config-CZWCzBr6.d.ts} +3 -12
- package/dist/core/index.d.ts +4 -4
- package/dist/core/index.js +8 -8
- package/dist/{index-lhkF3ln5.d.ts → index-G9JuwM9p.d.ts} +136 -163
- package/dist/index.d.ts +4 -4
- package/dist/index.js +9 -9
- package/dist/{merge-styles-Dp3eKkK9.d.ts → merge-styles-VXwJ0Frr.d.ts} +2 -3
- package/dist/ssr/astro-client.d.ts +1 -1
- package/dist/ssr/astro-middleware-extract-static.d.ts +1 -2
- package/dist/ssr/astro-middleware-extract.d.ts +1 -2
- package/dist/ssr/astro-middleware-static.d.ts +1 -2
- package/dist/ssr/astro-middleware.d.ts +1 -2
- package/dist/ssr/astro.d.ts +8 -16
- package/dist/ssr/astro.js +5 -4
- package/dist/ssr/astro.js.map +1 -1
- package/dist/ssr/index.d.ts +5 -6
- package/dist/ssr/index.js +2 -2
- package/dist/ssr/next-config.d.ts +3 -5
- package/dist/ssr/next-config.js +10 -6
- package/dist/ssr/next-config.js.map +1 -1
- package/dist/ssr/next.d.ts +3 -9
- package/dist/ssr/next.js +5 -4
- package/dist/ssr/next.js.map +1 -1
- package/dist/static/index.d.ts +8 -9
- package/dist/static/index.js +4 -4
- package/dist/static/index.js.map +1 -1
- package/dist/static/inject.d.ts +1 -2
- package/dist/{types-Ji9PGExW.d.ts → types-JEY8PVYP.d.ts} +5 -58
- package/dist/zero/babel.d.ts +1 -1
- package/dist/zero/babel.js +23 -18
- package/dist/zero/babel.js.map +1 -1
- package/dist/zero/index.d.ts +6 -7
- package/dist/zero/index.js +1 -1
- package/dist/zero/next.d.ts +3 -5
- package/dist/zero/next.js.map +1 -1
- package/package.json +31 -31
- package/dist/chunks/runtime-engine-B_4lx2DJ.js.map +0 -1
|
@@ -3,9 +3,8 @@
|
|
|
3
3
|
* Prerender-extraction middleware entrypoint for sites without islands.
|
|
4
4
|
* Exported only so Astro can resolve it through the package exports map.
|
|
5
5
|
*/
|
|
6
|
-
declare const onRequest: (context: {
|
|
6
|
+
export declare const onRequest: (context: {
|
|
7
7
|
isPrerendered?: boolean;
|
|
8
8
|
}, next: () => Promise<Response>) => Promise<Response>;
|
|
9
9
|
//#endregion
|
|
10
|
-
export { onRequest };
|
|
11
10
|
//# sourceMappingURL=astro-middleware-extract-static.d.ts.map
|
|
@@ -3,9 +3,8 @@
|
|
|
3
3
|
* Prerender-extraction middleware entrypoint with island cache transfer.
|
|
4
4
|
* Exported only so Astro can resolve it through the package exports map.
|
|
5
5
|
*/
|
|
6
|
-
declare const onRequest: (context: {
|
|
6
|
+
export declare const onRequest: (context: {
|
|
7
7
|
isPrerendered?: boolean;
|
|
8
8
|
}, next: () => Promise<Response>) => Promise<Response>;
|
|
9
9
|
//#endregion
|
|
10
|
-
export { onRequest };
|
|
11
10
|
//# sourceMappingURL=astro-middleware-extract.d.ts.map
|
|
@@ -10,9 +10,8 @@
|
|
|
10
10
|
* Identical to `./astro-middleware` except that no class-list `<script>` is
|
|
11
11
|
* emitted, so a site without `client:*` islands ships zero client JavaScript.
|
|
12
12
|
*/
|
|
13
|
-
declare const onRequest: (context: {
|
|
13
|
+
export declare const onRequest: (context: {
|
|
14
14
|
isPrerendered?: boolean;
|
|
15
15
|
}, next: () => Promise<Response>) => Promise<Response>;
|
|
16
16
|
//#endregion
|
|
17
|
-
export { onRequest };
|
|
18
17
|
//# sourceMappingURL=astro-middleware-static.d.ts.map
|
|
@@ -11,9 +11,8 @@
|
|
|
11
11
|
* `./astro-middleware-static` for the variant used by
|
|
12
12
|
* `tastyIntegration({ islands: false })`.
|
|
13
13
|
*/
|
|
14
|
-
declare const onRequest: (context: {
|
|
14
|
+
export declare const onRequest: (context: {
|
|
15
15
|
isPrerendered?: boolean;
|
|
16
16
|
}, next: () => Promise<Response>) => Promise<Response>;
|
|
17
17
|
//#endregion
|
|
18
|
-
export { onRequest };
|
|
19
18
|
//# sourceMappingURL=astro-middleware.d.ts.map
|
package/dist/ssr/astro.d.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* Import from '@tenphi/tasty/ssr/astro'.
|
|
10
10
|
*/
|
|
11
|
-
interface TastyMiddlewareOptions {
|
|
11
|
+
export interface TastyMiddlewareOptions {
|
|
12
12
|
/**
|
|
13
13
|
* Whether to embed the class-list script for client hydration.
|
|
14
14
|
* Set to false to skip class transfer (e.g. for CSP restrictions).
|
|
@@ -43,10 +43,10 @@ interface TastyMiddlewareOptions {
|
|
|
43
43
|
* );
|
|
44
44
|
* ```
|
|
45
45
|
*/
|
|
46
|
-
declare function tastyMiddleware(options?: TastyMiddlewareOptions): (context: {
|
|
46
|
+
export declare function tastyMiddleware(options?: TastyMiddlewareOptions): (context: {
|
|
47
47
|
isPrerendered?: boolean;
|
|
48
48
|
}, next: () => Promise<Response>) => Promise<Response>;
|
|
49
|
-
interface TastyIntegrationCSSOptions {
|
|
49
|
+
export interface TastyIntegrationCSSOptions {
|
|
50
50
|
/**
|
|
51
51
|
* CSS delivery mode. Extraction only applies to prerendered builds.
|
|
52
52
|
* Extracted CSS preserves resource URLs verbatim, so use absolute URLs or
|
|
@@ -56,7 +56,7 @@ interface TastyIntegrationCSSOptions {
|
|
|
56
56
|
*/
|
|
57
57
|
mode?: 'inline' | 'extract';
|
|
58
58
|
}
|
|
59
|
-
interface TastyIntegrationOptions {
|
|
59
|
+
export interface TastyIntegrationOptions {
|
|
60
60
|
/**
|
|
61
61
|
* Enable island hydration support.
|
|
62
62
|
*
|
|
@@ -98,22 +98,17 @@ interface TastyIntegrationOptions {
|
|
|
98
98
|
* });
|
|
99
99
|
* ```
|
|
100
100
|
*/
|
|
101
|
-
declare function tastyIntegration(options?: TastyIntegrationOptions): {
|
|
101
|
+
export declare function tastyIntegration(options?: TastyIntegrationOptions): {
|
|
102
102
|
name: string;
|
|
103
103
|
hooks: {
|
|
104
|
-
'astro:config:setup': ({
|
|
105
|
-
addMiddleware,
|
|
106
|
-
injectScript
|
|
107
|
-
}: {
|
|
104
|
+
'astro:config:setup': ({ addMiddleware, injectScript }: {
|
|
108
105
|
addMiddleware: (middleware: {
|
|
109
106
|
entrypoint: string | URL;
|
|
110
107
|
order: "pre" | "post";
|
|
111
108
|
}) => void;
|
|
112
109
|
injectScript: (stage: "head-inline" | "before-hydration" | "page" | "page-ssr", content: string) => void;
|
|
113
110
|
}) => void;
|
|
114
|
-
'astro:config:done': ({
|
|
115
|
-
config
|
|
116
|
-
}: {
|
|
111
|
+
'astro:config:done': ({ config }: {
|
|
117
112
|
config: {
|
|
118
113
|
base?: string;
|
|
119
114
|
site?: URL;
|
|
@@ -123,13 +118,10 @@ declare function tastyIntegration(options?: TastyIntegrationOptions): {
|
|
|
123
118
|
};
|
|
124
119
|
};
|
|
125
120
|
}) => void;
|
|
126
|
-
'astro:build:done': ({
|
|
127
|
-
dir
|
|
128
|
-
}: {
|
|
121
|
+
'astro:build:done': ({ dir }: {
|
|
129
122
|
dir: URL;
|
|
130
123
|
}) => Promise<void>;
|
|
131
124
|
};
|
|
132
125
|
};
|
|
133
126
|
//#endregion
|
|
134
|
-
export { TastyIntegrationCSSOptions, TastyIntegrationOptions, TastyMiddlewareOptions, tastyIntegration, tastyMiddleware };
|
|
135
127
|
//# sourceMappingURL=astro.d.ts.map
|
package/dist/ssr/astro.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { r as registerSSRCollectorGetterGlobal, u as getRuntimeConfigState } from "../chunks/runtime-state-
|
|
2
|
-
import { t as ServerStyleCollector } from "../chunks/collector-
|
|
1
|
+
import { r as registerSSRCollectorGetterGlobal, u as getRuntimeConfigState } from "../chunks/runtime-state-BxaLhVdP.js";
|
|
2
|
+
import { t as ServerStyleCollector } from "../chunks/collector-D2ARGT2L.js";
|
|
3
3
|
import { n as runWithCollector, t as getSSRCollector } from "../chunks/async-storage-CG5HnUT5.js";
|
|
4
|
-
import { t as findUnsafeCSSResource } from "../chunks/css-resources-
|
|
4
|
+
import { t as findUnsafeCSSResource } from "../chunks/css-resources-P7IBUUZs.js";
|
|
5
5
|
import { createHash } from "node:crypto";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
|
@@ -10,7 +10,8 @@ import { fileURLToPath } from "node:url";
|
|
|
10
10
|
const METADATA_START = "<template data-tasty-extract>";
|
|
11
11
|
const METADATA_END = "</template>";
|
|
12
12
|
function createExtractionMetadata(artifacts) {
|
|
13
|
-
|
|
13
|
+
const encoded = Buffer.from(JSON.stringify(artifacts), "utf8").toString("base64");
|
|
14
|
+
return `${METADATA_START}${encoded}${METADATA_END}`;
|
|
14
15
|
}
|
|
15
16
|
function parseExtractablePage(path, html) {
|
|
16
17
|
const metadataStart = html.indexOf(METADATA_START);
|
package/dist/ssr/astro.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"astro.js","names":[],"sources":["../../src/ssr/astro-extraction.ts","../../src/ssr/astro.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { readdir, readFile, writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { ServerStyleArtifact } from './collector';\nimport { findUnsafeCSSResource } from './css-resources';\n\nconst METADATA_START = '<template data-tasty-extract>';\nconst METADATA_END = '</template>';\n\ninterface ExtractablePage {\n path: string;\n html: string;\n artifacts: ServerStyleArtifact[];\n styleStart: number;\n replacementEnd: number;\n styleOpen: string;\n}\n\nexport function createExtractionMetadata(\n artifacts: ServerStyleArtifact[],\n): string {\n const encoded = Buffer.from(JSON.stringify(artifacts), 'utf8').toString(\n 'base64',\n );\n return `${METADATA_START}${encoded}${METADATA_END}`;\n}\n\nfunction parseExtractablePage(\n path: string,\n html: string,\n): ExtractablePage | null {\n const metadataStart = html.indexOf(METADATA_START);\n if (metadataStart === -1) return null;\n\n const metadataContentStart = metadataStart + METADATA_START.length;\n const metadataEnd = html.indexOf(METADATA_END, metadataContentStart);\n if (metadataEnd === -1) return null;\n\n const encoded = html.slice(metadataContentStart, metadataEnd);\n let artifacts: ServerStyleArtifact[];\n try {\n artifacts = JSON.parse(\n Buffer.from(encoded, 'base64').toString('utf8'),\n ) as ServerStyleArtifact[];\n } catch {\n return null;\n }\n\n const styleStart = html.lastIndexOf('<style data-tasty-ssr', metadataStart);\n if (styleStart === -1) return null;\n const styleOpenEnd = html.indexOf('>', styleStart);\n const styleEnd = html.indexOf('</style>', styleOpenEnd + 1);\n if (\n styleOpenEnd === -1 ||\n styleEnd === -1 ||\n styleEnd + '</style>'.length !== metadataStart\n ) {\n return null;\n }\n\n return {\n path,\n html,\n artifacts,\n styleStart,\n replacementEnd: metadataEnd + METADATA_END.length,\n styleOpen: html.slice(styleStart, styleOpenEnd + 1),\n };\n}\n\nasync function findHTMLFiles(dir: string): Promise<string[]> {\n const paths: string[] = [];\n const entries = await readdir(dir, { withFileTypes: true });\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n paths.push(...(await findHTMLFiles(path)));\n } else if (entry.isFile() && entry.name.endsWith('.html')) {\n paths.push(path);\n }\n }\n return paths;\n}\n\nfunction crossOriginAssetsPrefix(\n assetsPrefix?: string | Record<string, string>,\n site?: URL,\n): string | null {\n if (!assetsPrefix) return null;\n const prefix =\n typeof assetsPrefix === 'string'\n ? assetsPrefix\n : assetsPrefix.css || assetsPrefix.fallback;\n if (!/^(?:[a-z][a-z\\d+.-]*:|\\/\\/)/i.test(prefix)) return null;\n if (!site) return prefix;\n\n try {\n const prefixURL = prefix.startsWith('//')\n ? new URL(`${site.protocol}${prefix}`)\n : new URL(prefix);\n return prefixURL.origin === site.origin ? null : prefix;\n } catch {\n return prefix;\n }\n}\n\nfunction validateExtractedURLs(\n pages: ExtractablePage[],\n assetsPrefix?: string | Record<string, string>,\n site?: URL,\n): void {\n const externalPrefix = crossOriginAssetsPrefix(assetsPrefix, site);\n for (const page of pages) {\n for (const artifact of page.artifacts) {\n const unsafe = findUnsafeCSSResource(\n artifact.css,\n externalPrefix !== null,\n );\n if (unsafe) {\n const reason = unsafe.rootRelative\n ? `root-relative CSS URL \"${unsafe.url}\" would resolve against the external assetsPrefix \"${externalPrefix}\" instead of the page origin`\n : `page-relative CSS URL \"${unsafe.url}\" cannot preserve its target`;\n throw new Error(\n `[Tasty] Astro CSS extraction cannot preserve ${reason} in ${page.path} (${artifact.kind} artifact ${artifact.id}). Use an absolute URL or a data URL${externalPrefix ? '' : ', or a root-relative URL such as url(/path/to/asset)'}.`,\n );\n }\n }\n }\n}\n\n/** Find artifacts emitted by every styled page, in the first page's order. */\nfunction selectSharedArtifacts(\n pages: ExtractablePage[],\n): ServerStyleArtifact[] {\n if (pages.length < 2) return [];\n\n const source = pages[0].artifacts;\n const otherIds = pages\n .slice(1)\n .map((page) => new Set(page.artifacts.map(({ id }) => id)));\n\n return source.filter(({ id }) => otherIds.every((ids) => ids.has(id)));\n}\n\nfunction stylesheetHref(\n base: string,\n assets: string,\n filename: string,\n assetsPrefix?: string | Record<string, string>,\n): string {\n const assetsPath = assets.replace(/^\\/+|\\/+$/g, '');\n if (assetsPrefix) {\n const prefix =\n typeof assetsPrefix === 'string'\n ? assetsPrefix\n : assetsPrefix.css || assetsPrefix.fallback;\n return `${prefix.replace(/\\/+$/g, '')}/${assetsPath}/${filename}`;\n }\n\n const basePath = base === '/' ? '' : `/${base.replace(/^\\/+|\\/+$/g, '')}`;\n return `${basePath}/${assetsPath}/${filename}`;\n}\n\nfunction stylesheetLink(page: ExtractablePage, href: string): string {\n const nonceAttr = page.styleOpen.match(/\\snonce=\"[^\"]*\"/)?.[0] ?? '';\n return `<link rel=\"stylesheet\" href=\"${href}\" data-tasty-ssr${nonceAttr}>`;\n}\n\nfunction transformPage(page: ExtractablePage, hrefs: string[]): string {\n const replacement = hrefs.map((href) => stylesheetLink(page, href)).join('');\n\n return (\n page.html.slice(0, page.styleStart) +\n replacement +\n page.html.slice(page.replacementEnd)\n );\n}\n\nasync function writeStylesheet(\n assetDir: string,\n scope: 'shared' | 'page',\n artifacts: ServerStyleArtifact[],\n): Promise<string | null> {\n if (artifacts.length === 0) return null;\n\n const css = artifacts.map(({ css }) => css).join('\\n');\n const hash = createHash('sha256').update(css).digest('hex').slice(0, 12);\n const filename = `tasty.${scope}.${hash}.css`;\n await writeFile(join(assetDir, filename), css);\n return filename;\n}\n\nexport async function extractAstroCSS(options: {\n dir: URL;\n base: string;\n assets: string;\n assetsPrefix?: string | Record<string, string>;\n site?: URL;\n}): Promise<void> {\n const outputDir = fileURLToPath(options.dir);\n const paths = await findHTMLFiles(outputDir);\n const pages = (\n await Promise.all(\n paths.map(async (path) =>\n parseExtractablePage(path, await readFile(path, 'utf8')),\n ),\n )\n ).filter((page): page is ExtractablePage => page !== null);\n if (pages.length === 0) return;\n validateExtractedURLs(pages, options.assetsPrefix, options.site);\n\n const shared = selectSharedArtifacts(pages);\n const assetDir = join(outputDir, options.assets);\n await mkdir(assetDir, { recursive: true });\n const sharedFilename = await writeStylesheet(assetDir, 'shared', shared);\n const sharedHref = sharedFilename\n ? stylesheetHref(\n options.base,\n options.assets,\n sharedFilename,\n options.assetsPrefix,\n )\n : null;\n const sharedIds = new Set(shared.map(({ id }) => id));\n\n for (const page of pages) {\n const remainder = page.artifacts.filter(({ id }) => !sharedIds.has(id));\n const pageFilename = await writeStylesheet(assetDir, 'page', remainder);\n const hrefs = sharedHref ? [sharedHref] : [];\n if (pageFilename) {\n hrefs.push(\n stylesheetHref(\n options.base,\n options.assets,\n pageFilename,\n options.assetsPrefix,\n ),\n );\n }\n await writeFile(page.path, transformPage(page, hrefs));\n }\n}\n","/**\n * Astro integration for Tasty SSR.\n *\n * Provides:\n * - tastyIntegration() — Astro Integration API (recommended)\n * - tastyMiddleware() — manual middleware for advanced composition\n *\n * Import from '@tenphi/tasty/ssr/astro'.\n */\n\nimport { getRuntimeConfigState } from '../config-resources';\nimport { getSSRCollector, runWithCollector } from './async-storage';\nimport { createExtractionMetadata, extractAstroCSS } from './astro-extraction';\nimport { ServerStyleCollector } from './collector';\nimport { registerSSRCollectorGetterGlobal } from './ssr-collector-ref';\n\n// Wire up ALS-based collector discovery so computeStyles() can find\n// the collector set by tastyMiddleware's runWithCollector().\n// Uses globalThis so the getter is visible across Astro's separate\n// module graphs (middleware vs page components).\nregisterSSRCollectorGetterGlobal(getSSRCollector);\n\nexport interface TastyMiddlewareOptions {\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\ninterface InternalTastyMiddlewareOptions extends TastyMiddlewareOptions {\n extractionMetadata?: boolean;\n}\n\n/**\n * Create an Astro middleware that collects Tasty styles during SSR.\n *\n * All React components rendered during the request will have their\n * computeStyles() calls captured by the collector via AsyncLocalStorage.\n * After rendering, the middleware injects the collected CSS into </head>.\n *\n * @example Manual middleware setup\n * ```ts\n * // src/middleware.ts\n * import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';\n * export const onRequest = tastyMiddleware();\n * ```\n *\n * @example Composing with other middleware\n * ```ts\n * // src/middleware.ts\n * import { sequence } from 'astro:middleware';\n * import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';\n *\n * export const onRequest = sequence(\n * tastyMiddleware(),\n * myOtherMiddleware,\n * );\n * ```\n */\nexport function tastyMiddleware(options?: TastyMiddlewareOptions) {\n const internalOptions = options as InternalTastyMiddlewareOptions | undefined;\n return async (\n context: { isPrerendered?: boolean },\n next: () => Promise<Response>,\n ): Promise<Response> => {\n const transferCache = options?.transferCache ?? true;\n const extractionMetadata =\n internalOptions?.extractionMetadata === true &&\n context.isPrerendered === true;\n const collector = new ServerStyleCollector();\n\n // Run the entire request — including body stream consumption — inside\n // the ALS context so that components rendering lazily during stream\n // reads can still find the collector via getSSRCollector().\n type Rendered =\n | { response: Response }\n | { html: string | null; status: number; headers: Headers };\n\n const rendered = await runWithCollector<Promise<Rendered>>(\n collector,\n async (): Promise<Rendered> => {\n const response = await next();\n const body = response.body;\n\n // Only process HTML responses. Reading a non-HTML body (e.g. an\n // image, font, or JSON endpoint) as UTF-8 text corrupts binary\n // payloads: every byte >= 0x80 is decoded to U+FFFD and re-encoded\n // as EF BF BD. Pass anything that isn't HTML straight through.\n const contentType = response.headers.get('content-type') ?? '';\n if (!body || !contentType.includes('text/html')) {\n return { response };\n }\n\n const reader = body.pipeThrough(new TextDecoderStream()).getReader();\n const parts: string[] = [];\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n parts.push(value);\n }\n return {\n html: parts.join(''),\n status: response.status,\n headers: response.headers,\n };\n },\n );\n\n // Non-HTML responses are returned untouched to avoid corrupting\n // binary payloads.\n if ('response' in rendered) {\n return rendered.response;\n }\n\n if (!rendered.html) {\n return new Response(null, {\n status: rendered.status,\n headers: rendered.headers,\n });\n }\n\n let { html } = rendered;\n\n const css = collector.getCSS();\n if (!css) {\n return new Response(html, {\n status: rendered.status,\n headers: rendered.headers,\n });\n }\n\n const nonce = getRuntimeConfigState()?.nonce;\n const nonceAttr = nonce ? ` nonce=\"${nonce}\"` : '';\n const styleTag = `<style data-tasty-ssr${nonceAttr}>${css}</style>`;\n const metadataTag = extractionMetadata\n ? createExtractionMetadata(collector.getArtifacts())\n : '';\n\n let cacheTag = '';\n if (transferCache) {\n const classNames = collector.getRenderedClassNames();\n if (classNames.length > 0) {\n const classListJSON = classNames.map((n) => `\"${n}\"`).join(',');\n cacheTag = `<script${nonceAttr}>(window.__TASTY__=window.__TASTY__||[]).push(${classListJSON})</script>`;\n }\n }\n\n const injection = styleTag + metadataTag + cacheTag;\n const idx = html.indexOf('</head>');\n if (idx !== -1) {\n html = html.slice(0, idx) + injection + html.slice(idx);\n } else {\n html = injection + html;\n }\n\n const headers = new Headers(rendered.headers);\n headers.delete('content-length');\n\n return new Response(html, {\n status: rendered.status,\n headers,\n });\n };\n}\n\n// ============================================================================\n// Astro Integration API\n// ============================================================================\n\n/**\n * Package subpaths of the middleware entrypoints registered by\n * `tastyIntegration()`.\n *\n * These must be bare specifiers rather than\n * `new URL('./astro-middleware.js', import.meta.url)`. The bundler is free to\n * hoist `tastyIntegration` into a shared chunk at a different directory depth\n * than `dist/ssr/`, which makes a relative URL resolve to a file that does not\n * exist and breaks the build for every consumer. A package subpath is resolved\n * by the consumer through our `exports` map, so it never depends on the\n * chunk layout.\n *\n * There are separate entrypoints instead of one parameterised entrypoint because\n * `addMiddleware()` cannot pass options: the integration runs when the Astro\n * config is loaded, while the middleware module is evaluated in the server\n * runtime — a different process for built output — so module-level state set\n * by the integration is not visible to the middleware.\n */\nconst MIDDLEWARE_ENTRYPOINT = '@tenphi/tasty/ssr/astro-middleware';\nconst MIDDLEWARE_ENTRYPOINT_STATIC =\n '@tenphi/tasty/ssr/astro-middleware-static';\nconst MIDDLEWARE_ENTRYPOINT_EXTRACT =\n '@tenphi/tasty/ssr/astro-middleware-extract';\nconst MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC =\n '@tenphi/tasty/ssr/astro-middleware-extract-static';\n\nexport interface TastyIntegrationCSSOptions {\n /**\n * CSS delivery mode. Extraction only applies to prerendered builds.\n * Extracted CSS preserves resource URLs verbatim, so use absolute URLs or\n * data URLs. Root-relative URLs are also supported unless `assetsPrefix`\n * sends CSS to an external origin. The build rejects resource URLs whose\n * targets would change after extraction.\n */\n mode?: 'inline' | 'extract';\n}\n\nexport interface TastyIntegrationOptions {\n /**\n * Enable island hydration support.\n *\n * When `true` (default): injects a client hydration script via\n * `injectScript('before-hydration')` and sets `transferCache: true`\n * on the middleware. Islands skip the style pipeline during hydration.\n *\n * When `false`: no client JS is shipped and `transferCache` is set\n * to `false`. Use this for fully static sites without `client:*`\n * directives.\n */\n islands?: boolean;\n /** Configure inline or build-wide extracted CSS delivery. */\n css?: TastyIntegrationCSSOptions;\n}\n\n/**\n * Astro integration that automatically sets up Tasty SSR.\n *\n * Registers middleware for cross-component CSS deduplication and\n * optionally injects a client hydration script for island support.\n *\n * @example Basic setup (with islands)\n * ```ts\n * // astro.config.mjs\n * import { tastyIntegration } from '@tenphi/tasty/ssr/astro';\n *\n * export default defineConfig({\n * integrations: [tastyIntegration()],\n * });\n * ```\n *\n * @example Static-only (no client JS)\n * ```ts\n * // astro.config.mjs\n * import { tastyIntegration } from '@tenphi/tasty/ssr/astro';\n *\n * export default defineConfig({\n * integrations: [tastyIntegration({ islands: false })],\n * });\n * ```\n */\nexport function tastyIntegration(options?: TastyIntegrationOptions) {\n const { islands = true } = options ?? {};\n const cssMode = options?.css?.mode ?? 'inline';\n let base = '/';\n let assets = '_astro';\n let assetsPrefix: string | Record<string, string> | undefined;\n let site: URL | undefined;\n\n return {\n name: '@tenphi/tasty',\n hooks: {\n 'astro:config:setup': ({\n addMiddleware,\n injectScript,\n }: {\n addMiddleware: (middleware: {\n entrypoint: string | URL;\n order: 'pre' | 'post';\n }) => void;\n injectScript: (\n stage: 'head-inline' | 'before-hydration' | 'page' | 'page-ssr',\n content: string,\n ) => void;\n }) => {\n addMiddleware({\n entrypoint:\n cssMode === 'extract'\n ? islands\n ? MIDDLEWARE_ENTRYPOINT_EXTRACT\n : MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC\n : islands\n ? MIDDLEWARE_ENTRYPOINT\n : MIDDLEWARE_ENTRYPOINT_STATIC,\n order: 'pre',\n });\n\n if (islands) {\n injectScript(\n 'before-hydration',\n `import \"@tenphi/tasty/ssr/astro-client\";`,\n );\n }\n },\n 'astro:config:done': ({\n config,\n }: {\n config: {\n base?: string;\n site?: URL;\n build?: {\n assets?: string;\n assetsPrefix?: string | Record<string, string>;\n };\n };\n }) => {\n base = config.base ?? '/';\n assets = config.build?.assets ?? '_astro';\n assetsPrefix = config.build?.assetsPrefix;\n site = config.site;\n },\n 'astro:build:done': async ({ dir }: { dir: URL }) => {\n if (cssMode !== 'extract') return;\n await extractAstroCSS({ dir, base, assets, assetsPrefix, site });\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;AAQA,MAAM,iBAAiB;AACvB,MAAM,eAAe;AAWrB,SAAgB,yBACd,WACQ;CAIR,OAAO,GAAG,iBAHM,OAAO,KAAK,KAAK,UAAU,SAAS,GAAG,MAAM,CAAC,CAAC,SAC7D,QAE+B,IAAI;AACvC;AAEA,SAAS,qBACP,MACA,MACwB;CACxB,MAAM,gBAAgB,KAAK,QAAQ,cAAc;CACjD,IAAI,kBAAkB,IAAI,OAAO;CAEjC,MAAM,uBAAuB,gBAAgB;CAC7C,MAAM,cAAc,KAAK,QAAQ,cAAc,oBAAoB;CACnE,IAAI,gBAAgB,IAAI,OAAO;CAE/B,MAAM,UAAU,KAAK,MAAM,sBAAsB,WAAW;CAC5D,IAAI;CACJ,IAAI;EACF,YAAY,KAAK,MACf,OAAO,KAAK,SAAS,QAAQ,CAAC,CAAC,SAAS,MAAM,CAChD;CACF,QAAQ;EACN,OAAO;CACT;CAEA,MAAM,aAAa,KAAK,YAAY,yBAAyB,aAAa;CAC1E,IAAI,eAAe,IAAI,OAAO;CAC9B,MAAM,eAAe,KAAK,QA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AM,gBAAgB;KAAE;KAAK;KAAM;KAAQ;KAAc;IAAK,CAAC;GACjE;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"astro.js","names":[],"sources":["../../src/ssr/astro-extraction.ts","../../src/ssr/astro.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { readdir, readFile, writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { ServerStyleArtifact } from './collector';\nimport { findUnsafeCSSResource } from './css-resources';\n\nconst METADATA_START = '<template data-tasty-extract>';\nconst METADATA_END = '</template>';\n\ninterface ExtractablePage {\n path: string;\n html: string;\n artifacts: ServerStyleArtifact[];\n styleStart: number;\n replacementEnd: number;\n styleOpen: string;\n}\n\nexport function createExtractionMetadata(\n artifacts: ServerStyleArtifact[],\n): string {\n const encoded = Buffer.from(JSON.stringify(artifacts), 'utf8').toString(\n 'base64',\n );\n return `${METADATA_START}${encoded}${METADATA_END}`;\n}\n\nfunction parseExtractablePage(\n path: string,\n html: string,\n): ExtractablePage | null {\n const metadataStart = html.indexOf(METADATA_START);\n if (metadataStart === -1) return null;\n\n const metadataContentStart = metadataStart + METADATA_START.length;\n const metadataEnd = html.indexOf(METADATA_END, metadataContentStart);\n if (metadataEnd === -1) return null;\n\n const encoded = html.slice(metadataContentStart, metadataEnd);\n let artifacts: ServerStyleArtifact[];\n try {\n artifacts = JSON.parse(\n Buffer.from(encoded, 'base64').toString('utf8'),\n ) as ServerStyleArtifact[];\n } catch {\n return null;\n }\n\n const styleStart = html.lastIndexOf('<style data-tasty-ssr', metadataStart);\n if (styleStart === -1) return null;\n const styleOpenEnd = html.indexOf('>', styleStart);\n const styleEnd = html.indexOf('</style>', styleOpenEnd + 1);\n if (\n styleOpenEnd === -1 ||\n styleEnd === -1 ||\n styleEnd + '</style>'.length !== metadataStart\n ) {\n return null;\n }\n\n return {\n path,\n html,\n artifacts,\n styleStart,\n replacementEnd: metadataEnd + METADATA_END.length,\n styleOpen: html.slice(styleStart, styleOpenEnd + 1),\n };\n}\n\nasync function findHTMLFiles(dir: string): Promise<string[]> {\n const paths: string[] = [];\n const entries = await readdir(dir, { withFileTypes: true });\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n paths.push(...(await findHTMLFiles(path)));\n } else if (entry.isFile() && entry.name.endsWith('.html')) {\n paths.push(path);\n }\n }\n return paths;\n}\n\nfunction crossOriginAssetsPrefix(\n assetsPrefix?: string | Record<string, string>,\n site?: URL,\n): string | null {\n if (!assetsPrefix) return null;\n const prefix =\n typeof assetsPrefix === 'string'\n ? assetsPrefix\n : assetsPrefix.css || assetsPrefix.fallback;\n if (!/^(?:[a-z][a-z\\d+.-]*:|\\/\\/)/i.test(prefix)) return null;\n if (!site) return prefix;\n\n try {\n const prefixURL = prefix.startsWith('//')\n ? new URL(`${site.protocol}${prefix}`)\n : new URL(prefix);\n return prefixURL.origin === site.origin ? null : prefix;\n } catch {\n return prefix;\n }\n}\n\nfunction validateExtractedURLs(\n pages: ExtractablePage[],\n assetsPrefix?: string | Record<string, string>,\n site?: URL,\n): void {\n const externalPrefix = crossOriginAssetsPrefix(assetsPrefix, site);\n for (const page of pages) {\n for (const artifact of page.artifacts) {\n const unsafe = findUnsafeCSSResource(\n artifact.css,\n externalPrefix !== null,\n );\n if (unsafe) {\n const reason = unsafe.rootRelative\n ? `root-relative CSS URL \"${unsafe.url}\" would resolve against the external assetsPrefix \"${externalPrefix}\" instead of the page origin`\n : `page-relative CSS URL \"${unsafe.url}\" cannot preserve its target`;\n throw new Error(\n `[Tasty] Astro CSS extraction cannot preserve ${reason} in ${page.path} (${artifact.kind} artifact ${artifact.id}). Use an absolute URL or a data URL${externalPrefix ? '' : ', or a root-relative URL such as url(/path/to/asset)'}.`,\n );\n }\n }\n }\n}\n\n/** Find artifacts emitted by every styled page, in the first page's order. */\nfunction selectSharedArtifacts(\n pages: ExtractablePage[],\n): ServerStyleArtifact[] {\n if (pages.length < 2) return [];\n\n const source = pages[0].artifacts;\n const otherIds = pages\n .slice(1)\n .map((page) => new Set(page.artifacts.map(({ id }) => id)));\n\n return source.filter(({ id }) => otherIds.every((ids) => ids.has(id)));\n}\n\nfunction stylesheetHref(\n base: string,\n assets: string,\n filename: string,\n assetsPrefix?: string | Record<string, string>,\n): string {\n const assetsPath = assets.replace(/^\\/+|\\/+$/g, '');\n if (assetsPrefix) {\n const prefix =\n typeof assetsPrefix === 'string'\n ? assetsPrefix\n : assetsPrefix.css || assetsPrefix.fallback;\n return `${prefix.replace(/\\/+$/g, '')}/${assetsPath}/${filename}`;\n }\n\n const basePath = base === '/' ? '' : `/${base.replace(/^\\/+|\\/+$/g, '')}`;\n return `${basePath}/${assetsPath}/${filename}`;\n}\n\nfunction stylesheetLink(page: ExtractablePage, href: string): string {\n const nonceAttr = page.styleOpen.match(/\\snonce=\"[^\"]*\"/)?.[0] ?? '';\n return `<link rel=\"stylesheet\" href=\"${href}\" data-tasty-ssr${nonceAttr}>`;\n}\n\nfunction transformPage(page: ExtractablePage, hrefs: string[]): string {\n const replacement = hrefs.map((href) => stylesheetLink(page, href)).join('');\n\n return (\n page.html.slice(0, page.styleStart) +\n replacement +\n page.html.slice(page.replacementEnd)\n );\n}\n\nasync function writeStylesheet(\n assetDir: string,\n scope: 'shared' | 'page',\n artifacts: ServerStyleArtifact[],\n): Promise<string | null> {\n if (artifacts.length === 0) return null;\n\n const css = artifacts.map(({ css }) => css).join('\\n');\n const hash = createHash('sha256').update(css).digest('hex').slice(0, 12);\n const filename = `tasty.${scope}.${hash}.css`;\n await writeFile(join(assetDir, filename), css);\n return filename;\n}\n\nexport async function extractAstroCSS(options: {\n dir: URL;\n base: string;\n assets: string;\n assetsPrefix?: string | Record<string, string>;\n site?: URL;\n}): Promise<void> {\n const outputDir = fileURLToPath(options.dir);\n const paths = await findHTMLFiles(outputDir);\n const pages = (\n await Promise.all(\n paths.map(async (path) =>\n parseExtractablePage(path, await readFile(path, 'utf8')),\n ),\n )\n ).filter((page): page is ExtractablePage => page !== null);\n if (pages.length === 0) return;\n validateExtractedURLs(pages, options.assetsPrefix, options.site);\n\n const shared = selectSharedArtifacts(pages);\n const assetDir = join(outputDir, options.assets);\n await mkdir(assetDir, { recursive: true });\n const sharedFilename = await writeStylesheet(assetDir, 'shared', shared);\n const sharedHref = sharedFilename\n ? stylesheetHref(\n options.base,\n options.assets,\n sharedFilename,\n options.assetsPrefix,\n )\n : null;\n const sharedIds = new Set(shared.map(({ id }) => id));\n\n for (const page of pages) {\n const remainder = page.artifacts.filter(({ id }) => !sharedIds.has(id));\n const pageFilename = await writeStylesheet(assetDir, 'page', remainder);\n const hrefs = sharedHref ? [sharedHref] : [];\n if (pageFilename) {\n hrefs.push(\n stylesheetHref(\n options.base,\n options.assets,\n pageFilename,\n options.assetsPrefix,\n ),\n );\n }\n await writeFile(page.path, transformPage(page, hrefs));\n }\n}\n","/**\n * Astro integration for Tasty SSR.\n *\n * Provides:\n * - tastyIntegration() — Astro Integration API (recommended)\n * - tastyMiddleware() — manual middleware for advanced composition\n *\n * Import from '@tenphi/tasty/ssr/astro'.\n */\n\nimport { getRuntimeConfigState } from '../config-resources';\nimport { getSSRCollector, runWithCollector } from './async-storage';\nimport { createExtractionMetadata, extractAstroCSS } from './astro-extraction';\nimport { ServerStyleCollector } from './collector';\nimport { registerSSRCollectorGetterGlobal } from './ssr-collector-ref';\n\n// Wire up ALS-based collector discovery so computeStyles() can find\n// the collector set by tastyMiddleware's runWithCollector().\n// Uses globalThis so the getter is visible across Astro's separate\n// module graphs (middleware vs page components).\nregisterSSRCollectorGetterGlobal(getSSRCollector);\n\nexport interface TastyMiddlewareOptions {\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\ninterface InternalTastyMiddlewareOptions extends TastyMiddlewareOptions {\n extractionMetadata?: boolean;\n}\n\n/**\n * Create an Astro middleware that collects Tasty styles during SSR.\n *\n * All React components rendered during the request will have their\n * computeStyles() calls captured by the collector via AsyncLocalStorage.\n * After rendering, the middleware injects the collected CSS into </head>.\n *\n * @example Manual middleware setup\n * ```ts\n * // src/middleware.ts\n * import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';\n * export const onRequest = tastyMiddleware();\n * ```\n *\n * @example Composing with other middleware\n * ```ts\n * // src/middleware.ts\n * import { sequence } from 'astro:middleware';\n * import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';\n *\n * export const onRequest = sequence(\n * tastyMiddleware(),\n * myOtherMiddleware,\n * );\n * ```\n */\nexport function tastyMiddleware(options?: TastyMiddlewareOptions) {\n const internalOptions = options as InternalTastyMiddlewareOptions | undefined;\n return async (\n context: { isPrerendered?: boolean },\n next: () => Promise<Response>,\n ): Promise<Response> => {\n const transferCache = options?.transferCache ?? true;\n const extractionMetadata =\n internalOptions?.extractionMetadata === true &&\n context.isPrerendered === true;\n const collector = new ServerStyleCollector();\n\n // Run the entire request — including body stream consumption — inside\n // the ALS context so that components rendering lazily during stream\n // reads can still find the collector via getSSRCollector().\n type Rendered =\n | { response: Response }\n | { html: string | null; status: number; headers: Headers };\n\n const rendered = await runWithCollector<Promise<Rendered>>(\n collector,\n async (): Promise<Rendered> => {\n const response = await next();\n const body = response.body;\n\n // Only process HTML responses. Reading a non-HTML body (e.g. an\n // image, font, or JSON endpoint) as UTF-8 text corrupts binary\n // payloads: every byte >= 0x80 is decoded to U+FFFD and re-encoded\n // as EF BF BD. Pass anything that isn't HTML straight through.\n const contentType = response.headers.get('content-type') ?? '';\n if (!body || !contentType.includes('text/html')) {\n return { response };\n }\n\n const reader = body.pipeThrough(new TextDecoderStream()).getReader();\n const parts: string[] = [];\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n parts.push(value);\n }\n return {\n html: parts.join(''),\n status: response.status,\n headers: response.headers,\n };\n },\n );\n\n // Non-HTML responses are returned untouched to avoid corrupting\n // binary payloads.\n if ('response' in rendered) {\n return rendered.response;\n }\n\n if (!rendered.html) {\n return new Response(null, {\n status: rendered.status,\n headers: rendered.headers,\n });\n }\n\n let { html } = rendered;\n\n const css = collector.getCSS();\n if (!css) {\n return new Response(html, {\n status: rendered.status,\n headers: rendered.headers,\n });\n }\n\n const nonce = getRuntimeConfigState()?.nonce;\n const nonceAttr = nonce ? ` nonce=\"${nonce}\"` : '';\n const styleTag = `<style data-tasty-ssr${nonceAttr}>${css}</style>`;\n const metadataTag = extractionMetadata\n ? createExtractionMetadata(collector.getArtifacts())\n : '';\n\n let cacheTag = '';\n if (transferCache) {\n const classNames = collector.getRenderedClassNames();\n if (classNames.length > 0) {\n const classListJSON = classNames.map((n) => `\"${n}\"`).join(',');\n cacheTag = `<script${nonceAttr}>(window.__TASTY__=window.__TASTY__||[]).push(${classListJSON})</script>`;\n }\n }\n\n const injection = styleTag + metadataTag + cacheTag;\n const idx = html.indexOf('</head>');\n if (idx !== -1) {\n html = html.slice(0, idx) + injection + html.slice(idx);\n } else {\n html = injection + html;\n }\n\n const headers = new Headers(rendered.headers);\n headers.delete('content-length');\n\n return new Response(html, {\n status: rendered.status,\n headers,\n });\n };\n}\n\n// ============================================================================\n// Astro Integration API\n// ============================================================================\n\n/**\n * Package subpaths of the middleware entrypoints registered by\n * `tastyIntegration()`.\n *\n * These must be bare specifiers rather than\n * `new URL('./astro-middleware.js', import.meta.url)`. The bundler is free to\n * hoist `tastyIntegration` into a shared chunk at a different directory depth\n * than `dist/ssr/`, which makes a relative URL resolve to a file that does not\n * exist and breaks the build for every consumer. A package subpath is resolved\n * by the consumer through our `exports` map, so it never depends on the\n * chunk layout.\n *\n * There are separate entrypoints instead of one parameterised entrypoint because\n * `addMiddleware()` cannot pass options: the integration runs when the Astro\n * config is loaded, while the middleware module is evaluated in the server\n * runtime — a different process for built output — so module-level state set\n * by the integration is not visible to the middleware.\n */\nconst MIDDLEWARE_ENTRYPOINT = '@tenphi/tasty/ssr/astro-middleware';\nconst MIDDLEWARE_ENTRYPOINT_STATIC =\n '@tenphi/tasty/ssr/astro-middleware-static';\nconst MIDDLEWARE_ENTRYPOINT_EXTRACT =\n '@tenphi/tasty/ssr/astro-middleware-extract';\nconst MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC =\n '@tenphi/tasty/ssr/astro-middleware-extract-static';\n\nexport interface TastyIntegrationCSSOptions {\n /**\n * CSS delivery mode. Extraction only applies to prerendered builds.\n * Extracted CSS preserves resource URLs verbatim, so use absolute URLs or\n * data URLs. Root-relative URLs are also supported unless `assetsPrefix`\n * sends CSS to an external origin. The build rejects resource URLs whose\n * targets would change after extraction.\n */\n mode?: 'inline' | 'extract';\n}\n\nexport interface TastyIntegrationOptions {\n /**\n * Enable island hydration support.\n *\n * When `true` (default): injects a client hydration script via\n * `injectScript('before-hydration')` and sets `transferCache: true`\n * on the middleware. Islands skip the style pipeline during hydration.\n *\n * When `false`: no client JS is shipped and `transferCache` is set\n * to `false`. Use this for fully static sites without `client:*`\n * directives.\n */\n islands?: boolean;\n /** Configure inline or build-wide extracted CSS delivery. */\n css?: TastyIntegrationCSSOptions;\n}\n\n/**\n * Astro integration that automatically sets up Tasty SSR.\n *\n * Registers middleware for cross-component CSS deduplication and\n * optionally injects a client hydration script for island support.\n *\n * @example Basic setup (with islands)\n * ```ts\n * // astro.config.mjs\n * import { tastyIntegration } from '@tenphi/tasty/ssr/astro';\n *\n * export default defineConfig({\n * integrations: [tastyIntegration()],\n * });\n * ```\n *\n * @example Static-only (no client JS)\n * ```ts\n * // astro.config.mjs\n * import { tastyIntegration } from '@tenphi/tasty/ssr/astro';\n *\n * export default defineConfig({\n * integrations: [tastyIntegration({ islands: false })],\n * });\n * ```\n */\nexport function tastyIntegration(options?: TastyIntegrationOptions) {\n const { islands = true } = options ?? {};\n const cssMode = options?.css?.mode ?? 'inline';\n let base = '/';\n let assets = '_astro';\n let assetsPrefix: string | Record<string, string> | undefined;\n let site: URL | undefined;\n\n return {\n name: '@tenphi/tasty',\n hooks: {\n 'astro:config:setup': ({\n addMiddleware,\n injectScript,\n }: {\n addMiddleware: (middleware: {\n entrypoint: string | URL;\n order: 'pre' | 'post';\n }) => void;\n injectScript: (\n stage: 'head-inline' | 'before-hydration' | 'page' | 'page-ssr',\n content: string,\n ) => void;\n }) => {\n addMiddleware({\n entrypoint:\n cssMode === 'extract'\n ? islands\n ? MIDDLEWARE_ENTRYPOINT_EXTRACT\n : MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC\n : islands\n ? MIDDLEWARE_ENTRYPOINT\n : MIDDLEWARE_ENTRYPOINT_STATIC,\n order: 'pre',\n });\n\n if (islands) {\n injectScript(\n 'before-hydration',\n `import \"@tenphi/tasty/ssr/astro-client\";`,\n );\n }\n },\n 'astro:config:done': ({\n config,\n }: {\n config: {\n base?: string;\n site?: URL;\n build?: {\n assets?: string;\n assetsPrefix?: string | Record<string, string>;\n };\n };\n }) => {\n base = config.base ?? '/';\n assets = config.build?.assets ?? '_astro';\n assetsPrefix = config.build?.assetsPrefix;\n site = config.site;\n },\n 'astro:build:done': async ({ dir }: { dir: URL }) => {\n if (cssMode !== 'extract') return;\n await extractAstroCSS({ dir, base, assets, assetsPrefix, site });\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;AAQA,MAAM,iBAAiB;AACvB,MAAM,eAAe;AAWrB,SAAgB,yBACd,WACQ;CACR,MAAM,UAAU,OAAO,KAAK,KAAK,UAAU,SAAS,GAAG,MAAM,CAAC,CAAC,SAC7D,QACF;CACA,OAAO,GAAG,iBAAiB,UAAU;AACvC;AAEA,SAAS,qBACP,MACA,MACwB;CACxB,MAAM,gBAAgB,KAAK,QAAQ,cAAc;CACjD,IAAI,kBAAkB,IAAI,OAAO;CAEjC,MAAM,uBAAuB,gBAAgB;CAC7C,MAAM,cAAc,KAAK,QAAQ,cAAc,oBAAoB;CACnE,IAAI,gBAAgB,IAAI,OAAO;CAE/B,MAAM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ACE,wBACA;KACR,OAAO;IACT,CAAC;IAED,IAAI,SACF,aACE,oBACA,0CACF;GAEJ;GACA,sBAAsB,EACpB,aAUI;IACJ,OAAO,OAAO,QAAQ;IACtB,SAAS,OAAO,OAAO,UAAU;IACjC,eAAe,OAAO,OAAO;IAC7B,OAAO,OAAO;GAChB;GACA,oBAAoB,OAAO,EAAE,UAAwB;IACnD,IAAI,YAAY,WAAW;IAC3B,MAAM,gBAAgB;KAAE;KAAK;KAAM;KAAQ;KAAc;IAAK,CAAC;GACjE;EACF;CACF;AACF"}
|
package/dist/ssr/index.d.ts
CHANGED
|
@@ -1,17 +1,16 @@
|
|
|
1
|
-
import { i as ServerStyleArtifactKind, n as createServerStyleCollector, r as ServerStyleArtifact, t as ServerStyleCollector } from "../collector-
|
|
2
|
-
|
|
1
|
+
import { i as ServerStyleArtifactKind, n as createServerStyleCollector, r as ServerStyleArtifact, t as ServerStyleCollector } from "../collector-w4mBj5gd.js";
|
|
3
2
|
//#region src/ssr/async-storage.d.ts
|
|
4
3
|
/**
|
|
5
4
|
* Run a function with a ServerStyleCollector bound to the current
|
|
6
5
|
* async context. All useStyles() calls within `fn` (and any async
|
|
7
6
|
* continuations) will find this collector via getSSRCollector().
|
|
8
7
|
*/
|
|
9
|
-
declare function runWithCollector<T>(collector: ServerStyleCollector, fn: () => T): T;
|
|
8
|
+
export declare function runWithCollector<T>(collector: ServerStyleCollector, fn: () => T): T;
|
|
10
9
|
/**
|
|
11
10
|
* Retrieve the ServerStyleCollector bound to the current async context.
|
|
12
11
|
* Returns null when called outside of runWithCollector() or on the client.
|
|
13
12
|
*/
|
|
14
|
-
declare function getSSRCollector(): ServerStyleCollector | null;
|
|
13
|
+
export declare function getSSRCollector(): ServerStyleCollector | null;
|
|
15
14
|
//#endregion
|
|
16
15
|
//#region src/ssr/hydrate.d.ts
|
|
17
16
|
/**
|
|
@@ -31,7 +30,7 @@ declare function getSSRCollector(): ServerStyleCollector | null;
|
|
|
31
30
|
* When called without arguments, reads the class list from `window.__TASTY__`
|
|
32
31
|
* (populated by inline scripts emitted during SSR/RSC streaming).
|
|
33
32
|
*/
|
|
34
|
-
declare function hydrateTastyClasses(classes?: string[]): void;
|
|
33
|
+
export declare function hydrateTastyClasses(classes?: string[]): void;
|
|
35
34
|
//#endregion
|
|
36
|
-
export { type ServerStyleArtifact, type ServerStyleArtifactKind, ServerStyleCollector, createServerStyleCollector
|
|
35
|
+
export { type ServerStyleArtifact, type ServerStyleArtifactKind, ServerStyleCollector, createServerStyleCollector };
|
|
37
36
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/ssr/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { r as registerSSRCollectorGetterGlobal } from "../chunks/runtime-state-
|
|
2
|
-
import { n as createServerStyleCollector, t as ServerStyleCollector } from "../chunks/collector-
|
|
1
|
+
import { r as registerSSRCollectorGetterGlobal } from "../chunks/runtime-state-BxaLhVdP.js";
|
|
2
|
+
import { n as createServerStyleCollector, t as ServerStyleCollector } from "../chunks/collector-D2ARGT2L.js";
|
|
3
3
|
import { n as runWithCollector, t as getSSRCollector } from "../chunks/async-storage-CG5HnUT5.js";
|
|
4
4
|
import { t as hydrateTastyClasses } from "../chunks/hydration-TRcz5vnk.js";
|
|
5
5
|
//#region src/ssr/index.ts
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { t as TastyConfig } from "../config-
|
|
2
|
-
|
|
1
|
+
import { t as TastyConfig } from "../config-CZWCzBr6.js";
|
|
3
2
|
//#region src/ssr/next-config.d.ts
|
|
4
3
|
interface NextConfig {
|
|
5
4
|
basePath?: string;
|
|
@@ -16,7 +15,7 @@ interface NextHeader {
|
|
|
16
15
|
}[];
|
|
17
16
|
[key: string]: unknown;
|
|
18
17
|
}
|
|
19
|
-
interface TastyNextOptions {
|
|
18
|
+
export interface TastyNextOptions {
|
|
20
19
|
/**
|
|
21
20
|
* Next.js project directory. Useful when the build command runs from a
|
|
22
21
|
* monorepo root rather than the app directory.
|
|
@@ -60,7 +59,6 @@ interface TastyNextOptions {
|
|
|
60
59
|
* Route-dependent component and hook styles continue to stream through
|
|
61
60
|
* `TastyRegistry` so App Router navigation and Suspense remain correct.
|
|
62
61
|
*/
|
|
63
|
-
declare function withTastyNext(options: TastyNextOptions): (nextConfig?: NextConfig) => NextConfig;
|
|
62
|
+
export declare function withTastyNext(options: TastyNextOptions): (nextConfig?: NextConfig) => NextConfig;
|
|
64
63
|
//#endregion
|
|
65
|
-
export { TastyNextOptions, withTastyNext };
|
|
66
64
|
//# sourceMappingURL=next-config.d.ts.map
|
package/dist/ssr/next-config.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { L as DEFAULT_PROPERTIES, U as parseFunctionName, V as formatFunctionRule, a as formatPropertyCSS, b as formatFontFaceRule, h as formatCounterStyleRule, n as formatGlobalRules, t as createServerStyleArtifact, v as fontFaceContentHash } from "../chunks/css-definitions-
|
|
2
|
-
import { b as renderStyles } from "../chunks/style-engine-
|
|
3
|
-
import { n as functionsForExtraction, r as resetZeroConfig, t as configureZero } from "../chunks/build-config-
|
|
4
|
-
import { t as findUnsafeCSSResource } from "../chunks/css-resources-
|
|
1
|
+
import { L as DEFAULT_PROPERTIES, U as parseFunctionName, V as formatFunctionRule, a as formatPropertyCSS, b as formatFontFaceRule, h as formatCounterStyleRule, n as formatGlobalRules, t as createServerStyleArtifact, v as fontFaceContentHash } from "../chunks/css-definitions-DotDkIXt.js";
|
|
2
|
+
import { b as renderStyles } from "../chunks/style-engine-BBbBuSkT.js";
|
|
3
|
+
import { n as functionsForExtraction, r as resetZeroConfig, t as configureZero } from "../chunks/build-config-CL4eRu2z.js";
|
|
4
|
+
import { t as findUnsafeCSSResource } from "../chunks/css-resources-P7IBUUZs.js";
|
|
5
5
|
import { createHash } from "node:crypto";
|
|
6
6
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
7
|
import { createRequire } from "node:module";
|
|
@@ -44,7 +44,10 @@ function collectSharedCSS(config) {
|
|
|
44
44
|
}
|
|
45
45
|
for (const [name, descriptors] of Object.entries(normalized.counterStyles)) append("counter-style", name, formatCounterStyleRule(name, descriptors));
|
|
46
46
|
for (const [name, definition] of Object.entries(functionsForExtraction(resolved) ?? {})) append("function", parseFunctionName(name), formatFunctionRule(name, definition));
|
|
47
|
-
if (Object.keys(normalized.tokens).length > 0)
|
|
47
|
+
if (Object.keys(normalized.tokens).length > 0) {
|
|
48
|
+
const rules = renderStyles(normalized.tokens, ":root");
|
|
49
|
+
append("global", "__global:tokens", formatGlobalRules(rules));
|
|
50
|
+
}
|
|
48
51
|
for (const [selector, styles] of Object.entries(normalized.globalStyles)) {
|
|
49
52
|
if (Object.keys(styles).length === 0) continue;
|
|
50
53
|
const rules = renderStyles(styles, selector);
|
|
@@ -60,7 +63,8 @@ function collectSharedCSS(config) {
|
|
|
60
63
|
}
|
|
61
64
|
}
|
|
62
65
|
function inferPublicPath(projectDir, outputDir) {
|
|
63
|
-
const
|
|
66
|
+
const publicDir = resolve(projectDir, "public");
|
|
67
|
+
const relativePath = relative(publicDir, outputDir);
|
|
64
68
|
if (relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) throw new Error("[Tasty] `publicPath` is required when `outputDir` is outside the Next.js public directory.");
|
|
65
69
|
return `/${relativePath.split(sep).filter(Boolean).join("/")}`;
|
|
66
70
|
}
|
|
@@ -1 +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 type { TastyConfig } from '../config';\nimport { formatCounterStyleRule } from '../counter-style';\nimport { fontFaceContentHash, formatFontFaceRule } from '../font-face';\nimport { formatFunctionRule, parseFunctionName } from '../functions';\nimport { renderStyles } from '../pipeline';\nimport type { StyleResult } from '../pipeline';\nimport { DEFAULT_PROPERTIES } from '../properties/defaults';\nimport {\n configureZero,\n functionsForExtraction,\n resetZeroConfig,\n} from '../zero/config';\nimport { createServerStyleArtifact } from './artifacts';\nimport type { ServerStyleArtifact, ServerStyleArtifactKind } from './artifacts';\nimport { findUnsafeCSSResource } from './css-resources';\nimport { formatGlobalRules } from './format-global-rules';\nimport { formatPropertyCSS } from './format-property';\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 resetZeroConfig();\n try {\n const resolved = configureZero(config);\n const { normalized } = resolved;\n const artifacts: ServerStyleArtifact[] = [];\n const append = (\n kind: ServerStyleArtifactKind,\n key: string,\n css: string,\n ) => {\n if (!css) return;\n\n artifacts.push(\n createServerStyleArtifact(kind, key, css, artifacts.length),\n );\n };\n\n for (const [token, definition] of Object.entries({\n ...DEFAULT_PROPERTIES,\n ...normalized.properties,\n })) {\n append(\n 'property',\n `__prop:${token}`,\n formatPropertyCSS(token, definition),\n );\n }\n\n for (const [family, input] of Object.entries(normalized.fontFaces)) {\n const descriptors = Array.isArray(input) ? input : [input];\n for (const descriptor of descriptors) {\n append(\n 'font-face',\n fontFaceContentHash(family, descriptor),\n formatFontFaceRule(family, descriptor),\n );\n }\n }\n\n for (const [name, descriptors] of Object.entries(\n normalized.counterStyles,\n )) {\n append('counter-style', name, formatCounterStyleRule(name, descriptors));\n }\n\n for (const [name, definition] of Object.entries(\n functionsForExtraction(resolved) ?? {},\n )) {\n append(\n 'function',\n parseFunctionName(name),\n formatFunctionRule(name, definition),\n );\n }\n\n if (Object.keys(normalized.tokens).length > 0) {\n const rules = renderStyles(normalized.tokens, ':root') as StyleResult[];\n append('global', '__global:tokens', formatGlobalRules(rules));\n }\n\n for (const [selector, styles] of Object.entries(normalized.globalStyles)) {\n if (Object.keys(styles).length === 0) continue;\n const rules = renderStyles(styles, selector) as StyleResult[];\n append('global', `__global:styles:${selector}`, formatGlobalRules(rules));\n }\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 resetZeroConfig();\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":";;;;;;;;;AA+BA,MAAM,UAAU;AAChB,MAAM,iBAAiB,cAAc,OAAO,KAAK,GAAG;AA6DpD,SAAS,WACP,YACA,SACa;CACb,IAAI,QAAQ,QAAQ,OAAO,QAAQ;CACnC,IAA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ACF;EAKA,IAAI,WAAW,WAAW,UAAU,OAAO;EAE3C,OAAO;GACL,GAAG;GACH,MAAM,UAAU;IAEd,OAAO,CACL,GAFc,kBAAkB,MAAM,gBAAgB,IAAI,CAAC,GAG3D;KACE,QAAQ;KACR,SAAS,CACP;MACE,KAAK;MACL,OAAO;KACT,CACF;IACF,CACF;GACF;EACF;CACF;AACF"}
|
|
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 type { TastyConfig } from '../config';\nimport { formatCounterStyleRule } from '../counter-style';\nimport { fontFaceContentHash, formatFontFaceRule } from '../font-face';\nimport { formatFunctionRule, parseFunctionName } from '../functions';\nimport { renderStyles } from '../pipeline';\nimport type { StyleResult } from '../pipeline';\nimport { DEFAULT_PROPERTIES } from '../properties/defaults';\nimport {\n configureZero,\n functionsForExtraction,\n resetZeroConfig,\n} from '../zero/config';\nimport { createServerStyleArtifact } from './artifacts';\nimport type { ServerStyleArtifact, ServerStyleArtifactKind } from './artifacts';\nimport { findUnsafeCSSResource } from './css-resources';\nimport { formatGlobalRules } from './format-global-rules';\nimport { formatPropertyCSS } from './format-property';\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 resetZeroConfig();\n try {\n const resolved = configureZero(config);\n const { normalized } = resolved;\n const artifacts: ServerStyleArtifact[] = [];\n const append = (\n kind: ServerStyleArtifactKind,\n key: string,\n css: string,\n ) => {\n if (!css) return;\n\n artifacts.push(\n createServerStyleArtifact(kind, key, css, artifacts.length),\n );\n };\n\n for (const [token, definition] of Object.entries({\n ...DEFAULT_PROPERTIES,\n ...normalized.properties,\n })) {\n append(\n 'property',\n `__prop:${token}`,\n formatPropertyCSS(token, definition),\n );\n }\n\n for (const [family, input] of Object.entries(normalized.fontFaces)) {\n const descriptors = Array.isArray(input) ? input : [input];\n for (const descriptor of descriptors) {\n append(\n 'font-face',\n fontFaceContentHash(family, descriptor),\n formatFontFaceRule(family, descriptor),\n );\n }\n }\n\n for (const [name, descriptors] of Object.entries(\n normalized.counterStyles,\n )) {\n append('counter-style', name, formatCounterStyleRule(name, descriptors));\n }\n\n for (const [name, definition] of Object.entries(\n functionsForExtraction(resolved) ?? {},\n )) {\n append(\n 'function',\n parseFunctionName(name),\n formatFunctionRule(name, definition),\n );\n }\n\n if (Object.keys(normalized.tokens).length > 0) {\n const rules = renderStyles(normalized.tokens, ':root') as StyleResult[];\n append('global', '__global:tokens', formatGlobalRules(rules));\n }\n\n for (const [selector, styles] of Object.entries(normalized.globalStyles)) {\n if (Object.keys(styles).length === 0) continue;\n const rules = renderStyles(styles, selector) as StyleResult[];\n append('global', `__global:styles:${selector}`, formatGlobalRules(rules));\n }\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 resetZeroConfig();\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":";;;;;;;;;AA+BA,MAAM,UAAU;AAChB,MAAM,iBAAiB,cAAc,YAAY,GAAG;AA6DpD,SAAS,WACP,YACA,SACa;CACb,IAAI,QAAQ,QAAQ,OAAO,QAAQ;CACnC,IAAI,CAAC,QAAQ,YACX,MAAM,IAAI,MACR,mEACF;CAGF,MAAM,aAAa,QAAQ,YAAY,QAAQ,UAAU;CACzD,IAAI;CACJ,IAAI;EACF,WAAW,eAAe,QAAQ,MAAM;CAC1C,SAAS,OAAO;EACd,IACE,iBAAiB,SACjB,UAAU,SACV,MAAM,SAAS,oBAEf,MAAM,IAAI,MACR,mIACA,EAAE,OAAO,MAAM,CACjB;EAEF,MAAM;CACR;CACA,MAAM,EAAE,eAAe,eAAe,QAAQ;CAI9C,MAAM,SADO,WAAW,YAAY,EAAE,aAAa,MAAM,CACvC,CAAC,CAAC,UAAU;CAE9B,OAAO,UAAU,OAAO,WAAW,YAAY,aAAa,SACxD,OAAO,UACP;AACN;AAEA,SAAS,iBAAiB,QAA6B;CACrD,gBAAgB;CAChB,IAAI;EACF,MAAM,WAAW,cAAc,MAAM;EACrC,MAAM,EAAE,eAAe;EACvB,MAAM,YAAmC,CAAC;EAC1C,MAAM,UACJ,MACA,KACA,QACG;GACH,IAAI,CAAC,KAAK;GAEV,UAAU,K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,QAAQ,QAAQ,IAAI,GAAG,QAAQ,WAAW,GAAG;EAChE,MAAM,YAAY,QAAQ,YAAY,QAAQ,aAAa,eAAe;EAC1E,MAAM,aAAa,iBACjB,QAAQ,cAAc,gBAAgB,YAAY,SAAS,GAC3D,YACF;EACA,MAAM,WAAW,iBAAiB,WAAW,YAAY,KAAK,UAAU;EACxE,MAAM,MAAM,iBAAiB,WAAW,YAAY,OAAO,CAAC;EAE5D,IAAI,CAAC,KAAK,OAAO;EAEjB,MAAM,WAAW,eAAe,WAAW,GAAG;EAC9C,MAAM,OAAO,GAAG,WAAW,WAAW,GAAG;EACzC,MAAM,eAAe,GAAG,WAAW,GAAG;EACtC,MAAM,cAAc,WAAW,OAAO,CAAC;EACvC,MAAM,kBAAkB,WAAW;EACnC,IAAI,YAAY,YAAY,YAAY,aAAa,MACnD,MAAM,IAAI,MACR,2BAA2B,QAAQ,iCACrC;EAGF,MAAM,kBAA8B;GAClC,GAAG;GACH,KAAK;IACH,GAAG;KACF,UAAU;GACb;EACF;EAKA,IAAI,WAAW,WAAW,UAAU,OAAO;EAE3C,OAAO;GACL,GAAG;GACH,MAAM,UAAU;IAEd,OAAO,CACL,GAFc,kBAAkB,MAAM,gBAAgB,IAAI,CAAC,GAG3D;KACE,QAAQ;KACR,SAAS,CACP;MACE,KAAK;MACL,OAAO;KACT,CACF;IACF,CACF;GACF;EACF;CACF;AACF"}
|
package/dist/ssr/next.d.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { t as ServerStyleCollector } from "../collector-
|
|
1
|
+
import { t as ServerStyleCollector } from "../collector-w4mBj5gd.js";
|
|
2
2
|
import { ReactNode } from "react";
|
|
3
|
-
|
|
4
3
|
//#region src/ssr/next.d.ts
|
|
5
|
-
interface TastyRegistryProps {
|
|
4
|
+
export interface TastyRegistryProps {
|
|
6
5
|
children: ReactNode;
|
|
7
6
|
/**
|
|
8
7
|
* Whether to embed the class-list script for client hydration.
|
|
@@ -42,11 +41,6 @@ interface TastyRegistryProps {
|
|
|
42
41
|
* }
|
|
43
42
|
* ```
|
|
44
43
|
*/
|
|
45
|
-
declare function TastyRegistry({
|
|
46
|
-
children,
|
|
47
|
-
transferCache,
|
|
48
|
-
sharedStylesheet
|
|
49
|
-
}: TastyRegistryProps): import("react").FunctionComponentElement<import("react").ProviderProps<ServerStyleCollector | null>>;
|
|
44
|
+
export declare function TastyRegistry({ children, transferCache, sharedStylesheet }: TastyRegistryProps): import("react").FunctionComponentElement<import("react").ProviderProps<ServerStyleCollector | null>>;
|
|
50
45
|
//#endregion
|
|
51
|
-
export { TastyRegistry, TastyRegistryProps };
|
|
52
46
|
//# sourceMappingURL=next.d.ts.map
|
package/dist/ssr/next.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { n as registerSSRCollectorGetter, u as getRuntimeConfigState } from "../chunks/runtime-state-
|
|
3
|
-
import { u as getTastySSRContext } from "../chunks/react-runtime-
|
|
4
|
-
import { t as ServerStyleCollector } from "../chunks/collector-
|
|
2
|
+
import { n as registerSSRCollectorGetter, u as getRuntimeConfigState } from "../chunks/runtime-state-BxaLhVdP.js";
|
|
3
|
+
import { u as getTastySSRContext } from "../chunks/react-runtime-BpxlOTbO.js";
|
|
4
|
+
import { t as ServerStyleCollector } from "../chunks/collector-D2ARGT2L.js";
|
|
5
5
|
import { t as hydrateTastyClasses } from "../chunks/hydration-TRcz5vnk.js";
|
|
6
6
|
import { Fragment, createElement, useState } from "react";
|
|
7
7
|
import { useServerInsertedHTML } from "next/navigation";
|
|
@@ -44,10 +44,11 @@ function TastyRegistry({ children, transferCache = true, sharedStylesheet = proc
|
|
|
44
44
|
dangerouslySetInnerHTML: { __html: css }
|
|
45
45
|
});
|
|
46
46
|
if (!transferCache || classNames.length === 0) return linkEl ? createElement(Fragment, null, linkEl, styleEl) : styleEl;
|
|
47
|
+
const classListJSON = classNames.map((n) => `"${n}"`).join(",");
|
|
47
48
|
const scriptEl = createElement("script", {
|
|
48
49
|
key: "tasty-ssr-cache",
|
|
49
50
|
nonce,
|
|
50
|
-
dangerouslySetInnerHTML: { __html: `(window.__TASTY__=window.__TASTY__||[]).push(${
|
|
51
|
+
dangerouslySetInnerHTML: { __html: `(window.__TASTY__=window.__TASTY__||[]).push(${classListJSON})` }
|
|
51
52
|
});
|
|
52
53
|
return createElement(Fragment, null, linkEl, styleEl, scriptEl);
|
|
53
54
|
});
|
package/dist/ssr/next.js.map
CHANGED
|
@@ -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 { getRuntimeConfigState } from '../config-resources';\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 = getRuntimeConfigState()?.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,sBAAsB,CAAC,EAAE;CAEvC,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;
|
|
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 { getRuntimeConfigState } from '../config-resources';\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 = getRuntimeConfigState()?.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,sBAAsB,CAAC,EAAE;CAEvC,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;EAGnE,MAAM,gBAAgB,WAAW,KAAK,MAAM,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,GAAG;EAE9D,MAAM,WAAW,cAAc,UAAU;GACvC,KAAK;GACL;GACA,yBAAyB,EACvB,QAAQ,gDAAgD,cAAc,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"}
|
package/dist/static/index.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as mergeStyles } from "../merge-styles-
|
|
3
|
-
|
|
1
|
+
import { Y as Styles } from "../types-JEY8PVYP.js";
|
|
2
|
+
import { t as mergeStyles } from "../merge-styles-VXwJ0Frr.js";
|
|
4
3
|
//#region src/static/types.d.ts
|
|
5
4
|
/**
|
|
6
5
|
* Static style definition returned by tastyStatic().
|
|
@@ -40,11 +39,11 @@ interface StaticStyle {
|
|
|
40
39
|
* Create a StaticStyle object.
|
|
41
40
|
* Used internally by the Babel plugin to generate output.
|
|
42
41
|
*/
|
|
43
|
-
declare function createStaticStyle(className: string, styles: Styles): StaticStyle;
|
|
42
|
+
export declare function createStaticStyle(className: string, styles: Styles): StaticStyle;
|
|
44
43
|
/**
|
|
45
44
|
* Type guard to check if a value is a StaticStyle object.
|
|
46
45
|
*/
|
|
47
|
-
declare function isStaticStyle(value: unknown): value is StaticStyle;
|
|
46
|
+
export declare function isStaticStyle(value: unknown): value is StaticStyle;
|
|
48
47
|
//#endregion
|
|
49
48
|
//#region src/static/tastyStatic.d.ts
|
|
50
49
|
/**
|
|
@@ -62,7 +61,7 @@ declare function isStaticStyle(value: unknown): value is StaticStyle;
|
|
|
62
61
|
* <div className={button} /> // Works via toString()
|
|
63
62
|
* ```
|
|
64
63
|
*/
|
|
65
|
-
declare function tastyStatic(styles: Styles): StaticStyle;
|
|
64
|
+
export declare function tastyStatic(styles: Styles): StaticStyle;
|
|
66
65
|
/**
|
|
67
66
|
* Extend an existing StaticStyle with additional styles.
|
|
68
67
|
* Uses mergeStyles() internally for proper nested selector handling.
|
|
@@ -74,7 +73,7 @@ declare function tastyStatic(styles: Styles): StaticStyle;
|
|
|
74
73
|
* // After build: { className: 'ts8c4d2e', styles: {...merged...}, toString() }
|
|
75
74
|
* ```
|
|
76
75
|
*/
|
|
77
|
-
declare function tastyStatic(base: StaticStyle, styles: Styles): StaticStyle;
|
|
76
|
+
export declare function tastyStatic(base: StaticStyle, styles: Styles): StaticStyle;
|
|
78
77
|
/**
|
|
79
78
|
* Generate styles for a specific CSS selector.
|
|
80
79
|
* The call is completely removed after build transformation.
|
|
@@ -85,7 +84,7 @@ declare function tastyStatic(base: StaticStyle, styles: Styles): StaticStyle;
|
|
|
85
84
|
* // After build: (removed)
|
|
86
85
|
* ```
|
|
87
86
|
*/
|
|
88
|
-
declare function tastyStatic(selector: string, styles: Styles): void;
|
|
87
|
+
export declare function tastyStatic(selector: string, styles: Styles): void;
|
|
89
88
|
//#endregion
|
|
90
|
-
export { type StaticStyle, type Styles,
|
|
89
|
+
export { type StaticStyle, type Styles, mergeStyles };
|
|
91
90
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/static/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as mergeStyles } from "../chunks/shared-utils-
|
|
1
|
+
import { t as mergeStyles } from "../chunks/shared-utils-y-HjvPN4.js";
|
|
2
2
|
//#region src/static/types.ts
|
|
3
3
|
function createStaticStyle(className, styles) {
|
|
4
4
|
return {
|
|
@@ -16,14 +16,14 @@ function isStaticStyle(value) {
|
|
|
16
16
|
//#region src/static/tastyStatic.ts
|
|
17
17
|
function tastyStatic(stylesOrBaseOrSelector, styles) {
|
|
18
18
|
if (typeof stylesOrBaseOrSelector === "string") {
|
|
19
|
-
console.warn(`[Tasty] tastyStatic('${stylesOrBaseOrSelector}', styles) was called at runtime. This indicates the Babel plugin is not configured. Add @tenphi/tasty/babel-plugin to your Babel config.`);
|
|
19
|
+
if (process.env.NODE_ENV !== "production") console.warn(`[Tasty] tastyStatic('${stylesOrBaseOrSelector}', styles) was called at runtime. This indicates the Babel plugin is not configured. Add @tenphi/tasty/babel-plugin to your Babel config.`);
|
|
20
20
|
return;
|
|
21
21
|
}
|
|
22
22
|
if (isStaticStyle(stylesOrBaseOrSelector)) {
|
|
23
|
-
console.warn("[Tasty] tastyStatic(base, styles) was called at runtime. This indicates the Babel plugin is not configured. Add @tenphi/tasty/babel-plugin to your Babel config.");
|
|
23
|
+
if (process.env.NODE_ENV !== "production") console.warn("[Tasty] tastyStatic(base, styles) was called at runtime. This indicates the Babel plugin is not configured. Add @tenphi/tasty/babel-plugin to your Babel config.");
|
|
24
24
|
return createStaticStyle("__TASTY_STATIC_NOT_TRANSFORMED__", mergeStyles(stylesOrBaseOrSelector.styles, styles || {}));
|
|
25
25
|
}
|
|
26
|
-
console.warn("[Tasty] tastyStatic(styles) was called at runtime. This indicates the Babel plugin is not configured. Add @tenphi/tasty/babel-plugin to your Babel config.");
|
|
26
|
+
if (process.env.NODE_ENV !== "production") console.warn("[Tasty] tastyStatic(styles) was called at runtime. This indicates the Babel plugin is not configured. Add @tenphi/tasty/babel-plugin to your Babel config.");
|
|
27
27
|
return createStaticStyle("__TASTY_STATIC_NOT_TRANSFORMED__", stylesOrBaseOrSelector);
|
|
28
28
|
}
|
|
29
29
|
//#endregion
|