@tenphi/tasty 3.4.0 → 3.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +147 -129
- package/dist/astro-CzY4LCpr.js +437 -0
- package/dist/astro-CzY4LCpr.js.map +1 -0
- package/dist/{babel-BUQGeOXA.d.ts → babel-DWCsafYw.d.ts} +2 -2
- package/dist/{collector-DUaHCcTS.d.ts → collector-BTVXj2hS.d.ts} +21 -3
- package/dist/{collector-DTahQUiV.js → collector-C6TtL8HJ.js} +36 -13
- package/dist/collector-C6TtL8HJ.js.map +1 -0
- package/dist/{config-B5kHzuNz.js → config-B3gPdCqd.js} +305 -153
- package/dist/config-B3gPdCqd.js.map +1 -0
- package/dist/{config-YsxGv4tq.d.ts → config-LfIDmVHx.d.ts} +132 -32
- package/dist/core/index.d.ts +5 -5
- package/dist/core/index.js +6 -6
- package/dist/{core-Dr4u1NVD.js → core-Bq7w2kti.js} +215 -95
- package/dist/core-Bq7w2kti.js.map +1 -0
- package/dist/{css-writer-B-J87ncv.js → css-writer-Bgowobbx.js} +3 -3
- package/dist/{css-writer-B-J87ncv.js.map → css-writer-Bgowobbx.js.map} +1 -1
- package/dist/{format-rules-DKOA-6qu.js → format-rules-rCZ37rqY.js} +2 -2
- package/dist/format-rules-rCZ37rqY.js.map +1 -0
- package/dist/{hydrate-OeMX99We.js → hydrate-CNOmZprz.js} +3 -3
- package/dist/{hydrate-OeMX99We.js.map → hydrate-CNOmZprz.js.map} +1 -1
- package/dist/{index-PqN-DIpn.d.ts → index-Bm9ltvdH.d.ts} +38 -16
- package/dist/{index-Cd45t5NM.d.ts → index-BmogEzTo.d.ts} +69 -15
- package/dist/index.d.ts +5 -5
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/{keyframes-CV8azJf3.js → keyframes-DE-OE76F.js} +45 -3
- package/dist/keyframes-DE-OE76F.js.map +1 -0
- package/dist/{merge-styles-CU7JbEwg.d.ts → merge-styles-BcLl1u_d.d.ts} +2 -2
- package/dist/{merge-styles-oklji0KB.js → merge-styles-DuoZEsm9.js} +2 -2
- package/dist/{merge-styles-oklji0KB.js.map → merge-styles-DuoZEsm9.js.map} +1 -1
- package/dist/{resolve-recipes-DTG81rzl.js → resolve-recipes-H9NqOQuP.js} +3 -3
- package/dist/{resolve-recipes-DTG81rzl.js.map → resolve-recipes-H9NqOQuP.js.map} +1 -1
- package/dist/ssr/astro-client.js +1 -1
- package/dist/ssr/astro-middleware-extract-static.d.ts +11 -0
- package/dist/ssr/astro-middleware-extract-static.js +9 -0
- package/dist/ssr/astro-middleware-extract-static.js.map +1 -0
- package/dist/ssr/astro-middleware-extract.d.ts +11 -0
- package/dist/ssr/astro-middleware-extract.js +9 -0
- package/dist/ssr/astro-middleware-extract.js.map +1 -0
- package/dist/ssr/astro-middleware-static.d.ts +3 -1
- package/dist/ssr/astro-middleware-static.js +1 -1
- package/dist/ssr/astro-middleware.d.ts +3 -1
- package/dist/ssr/astro-middleware.js +1 -1
- package/dist/ssr/astro.d.ts +45 -3
- package/dist/ssr/astro.js +1 -156
- package/dist/ssr/index.d.ts +2 -2
- package/dist/ssr/index.js +3 -3
- package/dist/ssr/index.js.map +1 -1
- package/dist/ssr/next.d.ts +1 -1
- package/dist/ssr/next.js +4 -4
- package/dist/static/index.d.ts +2 -2
- package/dist/static/index.js +1 -1
- package/dist/zero/babel.d.ts +1 -1
- package/dist/zero/babel.js +4 -4
- package/dist/zero/babel.js.map +1 -1
- package/dist/zero/index.d.ts +1 -1
- package/dist/zero/index.js +1 -1
- package/dist/zero/next.d.ts +1 -1
- package/docs/README.md +13 -8
- package/docs/adoption.md +56 -31
- package/docs/ai-agents.md +78 -77
- package/docs/comparison.md +69 -40
- package/docs/configuration.md +97 -87
- package/docs/debug.md +4 -2
- package/docs/design-system.md +41 -22
- package/docs/dsl.md +225 -195
- package/docs/getting-started.md +60 -39
- package/docs/injector.md +63 -26
- package/docs/methodology.md +42 -36
- package/docs/migration-v3.md +49 -49
- package/docs/plugins.md +37 -33
- package/docs/react-api.md +65 -44
- package/docs/runtime-benchmarks.md +178 -0
- package/docs/ssr.md +124 -61
- package/docs/styles.md +1 -1
- package/docs/tasty-static.md +137 -104
- package/package.json +26 -8
- package/dist/collector-DTahQUiV.js.map +0 -1
- package/dist/config-B5kHzuNz.js.map +0 -1
- package/dist/core-Dr4u1NVD.js.map +0 -1
- package/dist/format-rules-DKOA-6qu.js.map +0 -1
- package/dist/keyframes-CV8azJf3.js.map +0 -1
- package/dist/ssr/astro.js.map +0 -1
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
import { n as getConfig } from "./config-B3gPdCqd.js";
|
|
2
|
+
import { a as registerSSRCollectorGetterGlobal } from "./format-rules-rCZ37rqY.js";
|
|
3
|
+
import { t as ServerStyleCollector } from "./collector-C6TtL8HJ.js";
|
|
4
|
+
import { n as runWithCollector, t as getSSRCollector } from "./async-storage-DKK-wTD4.js";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
//#region src/ssr/astro-extraction.ts
|
|
10
|
+
const METADATA_START = "<template data-tasty-extract>";
|
|
11
|
+
const METADATA_END = "</template>";
|
|
12
|
+
function createExtractionMetadata(artifacts) {
|
|
13
|
+
return `${METADATA_START}${Buffer.from(JSON.stringify(artifacts), "utf8").toString("base64")}${METADATA_END}`;
|
|
14
|
+
}
|
|
15
|
+
function parseExtractablePage(path, html) {
|
|
16
|
+
const metadataStart = html.indexOf(METADATA_START);
|
|
17
|
+
if (metadataStart === -1) return null;
|
|
18
|
+
const metadataContentStart = metadataStart + 29;
|
|
19
|
+
const metadataEnd = html.indexOf(METADATA_END, metadataContentStart);
|
|
20
|
+
if (metadataEnd === -1) return null;
|
|
21
|
+
const encoded = html.slice(metadataContentStart, metadataEnd);
|
|
22
|
+
let artifacts;
|
|
23
|
+
try {
|
|
24
|
+
artifacts = JSON.parse(Buffer.from(encoded, "base64").toString("utf8"));
|
|
25
|
+
} catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
const styleStart = html.lastIndexOf("<style data-tasty-ssr", metadataStart);
|
|
29
|
+
if (styleStart === -1) return null;
|
|
30
|
+
const styleOpenEnd = html.indexOf(">", styleStart);
|
|
31
|
+
const styleEnd = html.indexOf("</style>", styleOpenEnd + 1);
|
|
32
|
+
if (styleOpenEnd === -1 || styleEnd === -1 || styleEnd + 8 !== metadataStart) return null;
|
|
33
|
+
return {
|
|
34
|
+
path,
|
|
35
|
+
html,
|
|
36
|
+
artifacts,
|
|
37
|
+
styleStart,
|
|
38
|
+
replacementEnd: metadataEnd + 11,
|
|
39
|
+
styleOpen: html.slice(styleStart, styleOpenEnd + 1)
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
async function findHTMLFiles(dir) {
|
|
43
|
+
const paths = [];
|
|
44
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
45
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
46
|
+
for (const entry of entries) {
|
|
47
|
+
const path = join(dir, entry.name);
|
|
48
|
+
if (entry.isDirectory()) paths.push(...await findHTMLFiles(path));
|
|
49
|
+
else if (entry.isFile() && entry.name.endsWith(".html")) paths.push(path);
|
|
50
|
+
}
|
|
51
|
+
return paths;
|
|
52
|
+
}
|
|
53
|
+
function skipCSSString(css, start, quote) {
|
|
54
|
+
for (let index = start + 1; index < css.length; index++) if (css[index] === "\\") index++;
|
|
55
|
+
else if (css[index] === quote) return index + 1;
|
|
56
|
+
return css.length;
|
|
57
|
+
}
|
|
58
|
+
function decodeCSSEscapes(value) {
|
|
59
|
+
return value.replace(/\\(?:([\da-f]{1,6})\s?|\r\n|[\n\r\f]|(.))/gi, (_match, hex, escaped) => {
|
|
60
|
+
if (hex) {
|
|
61
|
+
const codePoint = Number.parseInt(hex, 16);
|
|
62
|
+
return codePoint === 0 || codePoint > 1114111 ? "�" : String.fromCodePoint(codePoint);
|
|
63
|
+
}
|
|
64
|
+
return escaped ?? "";
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
function readCSSIdentifier(css, start) {
|
|
68
|
+
let name = "";
|
|
69
|
+
let index = start;
|
|
70
|
+
while (index < css.length) {
|
|
71
|
+
const char = css[index];
|
|
72
|
+
if (/[-_a-z\d]/i.test(char) || char.charCodeAt(0) >= 128) {
|
|
73
|
+
name += char;
|
|
74
|
+
index++;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (char !== "\\" || index + 1 >= css.length) break;
|
|
78
|
+
const hex = css.slice(index + 1).match(/^[\da-f]{1,6}/i)?.[0];
|
|
79
|
+
if (hex) {
|
|
80
|
+
name += decodeCSSEscapes(`\\${hex}`);
|
|
81
|
+
index += hex.length + 1;
|
|
82
|
+
if (/\s/.test(css[index] ?? "")) index++;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (/\r|\n|\f/.test(css[index + 1])) break;
|
|
86
|
+
name += css[index + 1];
|
|
87
|
+
index += 2;
|
|
88
|
+
}
|
|
89
|
+
return index === start ? null : {
|
|
90
|
+
name,
|
|
91
|
+
end: index
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function skipCSSWhitespaceAndComments(css, start) {
|
|
95
|
+
let index = start;
|
|
96
|
+
for (;;) {
|
|
97
|
+
while (/\s/.test(css[index] ?? "")) index++;
|
|
98
|
+
if (css[index] !== "/" || css[index + 1] !== "*") return index;
|
|
99
|
+
const commentEnd = css.indexOf("*/", index + 2);
|
|
100
|
+
if (commentEnd === -1) return css.length;
|
|
101
|
+
index = commentEnd + 2;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function classifyCSSResource(rawURL, rejectRootRelative) {
|
|
105
|
+
const url = decodeCSSEscapes(rawURL).trim();
|
|
106
|
+
if (!url || url.startsWith("//") || /^[a-z][a-z\d+.-]*:/i.test(url)) return null;
|
|
107
|
+
if (url.startsWith("/")) return rejectRootRelative ? {
|
|
108
|
+
url: rawURL,
|
|
109
|
+
rootRelative: true
|
|
110
|
+
} : null;
|
|
111
|
+
return {
|
|
112
|
+
url: rawURL,
|
|
113
|
+
rootRelative: false
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function findUnsafeCSSResource(css, rejectRootRelative) {
|
|
117
|
+
const functionStack = [];
|
|
118
|
+
const stringResourceFunctions = new Set([
|
|
119
|
+
"image",
|
|
120
|
+
"image-set",
|
|
121
|
+
"-webkit-image-set",
|
|
122
|
+
"src"
|
|
123
|
+
]);
|
|
124
|
+
for (let index = 0; index < css.length; index++) {
|
|
125
|
+
if (css[index] === "/" && css[index + 1] === "*") {
|
|
126
|
+
const commentEnd = css.indexOf("*/", index + 2);
|
|
127
|
+
index = commentEnd === -1 ? css.length : commentEnd + 1;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
const quote = css[index];
|
|
131
|
+
if (quote === "\"" || quote === "'") {
|
|
132
|
+
const stringEnd = skipCSSString(css, index, quote);
|
|
133
|
+
if (stringResourceFunctions.has(functionStack.at(-1) ?? "")) {
|
|
134
|
+
const unsafe = classifyCSSResource(css.slice(index + 1, stringEnd - 1), rejectRootRelative);
|
|
135
|
+
if (unsafe) return unsafe;
|
|
136
|
+
}
|
|
137
|
+
index = stringEnd - 1;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (css[index] === ")") {
|
|
141
|
+
functionStack.pop();
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (css[index] === "(") {
|
|
145
|
+
functionStack.push(null);
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (css[index] === "@") {
|
|
149
|
+
const atRule = readCSSIdentifier(css, index + 1);
|
|
150
|
+
if (atRule?.name.toLowerCase() === "import") {
|
|
151
|
+
const valueStart = skipCSSWhitespaceAndComments(css, atRule.end);
|
|
152
|
+
const importQuote = css[valueStart];
|
|
153
|
+
if (importQuote === "\"" || importQuote === "'") {
|
|
154
|
+
const valueEnd = skipCSSString(css, valueStart, importQuote);
|
|
155
|
+
const unsafe = classifyCSSResource(css.slice(valueStart + 1, valueEnd - 1), rejectRootRelative);
|
|
156
|
+
if (unsafe) return unsafe;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
const identifier = readCSSIdentifier(css, index);
|
|
162
|
+
if (!identifier || css[identifier.end] !== "(") continue;
|
|
163
|
+
const functionName = identifier.name.toLowerCase();
|
|
164
|
+
if (functionName !== "url") {
|
|
165
|
+
functionStack.push(functionName);
|
|
166
|
+
index = identifier.end;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
const valueStart = skipCSSWhitespaceAndComments(css, identifier.end + 1);
|
|
170
|
+
const urlQuote = css[valueStart];
|
|
171
|
+
const quoted = urlQuote === "\"" || urlQuote === "'";
|
|
172
|
+
let valueEnd;
|
|
173
|
+
if (quoted) {
|
|
174
|
+
valueEnd = skipCSSString(css, valueStart, urlQuote) - 1;
|
|
175
|
+
index = css.indexOf(")", valueEnd + 1);
|
|
176
|
+
} else {
|
|
177
|
+
valueEnd = valueStart;
|
|
178
|
+
while (valueEnd < css.length && css[valueEnd] !== ")") {
|
|
179
|
+
if (css[valueEnd] === "\\") valueEnd++;
|
|
180
|
+
valueEnd++;
|
|
181
|
+
}
|
|
182
|
+
index = valueEnd;
|
|
183
|
+
}
|
|
184
|
+
if (index === -1) return null;
|
|
185
|
+
const unsafe = classifyCSSResource(css.slice(valueStart + (quoted ? 1 : 0), valueEnd), rejectRootRelative);
|
|
186
|
+
if (unsafe) return unsafe;
|
|
187
|
+
}
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
function crossOriginAssetsPrefix(assetsPrefix, site) {
|
|
191
|
+
if (!assetsPrefix) return null;
|
|
192
|
+
const prefix = typeof assetsPrefix === "string" ? assetsPrefix : assetsPrefix.css || assetsPrefix.fallback;
|
|
193
|
+
if (!/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(prefix)) return null;
|
|
194
|
+
if (!site) return prefix;
|
|
195
|
+
try {
|
|
196
|
+
return (prefix.startsWith("//") ? new URL(`${site.protocol}${prefix}`) : new URL(prefix)).origin === site.origin ? null : prefix;
|
|
197
|
+
} catch {
|
|
198
|
+
return prefix;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
function validateExtractedURLs(pages, assetsPrefix, site) {
|
|
202
|
+
const externalPrefix = crossOriginAssetsPrefix(assetsPrefix, site);
|
|
203
|
+
for (const page of pages) for (const artifact of page.artifacts) {
|
|
204
|
+
const unsafe = findUnsafeCSSResource(artifact.css, externalPrefix !== null);
|
|
205
|
+
if (unsafe) {
|
|
206
|
+
const reason = unsafe.rootRelative ? `root-relative CSS URL "${unsafe.url}" would resolve against the external assetsPrefix "${externalPrefix}" instead of the page origin` : `page-relative CSS URL "${unsafe.url}" cannot preserve its target`;
|
|
207
|
+
throw new Error(`[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)"}.`);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/** Find artifacts emitted by every styled page, in the first page's order. */
|
|
212
|
+
function selectSharedArtifacts(pages) {
|
|
213
|
+
if (pages.length < 2) return [];
|
|
214
|
+
const source = pages[0].artifacts;
|
|
215
|
+
const otherIds = pages.slice(1).map((page) => new Set(page.artifacts.map(({ id }) => id)));
|
|
216
|
+
return source.filter(({ id }) => otherIds.every((ids) => ids.has(id)));
|
|
217
|
+
}
|
|
218
|
+
function stylesheetHref(base, assets, filename, assetsPrefix) {
|
|
219
|
+
const assetsPath = assets.replace(/^\/+|\/+$/g, "");
|
|
220
|
+
if (assetsPrefix) return `${(typeof assetsPrefix === "string" ? assetsPrefix : assetsPrefix.css || assetsPrefix.fallback).replace(/\/+$/g, "")}/${assetsPath}/${filename}`;
|
|
221
|
+
return `${base === "/" ? "" : `/${base.replace(/^\/+|\/+$/g, "")}`}/${assetsPath}/${filename}`;
|
|
222
|
+
}
|
|
223
|
+
function stylesheetLink(page, href) {
|
|
224
|
+
return `<link rel="stylesheet" href="${href}" data-tasty-ssr${page.styleOpen.match(/\snonce="[^"]*"/)?.[0] ?? ""}>`;
|
|
225
|
+
}
|
|
226
|
+
function transformPage(page, hrefs) {
|
|
227
|
+
const replacement = hrefs.map((href) => stylesheetLink(page, href)).join("");
|
|
228
|
+
return page.html.slice(0, page.styleStart) + replacement + page.html.slice(page.replacementEnd);
|
|
229
|
+
}
|
|
230
|
+
async function writeStylesheet(assetDir, scope, artifacts) {
|
|
231
|
+
if (artifacts.length === 0) return null;
|
|
232
|
+
const css = artifacts.map(({ css }) => css).join("\n");
|
|
233
|
+
const filename = `tasty.${scope}.${createHash("sha256").update(css).digest("hex").slice(0, 12)}.css`;
|
|
234
|
+
await writeFile(join(assetDir, filename), css);
|
|
235
|
+
return filename;
|
|
236
|
+
}
|
|
237
|
+
async function extractAstroCSS(options) {
|
|
238
|
+
const outputDir = fileURLToPath(options.dir);
|
|
239
|
+
const paths = await findHTMLFiles(outputDir);
|
|
240
|
+
const pages = (await Promise.all(paths.map(async (path) => parseExtractablePage(path, await readFile(path, "utf8"))))).filter((page) => page !== null);
|
|
241
|
+
if (pages.length === 0) return;
|
|
242
|
+
validateExtractedURLs(pages, options.assetsPrefix, options.site);
|
|
243
|
+
const shared = selectSharedArtifacts(pages);
|
|
244
|
+
const assetDir = join(outputDir, options.assets);
|
|
245
|
+
await mkdir(assetDir, { recursive: true });
|
|
246
|
+
const sharedFilename = await writeStylesheet(assetDir, "shared", shared);
|
|
247
|
+
const sharedHref = sharedFilename ? stylesheetHref(options.base, options.assets, sharedFilename, options.assetsPrefix) : null;
|
|
248
|
+
const sharedIds = new Set(shared.map(({ id }) => id));
|
|
249
|
+
for (const page of pages) {
|
|
250
|
+
const pageFilename = await writeStylesheet(assetDir, "page", page.artifacts.filter(({ id }) => !sharedIds.has(id)));
|
|
251
|
+
const hrefs = sharedHref ? [sharedHref] : [];
|
|
252
|
+
if (pageFilename) hrefs.push(stylesheetHref(options.base, options.assets, pageFilename, options.assetsPrefix));
|
|
253
|
+
await writeFile(page.path, transformPage(page, hrefs));
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
//#endregion
|
|
257
|
+
//#region src/ssr/astro.ts
|
|
258
|
+
/**
|
|
259
|
+
* Astro integration for Tasty SSR.
|
|
260
|
+
*
|
|
261
|
+
* Provides:
|
|
262
|
+
* - tastyIntegration() — Astro Integration API (recommended)
|
|
263
|
+
* - tastyMiddleware() — manual middleware for advanced composition
|
|
264
|
+
*
|
|
265
|
+
* Import from '@tenphi/tasty/ssr/astro'.
|
|
266
|
+
*/
|
|
267
|
+
registerSSRCollectorGetterGlobal(getSSRCollector);
|
|
268
|
+
/**
|
|
269
|
+
* Create an Astro middleware that collects Tasty styles during SSR.
|
|
270
|
+
*
|
|
271
|
+
* All React components rendered during the request will have their
|
|
272
|
+
* computeStyles() calls captured by the collector via AsyncLocalStorage.
|
|
273
|
+
* After rendering, the middleware injects the collected CSS into </head>.
|
|
274
|
+
*
|
|
275
|
+
* @example Manual middleware setup
|
|
276
|
+
* ```ts
|
|
277
|
+
* // src/middleware.ts
|
|
278
|
+
* import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';
|
|
279
|
+
* export const onRequest = tastyMiddleware();
|
|
280
|
+
* ```
|
|
281
|
+
*
|
|
282
|
+
* @example Composing with other middleware
|
|
283
|
+
* ```ts
|
|
284
|
+
* // src/middleware.ts
|
|
285
|
+
* import { sequence } from 'astro:middleware';
|
|
286
|
+
* import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';
|
|
287
|
+
*
|
|
288
|
+
* export const onRequest = sequence(
|
|
289
|
+
* tastyMiddleware(),
|
|
290
|
+
* myOtherMiddleware,
|
|
291
|
+
* );
|
|
292
|
+
* ```
|
|
293
|
+
*/
|
|
294
|
+
function tastyMiddleware(options) {
|
|
295
|
+
const internalOptions = options;
|
|
296
|
+
return async (context, next) => {
|
|
297
|
+
const transferCache = options?.transferCache ?? true;
|
|
298
|
+
const extractionMetadata = internalOptions?.extractionMetadata === true && context.isPrerendered === true;
|
|
299
|
+
const collector = new ServerStyleCollector();
|
|
300
|
+
const rendered = await runWithCollector(collector, async () => {
|
|
301
|
+
const response = await next();
|
|
302
|
+
const body = response.body;
|
|
303
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
304
|
+
if (!body || !contentType.includes("text/html")) return { response };
|
|
305
|
+
const reader = body.pipeThrough(new TextDecoderStream()).getReader();
|
|
306
|
+
const parts = [];
|
|
307
|
+
for (;;) {
|
|
308
|
+
const { done, value } = await reader.read();
|
|
309
|
+
if (done) break;
|
|
310
|
+
parts.push(value);
|
|
311
|
+
}
|
|
312
|
+
return {
|
|
313
|
+
html: parts.join(""),
|
|
314
|
+
status: response.status,
|
|
315
|
+
headers: response.headers
|
|
316
|
+
};
|
|
317
|
+
});
|
|
318
|
+
if ("response" in rendered) return rendered.response;
|
|
319
|
+
if (!rendered.html) return new Response(null, {
|
|
320
|
+
status: rendered.status,
|
|
321
|
+
headers: rendered.headers
|
|
322
|
+
});
|
|
323
|
+
let { html } = rendered;
|
|
324
|
+
const css = collector.getCSS();
|
|
325
|
+
if (!css) return new Response(html, {
|
|
326
|
+
status: rendered.status,
|
|
327
|
+
headers: rendered.headers
|
|
328
|
+
});
|
|
329
|
+
const nonce = getConfig().nonce;
|
|
330
|
+
const nonceAttr = nonce ? ` nonce="${nonce}"` : "";
|
|
331
|
+
const styleTag = `<style data-tasty-ssr${nonceAttr}>${css}</style>`;
|
|
332
|
+
const metadataTag = extractionMetadata ? createExtractionMetadata(collector.getArtifacts()) : "";
|
|
333
|
+
let cacheTag = "";
|
|
334
|
+
if (transferCache) {
|
|
335
|
+
const classNames = collector.getRenderedClassNames();
|
|
336
|
+
if (classNames.length > 0) cacheTag = `<script${nonceAttr}>(window.__TASTY__=window.__TASTY__||[]).push(${classNames.map((n) => `"${n}"`).join(",")})<\/script>`;
|
|
337
|
+
}
|
|
338
|
+
const injection = styleTag + metadataTag + cacheTag;
|
|
339
|
+
const idx = html.indexOf("</head>");
|
|
340
|
+
if (idx !== -1) html = html.slice(0, idx) + injection + html.slice(idx);
|
|
341
|
+
else html = injection + html;
|
|
342
|
+
const headers = new Headers(rendered.headers);
|
|
343
|
+
headers.delete("content-length");
|
|
344
|
+
return new Response(html, {
|
|
345
|
+
status: rendered.status,
|
|
346
|
+
headers
|
|
347
|
+
});
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Package subpaths of the middleware entrypoints registered by
|
|
352
|
+
* `tastyIntegration()`.
|
|
353
|
+
*
|
|
354
|
+
* These must be bare specifiers rather than
|
|
355
|
+
* `new URL('./astro-middleware.js', import.meta.url)`. The bundler is free to
|
|
356
|
+
* hoist `tastyIntegration` into a shared chunk at a different directory depth
|
|
357
|
+
* than `dist/ssr/`, which makes a relative URL resolve to a file that does not
|
|
358
|
+
* exist and breaks the build for every consumer. A package subpath is resolved
|
|
359
|
+
* by the consumer through our `exports` map, so it never depends on the
|
|
360
|
+
* chunk layout.
|
|
361
|
+
*
|
|
362
|
+
* There are separate entrypoints instead of one parameterised entrypoint because
|
|
363
|
+
* `addMiddleware()` cannot pass options: the integration runs when the Astro
|
|
364
|
+
* config is loaded, while the middleware module is evaluated in the server
|
|
365
|
+
* runtime — a different process for built output — so module-level state set
|
|
366
|
+
* by the integration is not visible to the middleware.
|
|
367
|
+
*/
|
|
368
|
+
const MIDDLEWARE_ENTRYPOINT = "@tenphi/tasty/ssr/astro-middleware";
|
|
369
|
+
const MIDDLEWARE_ENTRYPOINT_STATIC = "@tenphi/tasty/ssr/astro-middleware-static";
|
|
370
|
+
const MIDDLEWARE_ENTRYPOINT_EXTRACT = "@tenphi/tasty/ssr/astro-middleware-extract";
|
|
371
|
+
const MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC = "@tenphi/tasty/ssr/astro-middleware-extract-static";
|
|
372
|
+
/**
|
|
373
|
+
* Astro integration that automatically sets up Tasty SSR.
|
|
374
|
+
*
|
|
375
|
+
* Registers middleware for cross-component CSS deduplication and
|
|
376
|
+
* optionally injects a client hydration script for island support.
|
|
377
|
+
*
|
|
378
|
+
* @example Basic setup (with islands)
|
|
379
|
+
* ```ts
|
|
380
|
+
* // astro.config.mjs
|
|
381
|
+
* import { tastyIntegration } from '@tenphi/tasty/ssr/astro';
|
|
382
|
+
*
|
|
383
|
+
* export default defineConfig({
|
|
384
|
+
* integrations: [tastyIntegration()],
|
|
385
|
+
* });
|
|
386
|
+
* ```
|
|
387
|
+
*
|
|
388
|
+
* @example Static-only (no client JS)
|
|
389
|
+
* ```ts
|
|
390
|
+
* // astro.config.mjs
|
|
391
|
+
* import { tastyIntegration } from '@tenphi/tasty/ssr/astro';
|
|
392
|
+
*
|
|
393
|
+
* export default defineConfig({
|
|
394
|
+
* integrations: [tastyIntegration({ islands: false })],
|
|
395
|
+
* });
|
|
396
|
+
* ```
|
|
397
|
+
*/
|
|
398
|
+
function tastyIntegration(options) {
|
|
399
|
+
const { islands = true } = options ?? {};
|
|
400
|
+
const cssMode = options?.css?.mode ?? "inline";
|
|
401
|
+
let base = "/";
|
|
402
|
+
let assets = "_astro";
|
|
403
|
+
let assetsPrefix;
|
|
404
|
+
let site;
|
|
405
|
+
return {
|
|
406
|
+
name: "@tenphi/tasty",
|
|
407
|
+
hooks: {
|
|
408
|
+
"astro:config:setup": ({ addMiddleware, injectScript }) => {
|
|
409
|
+
addMiddleware({
|
|
410
|
+
entrypoint: cssMode === "extract" ? islands ? MIDDLEWARE_ENTRYPOINT_EXTRACT : MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC : islands ? MIDDLEWARE_ENTRYPOINT : MIDDLEWARE_ENTRYPOINT_STATIC,
|
|
411
|
+
order: "pre"
|
|
412
|
+
});
|
|
413
|
+
if (islands) injectScript("before-hydration", `import "@tenphi/tasty/ssr/astro-client";`);
|
|
414
|
+
},
|
|
415
|
+
"astro:config:done": ({ config }) => {
|
|
416
|
+
base = config.base ?? "/";
|
|
417
|
+
assets = config.build?.assets ?? "_astro";
|
|
418
|
+
assetsPrefix = config.build?.assetsPrefix;
|
|
419
|
+
site = config.site;
|
|
420
|
+
},
|
|
421
|
+
"astro:build:done": async ({ dir }) => {
|
|
422
|
+
if (cssMode !== "extract") return;
|
|
423
|
+
await extractAstroCSS({
|
|
424
|
+
dir,
|
|
425
|
+
base,
|
|
426
|
+
assets,
|
|
427
|
+
assetsPrefix,
|
|
428
|
+
site
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
//#endregion
|
|
435
|
+
export { tastyMiddleware as n, tastyIntegration as t };
|
|
436
|
+
|
|
437
|
+
//# sourceMappingURL=astro-CzY4LCpr.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"astro-CzY4LCpr.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';\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 skipCSSString(css: string, start: number, quote: string): number {\n for (let index = start + 1; index < css.length; index++) {\n if (css[index] === '\\\\') {\n index++;\n } else if (css[index] === quote) {\n return index + 1;\n }\n }\n return css.length;\n}\n\nfunction decodeCSSEscapes(value: string): string {\n return value.replace(\n /\\\\(?:([\\da-f]{1,6})\\s?|\\r\\n|[\\n\\r\\f]|(.))/gi,\n (_match, hex: string | undefined, escaped: string | undefined) => {\n if (hex) {\n const codePoint = Number.parseInt(hex, 16);\n return codePoint === 0 || codePoint > 0x10ffff\n ? '\\ufffd'\n : String.fromCodePoint(codePoint);\n }\n return escaped ?? '';\n },\n );\n}\n\nfunction readCSSIdentifier(\n css: string,\n start: number,\n): { name: string; end: number } | null {\n let name = '';\n let index = start;\n\n while (index < css.length) {\n const char = css[index];\n if (/[-_a-z\\d]/i.test(char) || char.charCodeAt(0) >= 0x80) {\n name += char;\n index++;\n continue;\n }\n if (char !== '\\\\' || index + 1 >= css.length) break;\n\n const hex = css.slice(index + 1).match(/^[\\da-f]{1,6}/i)?.[0];\n if (hex) {\n name += decodeCSSEscapes(`\\\\${hex}`);\n index += hex.length + 1;\n if (/\\s/.test(css[index] ?? '')) index++;\n continue;\n }\n\n if (/\\r|\\n|\\f/.test(css[index + 1])) break;\n name += css[index + 1];\n index += 2;\n }\n\n return index === start ? null : { name, end: index };\n}\n\nfunction skipCSSWhitespaceAndComments(css: string, start: number): number {\n let index = start;\n for (;;) {\n while (/\\s/.test(css[index] ?? '')) index++;\n if (css[index] !== '/' || css[index + 1] !== '*') return index;\n const commentEnd = css.indexOf('*/', index + 2);\n if (commentEnd === -1) return css.length;\n index = commentEnd + 2;\n }\n}\n\ninterface UnsafeCSSResource {\n url: string;\n rootRelative: boolean;\n}\n\nfunction classifyCSSResource(\n rawURL: string,\n rejectRootRelative: boolean,\n): UnsafeCSSResource | null {\n const url = decodeCSSEscapes(rawURL).trim();\n if (!url || url.startsWith('//') || /^[a-z][a-z\\d+.-]*:/i.test(url)) {\n return null;\n }\n if (url.startsWith('/')) {\n return rejectRootRelative ? { url: rawURL, rootRelative: true } : null;\n }\n return { url: rawURL, rootRelative: false };\n}\n\nfunction findUnsafeCSSResource(\n css: string,\n rejectRootRelative: boolean,\n): UnsafeCSSResource | null {\n const functionStack: (string | null)[] = [];\n const stringResourceFunctions = new Set([\n 'image',\n 'image-set',\n '-webkit-image-set',\n 'src',\n ]);\n\n for (let index = 0; index < css.length; index++) {\n if (css[index] === '/' && css[index + 1] === '*') {\n const commentEnd = css.indexOf('*/', index + 2);\n index = commentEnd === -1 ? css.length : commentEnd + 1;\n continue;\n }\n\n const quote = css[index];\n if (quote === '\"' || quote === \"'\") {\n const stringEnd = skipCSSString(css, index, quote);\n if (stringResourceFunctions.has(functionStack.at(-1) ?? '')) {\n const unsafe = classifyCSSResource(\n css.slice(index + 1, stringEnd - 1),\n rejectRootRelative,\n );\n if (unsafe) return unsafe;\n }\n index = stringEnd - 1;\n continue;\n }\n\n if (css[index] === ')') {\n functionStack.pop();\n continue;\n }\n\n if (css[index] === '(') {\n functionStack.push(null);\n continue;\n }\n\n if (css[index] === '@') {\n const atRule = readCSSIdentifier(css, index + 1);\n if (atRule?.name.toLowerCase() === 'import') {\n const valueStart = skipCSSWhitespaceAndComments(css, atRule.end);\n const importQuote = css[valueStart];\n if (importQuote === '\"' || importQuote === \"'\") {\n const valueEnd = skipCSSString(css, valueStart, importQuote);\n const unsafe = classifyCSSResource(\n css.slice(valueStart + 1, valueEnd - 1),\n rejectRootRelative,\n );\n if (unsafe) return unsafe;\n }\n }\n continue;\n }\n\n const identifier = readCSSIdentifier(css, index);\n if (!identifier || css[identifier.end] !== '(') continue;\n\n const functionName = identifier.name.toLowerCase();\n if (functionName !== 'url') {\n functionStack.push(functionName);\n index = identifier.end;\n continue;\n }\n\n const valueStart = skipCSSWhitespaceAndComments(css, identifier.end + 1);\n const urlQuote = css[valueStart];\n const quoted = urlQuote === '\"' || urlQuote === \"'\";\n let valueEnd: number;\n if (quoted) {\n valueEnd = skipCSSString(css, valueStart, urlQuote) - 1;\n index = css.indexOf(')', valueEnd + 1);\n } else {\n valueEnd = valueStart;\n while (valueEnd < css.length && css[valueEnd] !== ')') {\n if (css[valueEnd] === '\\\\') valueEnd++;\n valueEnd++;\n }\n index = valueEnd;\n }\n\n if (index === -1) return null;\n const unsafe = classifyCSSResource(\n css.slice(valueStart + (quoted ? 1 : 0), valueEnd),\n rejectRootRelative,\n );\n if (unsafe) return unsafe;\n }\n\n return null;\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 { getConfig } from '../config';\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 = getConfig().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":";;;;;;;;;AAOA,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,QAAQ,KAAK,UAAU;CACjD,MAAM,WAAW,KAAK,QAAQ,YAAY,eAAe,CAAC;CAC1D,IACE,iBAAiB,MACjB,aAAa,MACb,WAAW,MAAsB,eAEjC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.js";
|
|
2
2
|
import { PluginPass } from "@babel/core";
|
|
3
3
|
|
|
4
4
|
//#region src/zero/babel-types.d.ts
|
|
@@ -80,4 +80,4 @@ interface TastyZeroBabelOptions {
|
|
|
80
80
|
declare const _default: (api: object, options: TastyZeroBabelOptions | null | undefined, dirname: string) => import("@babel/core").PluginObj<PluginPass>;
|
|
81
81
|
//#endregion
|
|
82
82
|
export { _default as n, TastyZeroConfig as r, TastyZeroBabelOptions as t };
|
|
83
|
-
//# sourceMappingURL=babel-
|
|
83
|
+
//# sourceMappingURL=babel-DWCsafYw.d.ts.map
|
|
@@ -1,6 +1,15 @@
|
|
|
1
|
-
import { n as StyleResult } from "./index-
|
|
1
|
+
import { n as StyleResult } from "./index-BmogEzTo.js";
|
|
2
2
|
|
|
3
3
|
//#region src/ssr/collector.d.ts
|
|
4
|
+
type ServerStyleArtifactKind = 'property' | 'font-face' | 'counter-style' | 'function' | 'raw' | 'global' | 'chunk' | 'keyframes';
|
|
5
|
+
interface ServerStyleArtifact {
|
|
6
|
+
/** Stable identifier derived from the artifact kind, logical key, and CSS. */
|
|
7
|
+
id: string;
|
|
8
|
+
kind: ServerStyleArtifactKind;
|
|
9
|
+
css: string;
|
|
10
|
+
/** Zero-based position in the collector's final cascade order. */
|
|
11
|
+
order: number;
|
|
12
|
+
}
|
|
4
13
|
declare class ServerStyleCollector {
|
|
5
14
|
private chunks;
|
|
6
15
|
private cacheKeyToClassName;
|
|
@@ -105,6 +114,15 @@ declare class ServerStyleCollector {
|
|
|
105
114
|
* write must win to match the client's update-tracking behavior.
|
|
106
115
|
*/
|
|
107
116
|
collectRawCSS(key: string, css: string, replace?: boolean): void;
|
|
117
|
+
/**
|
|
118
|
+
* Return the collected CSS as structured, ordered artifacts.
|
|
119
|
+
*
|
|
120
|
+
* Artifact boundaries are part of the collector output so build tools never
|
|
121
|
+
* need to split or parse CSS text. IDs include the logical collection key
|
|
122
|
+
* and content, making them stable across equivalent page renders while a CSS
|
|
123
|
+
* change always produces a different ID.
|
|
124
|
+
*/
|
|
125
|
+
getArtifacts(): ServerStyleArtifact[];
|
|
108
126
|
/**
|
|
109
127
|
* Extract all CSS collected so far as a single string.
|
|
110
128
|
* Includes @property and @keyframes rules.
|
|
@@ -141,5 +159,5 @@ declare class ServerStyleCollector {
|
|
|
141
159
|
*/
|
|
142
160
|
declare function createServerStyleCollector(namePrefix?: string): ServerStyleCollector;
|
|
143
161
|
//#endregion
|
|
144
|
-
export { createServerStyleCollector as n, ServerStyleCollector as t };
|
|
145
|
-
//# sourceMappingURL=collector-
|
|
162
|
+
export { createServerStyleCollector as i, ServerStyleArtifactKind as n, ServerStyleCollector as r, ServerStyleArtifact as t };
|
|
163
|
+
//# sourceMappingURL=collector-BTVXj2hS.d.ts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { L as renderStyles, Mt as formatFunctionRule, Pt as parseFunctionName, X as fontFaceContentHash, Z as formatFontFaceRule, _t as hashString, a as getGlobalCounterStyles, d as getGlobalStyles, f as getNamePrefix, ft as makeClassName, gt as validateNamePrefix, i as getGlobalConfigTokens, mt as makeKeyframeName, o as getGlobalFontFaces, pt as makeCounterStyleName, q as formatCounterStyleRule, r as getEffectiveProperties, s as getGlobalFunctions } from "./config-
|
|
2
|
-
import { n as formatPropertyCSS, t as formatRules } from "./format-rules-
|
|
1
|
+
import { L as renderStyles, Mt as formatFunctionRule, Pt as parseFunctionName, X as fontFaceContentHash, Z as formatFontFaceRule, _t as hashString, a as getGlobalCounterStyles, d as getGlobalStyles, f as getNamePrefix, ft as makeClassName, gt as validateNamePrefix, i as getGlobalConfigTokens, mt as makeKeyframeName, o as getGlobalFontFaces, pt as makeCounterStyleName, q as formatCounterStyleRule, r as getEffectiveProperties, s as getGlobalFunctions } from "./config-B3gPdCqd.js";
|
|
2
|
+
import { n as formatPropertyCSS, t as formatRules } from "./format-rules-rCZ37rqY.js";
|
|
3
3
|
import { t as formatGlobalRules } from "./format-global-rules-DklyaXv-.js";
|
|
4
4
|
//#region src/ssr/collector.ts
|
|
5
5
|
/**
|
|
@@ -14,6 +14,10 @@ import { t as formatGlobalRules } from "./format-global-rules-DklyaXv-.js";
|
|
|
14
14
|
* One instance is created per HTTP request. Concurrent requests
|
|
15
15
|
* each get their own collector (via AsyncLocalStorage or React context).
|
|
16
16
|
*/
|
|
17
|
+
function artifactId(kind, key, css) {
|
|
18
|
+
const content = `${kind}\0${key}\0${css}`;
|
|
19
|
+
return `${kind}:${hashString(content)}:${content.length.toString(36)}`;
|
|
20
|
+
}
|
|
17
21
|
var ServerStyleCollector = class {
|
|
18
22
|
chunks = /* @__PURE__ */ new Map();
|
|
19
23
|
cacheKeyToClassName = /* @__PURE__ */ new Map();
|
|
@@ -209,21 +213,40 @@ var ServerStyleCollector = class {
|
|
|
209
213
|
if (replace || !this.rawCSS.has(key)) this.rawCSS.set(key, css);
|
|
210
214
|
}
|
|
211
215
|
/**
|
|
216
|
+
* Return the collected CSS as structured, ordered artifacts.
|
|
217
|
+
*
|
|
218
|
+
* Artifact boundaries are part of the collector output so build tools never
|
|
219
|
+
* need to split or parse CSS text. IDs include the logical collection key
|
|
220
|
+
* and content, making them stable across equivalent page renders while a CSS
|
|
221
|
+
* change always produces a different ID.
|
|
222
|
+
*/
|
|
223
|
+
getArtifacts() {
|
|
224
|
+
const artifacts = [];
|
|
225
|
+
const append = (kind, entries) => {
|
|
226
|
+
for (const [key, css] of entries) artifacts.push({
|
|
227
|
+
id: artifactId(kind, key, css),
|
|
228
|
+
kind,
|
|
229
|
+
css,
|
|
230
|
+
order: artifacts.length
|
|
231
|
+
});
|
|
232
|
+
};
|
|
233
|
+
append("property", this.propertyRules);
|
|
234
|
+
append("font-face", this.fontFaceRules);
|
|
235
|
+
append("counter-style", this.counterStyleRules);
|
|
236
|
+
append("function", this.functionRules);
|
|
237
|
+
append("raw", this.rawCSS);
|
|
238
|
+
append("global", this.globalStyles);
|
|
239
|
+
append("chunk", this.chunks);
|
|
240
|
+
append("keyframes", this.keyframeRules);
|
|
241
|
+
return artifacts;
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
212
244
|
* Extract all CSS collected so far as a single string.
|
|
213
245
|
* Includes @property and @keyframes rules.
|
|
214
246
|
* Used for non-streaming SSR (renderToString).
|
|
215
247
|
*/
|
|
216
248
|
getCSS() {
|
|
217
|
-
|
|
218
|
-
for (const css of this.propertyRules.values()) parts.push(css);
|
|
219
|
-
for (const css of this.fontFaceRules.values()) parts.push(css);
|
|
220
|
-
for (const css of this.counterStyleRules.values()) parts.push(css);
|
|
221
|
-
for (const css of this.functionRules.values()) parts.push(css);
|
|
222
|
-
for (const css of this.rawCSS.values()) parts.push(css);
|
|
223
|
-
for (const css of this.globalStyles.values()) parts.push(css);
|
|
224
|
-
for (const css of this.chunks.values()) parts.push(css);
|
|
225
|
-
for (const css of this.keyframeRules.values()) parts.push(css);
|
|
226
|
-
return parts.join("\n");
|
|
249
|
+
return this.getArtifacts().map(({ css }) => css).join("\n");
|
|
227
250
|
}
|
|
228
251
|
/**
|
|
229
252
|
* Flush only newly collected CSS since the last flush.
|
|
@@ -301,4 +324,4 @@ function createServerStyleCollector(namePrefix) {
|
|
|
301
324
|
//#endregion
|
|
302
325
|
export { createServerStyleCollector as n, ServerStyleCollector as t };
|
|
303
326
|
|
|
304
|
-
//# sourceMappingURL=collector-
|
|
327
|
+
//# sourceMappingURL=collector-C6TtL8HJ.js.map
|