@tenphi/tasty 0.0.0-snapshot.fdb16ea → 0.0.0-snapshot.fde6cf3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/astro-Dj8YpRd7.js +301 -0
- package/dist/astro-Dj8YpRd7.js.map +1 -0
- package/dist/{babel-CMYf4JZ2.d.ts → babel-Cbp2C2bj.d.ts} +2 -2
- package/dist/{collector-Ctn5s74s.d.ts → collector-DBY6liC2.d.ts} +94 -11
- package/dist/collector-NjmUiB8f.js +529 -0
- package/dist/collector-NjmUiB8f.js.map +1 -0
- package/dist/{config-B23gZrfP.js → config-Bd2vOF0Z.js} +454 -105
- package/dist/config-Bd2vOF0Z.js.map +1 -0
- package/dist/{config-CZx8_DCu.d.ts → config-CA7iAlEI.d.ts} +112 -22
- package/dist/core/index.d.ts +5 -5
- package/dist/core/index.js +6 -6
- package/dist/{core-B1tyn69d.js → core-ClInK6YG.js} +386 -107
- package/dist/core-ClInK6YG.js.map +1 -0
- package/dist/css-resources-Cyl_axbI.js +149 -0
- package/dist/css-resources-Cyl_axbI.js.map +1 -0
- package/dist/{css-writer-CvAxkR6S.js → css-writer-BDQXG9Jo.js} +3 -3
- package/dist/{css-writer-CvAxkR6S.js.map → css-writer-BDQXG9Jo.js.map} +1 -1
- package/dist/{format-rules-BCTWVvcS.js → format-rules-CGhgoVLR.js} +22 -32
- package/dist/format-rules-CGhgoVLR.js.map +1 -0
- package/dist/{hydrate-BCPvkJj3.js → hydrate-CqbxwVh_.js} +2 -2
- package/dist/{hydrate-BCPvkJj3.js.map → hydrate-CqbxwVh_.js.map} +1 -1
- package/dist/{index-B3o0aCYV.d.ts → index-C8RFYeFW.d.ts} +61 -12
- package/dist/{index-CsvB0EXZ.d.ts → index-FpYK0H5g.d.ts} +49 -8
- package/dist/index.d.ts +5 -5
- package/dist/index.js +43 -27
- package/dist/index.js.map +1 -1
- package/dist/{keyframes-Dxdx3KOo.js → keyframes-BjfNVhaB.js} +45 -3
- package/dist/keyframes-BjfNVhaB.js.map +1 -0
- package/dist/{merge-styles-DJTSfz_M.d.ts → merge-styles-BQv7d3fx.d.ts} +2 -2
- package/dist/{merge-styles-C-uwpoNW.js → merge-styles-BbJhjesV.js} +2 -2
- package/dist/{merge-styles-C-uwpoNW.js.map → merge-styles-BbJhjesV.js.map} +1 -1
- package/dist/precompile/index.d.ts +11 -0
- package/dist/precompile/index.js +72 -0
- package/dist/precompile/index.js.map +1 -0
- package/dist/precompile/register.d.ts +13 -0
- package/dist/precompile/register.js +2 -0
- package/dist/register-BkC-8Zuy.js +333 -0
- package/dist/register-BkC-8Zuy.js.map +1 -0
- package/dist/{resolve-recipes-BuOvSEa2.js → resolve-recipes-B2Sf36AH.js} +3 -3
- package/dist/{resolve-recipes-BuOvSEa2.js.map → resolve-recipes-B2Sf36AH.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-config.d.ts +66 -0
- package/dist/ssr/next-config.js +115 -0
- package/dist/ssr/next-config.js.map +1 -0
- package/dist/ssr/next.d.ts +9 -2
- package/dist/ssr/next.js +26 -9
- package/dist/ssr/next.js.map +1 -1
- package/dist/ssr-collector-ref-COs_ioWl.js +29 -0
- package/dist/ssr-collector-ref-COs_ioWl.js.map +1 -0
- package/dist/static/index.d.ts +2 -2
- package/dist/static/index.js +1 -1
- package/dist/types-Bo5ePLZh.d.ts +111 -0
- 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 +3 -1
- package/docs/debug.md +17 -6
- package/docs/injector.md +23 -3
- package/docs/precompile.md +202 -0
- package/docs/runtime-benchmarks.md +143 -72
- package/docs/ssr.md +179 -20
- package/package.json +44 -10
- package/dist/collector-DMSR6ANK.js +0 -304
- package/dist/collector-DMSR6ANK.js.map +0 -1
- package/dist/config-B23gZrfP.js.map +0 -1
- package/dist/core-B1tyn69d.js.map +0 -1
- package/dist/format-rules-BCTWVvcS.js.map +0 -1
- package/dist/keyframes-Dxdx3KOo.js.map +0 -1
- package/dist/ssr/astro.js.map +0 -1
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { n as getConfig } from "./config-Bd2vOF0Z.js";
|
|
2
|
+
import { r as registerSSRCollectorGetterGlobal } from "./ssr-collector-ref-COs_ioWl.js";
|
|
3
|
+
import { t as ServerStyleCollector } from "./collector-NjmUiB8f.js";
|
|
4
|
+
import { n as runWithCollector, t as getSSRCollector } from "./async-storage-DKK-wTD4.js";
|
|
5
|
+
import { t as findUnsafeCSSResource } from "./css-resources-Cyl_axbI.js";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
//#region src/ssr/astro-extraction.ts
|
|
11
|
+
const METADATA_START = "<template data-tasty-extract>";
|
|
12
|
+
const METADATA_END = "</template>";
|
|
13
|
+
function createExtractionMetadata(artifacts) {
|
|
14
|
+
return `${METADATA_START}${Buffer.from(JSON.stringify(artifacts), "utf8").toString("base64")}${METADATA_END}`;
|
|
15
|
+
}
|
|
16
|
+
function parseExtractablePage(path, html) {
|
|
17
|
+
const metadataStart = html.indexOf(METADATA_START);
|
|
18
|
+
if (metadataStart === -1) return null;
|
|
19
|
+
const metadataContentStart = metadataStart + 29;
|
|
20
|
+
const metadataEnd = html.indexOf(METADATA_END, metadataContentStart);
|
|
21
|
+
if (metadataEnd === -1) return null;
|
|
22
|
+
const encoded = html.slice(metadataContentStart, metadataEnd);
|
|
23
|
+
let artifacts;
|
|
24
|
+
try {
|
|
25
|
+
artifacts = JSON.parse(Buffer.from(encoded, "base64").toString("utf8"));
|
|
26
|
+
} catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
const styleStart = html.lastIndexOf("<style data-tasty-ssr", metadataStart);
|
|
30
|
+
if (styleStart === -1) return null;
|
|
31
|
+
const styleOpenEnd = html.indexOf(">", styleStart);
|
|
32
|
+
const styleEnd = html.indexOf("</style>", styleOpenEnd + 1);
|
|
33
|
+
if (styleOpenEnd === -1 || styleEnd === -1 || styleEnd + 8 !== metadataStart) return null;
|
|
34
|
+
return {
|
|
35
|
+
path,
|
|
36
|
+
html,
|
|
37
|
+
artifacts,
|
|
38
|
+
styleStart,
|
|
39
|
+
replacementEnd: metadataEnd + 11,
|
|
40
|
+
styleOpen: html.slice(styleStart, styleOpenEnd + 1)
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
async function findHTMLFiles(dir) {
|
|
44
|
+
const paths = [];
|
|
45
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
46
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
47
|
+
for (const entry of entries) {
|
|
48
|
+
const path = join(dir, entry.name);
|
|
49
|
+
if (entry.isDirectory()) paths.push(...await findHTMLFiles(path));
|
|
50
|
+
else if (entry.isFile() && entry.name.endsWith(".html")) paths.push(path);
|
|
51
|
+
}
|
|
52
|
+
return paths;
|
|
53
|
+
}
|
|
54
|
+
function crossOriginAssetsPrefix(assetsPrefix, site) {
|
|
55
|
+
if (!assetsPrefix) return null;
|
|
56
|
+
const prefix = typeof assetsPrefix === "string" ? assetsPrefix : assetsPrefix.css || assetsPrefix.fallback;
|
|
57
|
+
if (!/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(prefix)) return null;
|
|
58
|
+
if (!site) return prefix;
|
|
59
|
+
try {
|
|
60
|
+
return (prefix.startsWith("//") ? new URL(`${site.protocol}${prefix}`) : new URL(prefix)).origin === site.origin ? null : prefix;
|
|
61
|
+
} catch {
|
|
62
|
+
return prefix;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function validateExtractedURLs(pages, assetsPrefix, site) {
|
|
66
|
+
const externalPrefix = crossOriginAssetsPrefix(assetsPrefix, site);
|
|
67
|
+
for (const page of pages) for (const artifact of page.artifacts) {
|
|
68
|
+
const unsafe = findUnsafeCSSResource(artifact.css, externalPrefix !== null);
|
|
69
|
+
if (unsafe) {
|
|
70
|
+
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`;
|
|
71
|
+
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)"}.`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** Find artifacts emitted by every styled page, in the first page's order. */
|
|
76
|
+
function selectSharedArtifacts(pages) {
|
|
77
|
+
if (pages.length < 2) return [];
|
|
78
|
+
const source = pages[0].artifacts;
|
|
79
|
+
const otherIds = pages.slice(1).map((page) => new Set(page.artifacts.map(({ id }) => id)));
|
|
80
|
+
return source.filter(({ id }) => otherIds.every((ids) => ids.has(id)));
|
|
81
|
+
}
|
|
82
|
+
function stylesheetHref(base, assets, filename, assetsPrefix) {
|
|
83
|
+
const assetsPath = assets.replace(/^\/+|\/+$/g, "");
|
|
84
|
+
if (assetsPrefix) return `${(typeof assetsPrefix === "string" ? assetsPrefix : assetsPrefix.css || assetsPrefix.fallback).replace(/\/+$/g, "")}/${assetsPath}/${filename}`;
|
|
85
|
+
return `${base === "/" ? "" : `/${base.replace(/^\/+|\/+$/g, "")}`}/${assetsPath}/${filename}`;
|
|
86
|
+
}
|
|
87
|
+
function stylesheetLink(page, href) {
|
|
88
|
+
return `<link rel="stylesheet" href="${href}" data-tasty-ssr${page.styleOpen.match(/\snonce="[^"]*"/)?.[0] ?? ""}>`;
|
|
89
|
+
}
|
|
90
|
+
function transformPage(page, hrefs) {
|
|
91
|
+
const replacement = hrefs.map((href) => stylesheetLink(page, href)).join("");
|
|
92
|
+
return page.html.slice(0, page.styleStart) + replacement + page.html.slice(page.replacementEnd);
|
|
93
|
+
}
|
|
94
|
+
async function writeStylesheet(assetDir, scope, artifacts) {
|
|
95
|
+
if (artifacts.length === 0) return null;
|
|
96
|
+
const css = artifacts.map(({ css }) => css).join("\n");
|
|
97
|
+
const filename = `tasty.${scope}.${createHash("sha256").update(css).digest("hex").slice(0, 12)}.css`;
|
|
98
|
+
await writeFile(join(assetDir, filename), css);
|
|
99
|
+
return filename;
|
|
100
|
+
}
|
|
101
|
+
async function extractAstroCSS(options) {
|
|
102
|
+
const outputDir = fileURLToPath(options.dir);
|
|
103
|
+
const paths = await findHTMLFiles(outputDir);
|
|
104
|
+
const pages = (await Promise.all(paths.map(async (path) => parseExtractablePage(path, await readFile(path, "utf8"))))).filter((page) => page !== null);
|
|
105
|
+
if (pages.length === 0) return;
|
|
106
|
+
validateExtractedURLs(pages, options.assetsPrefix, options.site);
|
|
107
|
+
const shared = selectSharedArtifacts(pages);
|
|
108
|
+
const assetDir = join(outputDir, options.assets);
|
|
109
|
+
await mkdir(assetDir, { recursive: true });
|
|
110
|
+
const sharedFilename = await writeStylesheet(assetDir, "shared", shared);
|
|
111
|
+
const sharedHref = sharedFilename ? stylesheetHref(options.base, options.assets, sharedFilename, options.assetsPrefix) : null;
|
|
112
|
+
const sharedIds = new Set(shared.map(({ id }) => id));
|
|
113
|
+
for (const page of pages) {
|
|
114
|
+
const pageFilename = await writeStylesheet(assetDir, "page", page.artifacts.filter(({ id }) => !sharedIds.has(id)));
|
|
115
|
+
const hrefs = sharedHref ? [sharedHref] : [];
|
|
116
|
+
if (pageFilename) hrefs.push(stylesheetHref(options.base, options.assets, pageFilename, options.assetsPrefix));
|
|
117
|
+
await writeFile(page.path, transformPage(page, hrefs));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
//#endregion
|
|
121
|
+
//#region src/ssr/astro.ts
|
|
122
|
+
/**
|
|
123
|
+
* Astro integration for Tasty SSR.
|
|
124
|
+
*
|
|
125
|
+
* Provides:
|
|
126
|
+
* - tastyIntegration() — Astro Integration API (recommended)
|
|
127
|
+
* - tastyMiddleware() — manual middleware for advanced composition
|
|
128
|
+
*
|
|
129
|
+
* Import from '@tenphi/tasty/ssr/astro'.
|
|
130
|
+
*/
|
|
131
|
+
registerSSRCollectorGetterGlobal(getSSRCollector);
|
|
132
|
+
/**
|
|
133
|
+
* Create an Astro middleware that collects Tasty styles during SSR.
|
|
134
|
+
*
|
|
135
|
+
* All React components rendered during the request will have their
|
|
136
|
+
* computeStyles() calls captured by the collector via AsyncLocalStorage.
|
|
137
|
+
* After rendering, the middleware injects the collected CSS into </head>.
|
|
138
|
+
*
|
|
139
|
+
* @example Manual middleware setup
|
|
140
|
+
* ```ts
|
|
141
|
+
* // src/middleware.ts
|
|
142
|
+
* import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';
|
|
143
|
+
* export const onRequest = tastyMiddleware();
|
|
144
|
+
* ```
|
|
145
|
+
*
|
|
146
|
+
* @example Composing with other middleware
|
|
147
|
+
* ```ts
|
|
148
|
+
* // src/middleware.ts
|
|
149
|
+
* import { sequence } from 'astro:middleware';
|
|
150
|
+
* import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';
|
|
151
|
+
*
|
|
152
|
+
* export const onRequest = sequence(
|
|
153
|
+
* tastyMiddleware(),
|
|
154
|
+
* myOtherMiddleware,
|
|
155
|
+
* );
|
|
156
|
+
* ```
|
|
157
|
+
*/
|
|
158
|
+
function tastyMiddleware(options) {
|
|
159
|
+
const internalOptions = options;
|
|
160
|
+
return async (context, next) => {
|
|
161
|
+
const transferCache = options?.transferCache ?? true;
|
|
162
|
+
const extractionMetadata = internalOptions?.extractionMetadata === true && context.isPrerendered === true;
|
|
163
|
+
const collector = new ServerStyleCollector();
|
|
164
|
+
const rendered = await runWithCollector(collector, async () => {
|
|
165
|
+
const response = await next();
|
|
166
|
+
const body = response.body;
|
|
167
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
168
|
+
if (!body || !contentType.includes("text/html")) return { response };
|
|
169
|
+
const reader = body.pipeThrough(new TextDecoderStream()).getReader();
|
|
170
|
+
const parts = [];
|
|
171
|
+
for (;;) {
|
|
172
|
+
const { done, value } = await reader.read();
|
|
173
|
+
if (done) break;
|
|
174
|
+
parts.push(value);
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
html: parts.join(""),
|
|
178
|
+
status: response.status,
|
|
179
|
+
headers: response.headers
|
|
180
|
+
};
|
|
181
|
+
});
|
|
182
|
+
if ("response" in rendered) return rendered.response;
|
|
183
|
+
if (!rendered.html) return new Response(null, {
|
|
184
|
+
status: rendered.status,
|
|
185
|
+
headers: rendered.headers
|
|
186
|
+
});
|
|
187
|
+
let { html } = rendered;
|
|
188
|
+
const css = collector.getCSS();
|
|
189
|
+
if (!css) return new Response(html, {
|
|
190
|
+
status: rendered.status,
|
|
191
|
+
headers: rendered.headers
|
|
192
|
+
});
|
|
193
|
+
const nonce = getConfig().nonce;
|
|
194
|
+
const nonceAttr = nonce ? ` nonce="${nonce}"` : "";
|
|
195
|
+
const styleTag = `<style data-tasty-ssr${nonceAttr}>${css}</style>`;
|
|
196
|
+
const metadataTag = extractionMetadata ? createExtractionMetadata(collector.getArtifacts()) : "";
|
|
197
|
+
let cacheTag = "";
|
|
198
|
+
if (transferCache) {
|
|
199
|
+
const classNames = collector.getRenderedClassNames();
|
|
200
|
+
if (classNames.length > 0) cacheTag = `<script${nonceAttr}>(window.__TASTY__=window.__TASTY__||[]).push(${classNames.map((n) => `"${n}"`).join(",")})<\/script>`;
|
|
201
|
+
}
|
|
202
|
+
const injection = styleTag + metadataTag + cacheTag;
|
|
203
|
+
const idx = html.indexOf("</head>");
|
|
204
|
+
if (idx !== -1) html = html.slice(0, idx) + injection + html.slice(idx);
|
|
205
|
+
else html = injection + html;
|
|
206
|
+
const headers = new Headers(rendered.headers);
|
|
207
|
+
headers.delete("content-length");
|
|
208
|
+
return new Response(html, {
|
|
209
|
+
status: rendered.status,
|
|
210
|
+
headers
|
|
211
|
+
});
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Package subpaths of the middleware entrypoints registered by
|
|
216
|
+
* `tastyIntegration()`.
|
|
217
|
+
*
|
|
218
|
+
* These must be bare specifiers rather than
|
|
219
|
+
* `new URL('./astro-middleware.js', import.meta.url)`. The bundler is free to
|
|
220
|
+
* hoist `tastyIntegration` into a shared chunk at a different directory depth
|
|
221
|
+
* than `dist/ssr/`, which makes a relative URL resolve to a file that does not
|
|
222
|
+
* exist and breaks the build for every consumer. A package subpath is resolved
|
|
223
|
+
* by the consumer through our `exports` map, so it never depends on the
|
|
224
|
+
* chunk layout.
|
|
225
|
+
*
|
|
226
|
+
* There are separate entrypoints instead of one parameterised entrypoint because
|
|
227
|
+
* `addMiddleware()` cannot pass options: the integration runs when the Astro
|
|
228
|
+
* config is loaded, while the middleware module is evaluated in the server
|
|
229
|
+
* runtime — a different process for built output — so module-level state set
|
|
230
|
+
* by the integration is not visible to the middleware.
|
|
231
|
+
*/
|
|
232
|
+
const MIDDLEWARE_ENTRYPOINT = "@tenphi/tasty/ssr/astro-middleware";
|
|
233
|
+
const MIDDLEWARE_ENTRYPOINT_STATIC = "@tenphi/tasty/ssr/astro-middleware-static";
|
|
234
|
+
const MIDDLEWARE_ENTRYPOINT_EXTRACT = "@tenphi/tasty/ssr/astro-middleware-extract";
|
|
235
|
+
const MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC = "@tenphi/tasty/ssr/astro-middleware-extract-static";
|
|
236
|
+
/**
|
|
237
|
+
* Astro integration that automatically sets up Tasty SSR.
|
|
238
|
+
*
|
|
239
|
+
* Registers middleware for cross-component CSS deduplication and
|
|
240
|
+
* optionally injects a client hydration script for island support.
|
|
241
|
+
*
|
|
242
|
+
* @example Basic setup (with islands)
|
|
243
|
+
* ```ts
|
|
244
|
+
* // astro.config.mjs
|
|
245
|
+
* import { tastyIntegration } from '@tenphi/tasty/ssr/astro';
|
|
246
|
+
*
|
|
247
|
+
* export default defineConfig({
|
|
248
|
+
* integrations: [tastyIntegration()],
|
|
249
|
+
* });
|
|
250
|
+
* ```
|
|
251
|
+
*
|
|
252
|
+
* @example Static-only (no client JS)
|
|
253
|
+
* ```ts
|
|
254
|
+
* // astro.config.mjs
|
|
255
|
+
* import { tastyIntegration } from '@tenphi/tasty/ssr/astro';
|
|
256
|
+
*
|
|
257
|
+
* export default defineConfig({
|
|
258
|
+
* integrations: [tastyIntegration({ islands: false })],
|
|
259
|
+
* });
|
|
260
|
+
* ```
|
|
261
|
+
*/
|
|
262
|
+
function tastyIntegration(options) {
|
|
263
|
+
const { islands = true } = options ?? {};
|
|
264
|
+
const cssMode = options?.css?.mode ?? "inline";
|
|
265
|
+
let base = "/";
|
|
266
|
+
let assets = "_astro";
|
|
267
|
+
let assetsPrefix;
|
|
268
|
+
let site;
|
|
269
|
+
return {
|
|
270
|
+
name: "@tenphi/tasty",
|
|
271
|
+
hooks: {
|
|
272
|
+
"astro:config:setup": ({ addMiddleware, injectScript }) => {
|
|
273
|
+
addMiddleware({
|
|
274
|
+
entrypoint: cssMode === "extract" ? islands ? MIDDLEWARE_ENTRYPOINT_EXTRACT : MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC : islands ? MIDDLEWARE_ENTRYPOINT : MIDDLEWARE_ENTRYPOINT_STATIC,
|
|
275
|
+
order: "pre"
|
|
276
|
+
});
|
|
277
|
+
if (islands) injectScript("before-hydration", `import "@tenphi/tasty/ssr/astro-client";`);
|
|
278
|
+
},
|
|
279
|
+
"astro:config:done": ({ config }) => {
|
|
280
|
+
base = config.base ?? "/";
|
|
281
|
+
assets = config.build?.assets ?? "_astro";
|
|
282
|
+
assetsPrefix = config.build?.assetsPrefix;
|
|
283
|
+
site = config.site;
|
|
284
|
+
},
|
|
285
|
+
"astro:build:done": async ({ dir }) => {
|
|
286
|
+
if (cssMode !== "extract") return;
|
|
287
|
+
await extractAstroCSS({
|
|
288
|
+
dir,
|
|
289
|
+
base,
|
|
290
|
+
assets,
|
|
291
|
+
assetsPrefix,
|
|
292
|
+
site
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
//#endregion
|
|
299
|
+
export { tastyMiddleware as n, tastyIntegration as t };
|
|
300
|
+
|
|
301
|
+
//# sourceMappingURL=astro-Dj8YpRd7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"astro-Dj8YpRd7.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 { 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":";;;;;;;;;;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,QAAQ,KAAK,UAAU;CACjD,MAAM,WAAW,KAAK,QAAQ,YAAY,eAAe,CAAC;CAC1D,IACE,iBAAiB,MACjB,aAAa,MACb,WAAW,MAAsB,eAEjC,OAAO;CAGT,OAAO;EACL;EACA;EACA;EACA;EACA,gBAAgB,cAAc;EAC9B,WAAW,KAAK,MAAM,YAAY,eAAe,CAAC;CACpD;AACF;AAEA,eAAe,cAAc,KAAgC;CAC3D,MAAM,Q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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-Cbp2C2bj.d.ts.map
|
|
@@ -1,8 +1,37 @@
|
|
|
1
|
-
import { n as StyleResult } from "./index-
|
|
1
|
+
import { n as StyleResult } from "./index-C8RFYeFW.js";
|
|
2
|
+
import { c as TastyPrecompiledChunk, f as TastyStyleArtifactSource, l as TastyPrecompiledDependencies } from "./types-Bo5ePLZh.js";
|
|
2
3
|
|
|
3
4
|
//#region src/ssr/collector.d.ts
|
|
5
|
+
type ServerStyleArtifactKind = 'property' | 'font-face' | 'counter-style' | 'function' | 'raw' | 'global' | 'chunk' | 'keyframes';
|
|
6
|
+
interface ServerStyleArtifact {
|
|
7
|
+
/** Stable identifier derived from the artifact kind, logical key, and CSS. */
|
|
8
|
+
id: string;
|
|
9
|
+
kind: ServerStyleArtifactKind;
|
|
10
|
+
css: string;
|
|
11
|
+
/** Zero-based position in the collector's final cascade order. */
|
|
12
|
+
order: number;
|
|
13
|
+
/** Origin of the rule. */
|
|
14
|
+
source: TastyStyleArtifactSource;
|
|
15
|
+
}
|
|
16
|
+
interface CollectArtifactOptions {
|
|
17
|
+
source?: TastyStyleArtifactSource;
|
|
18
|
+
}
|
|
19
|
+
interface CollectPropertyOptions extends CollectArtifactOptions {
|
|
20
|
+
cssName?: string;
|
|
21
|
+
normalizedDefinition?: string;
|
|
22
|
+
rscKey?: string;
|
|
23
|
+
}
|
|
24
|
+
interface CollectKeyframesOptions extends CollectArtifactOptions {
|
|
25
|
+
contentKey?: string;
|
|
26
|
+
rscKeys?: readonly string[];
|
|
27
|
+
}
|
|
28
|
+
interface CollectCounterStyleOptions extends CollectArtifactOptions {
|
|
29
|
+
weak?: boolean;
|
|
30
|
+
rscKeys?: readonly string[];
|
|
31
|
+
}
|
|
4
32
|
declare class ServerStyleCollector {
|
|
5
33
|
private chunks;
|
|
34
|
+
private chunkRuleCounts;
|
|
6
35
|
private cacheKeyToClassName;
|
|
7
36
|
private flushedKeys;
|
|
8
37
|
private propertyRules;
|
|
@@ -23,6 +52,21 @@ declare class ServerStyleCollector {
|
|
|
23
52
|
private counterStyleCounter;
|
|
24
53
|
private internalsCollected;
|
|
25
54
|
private namePrefix;
|
|
55
|
+
private artifactSources;
|
|
56
|
+
private precompiledChunks;
|
|
57
|
+
private precompiledProperties;
|
|
58
|
+
private precompiledKeyframes;
|
|
59
|
+
private precompiledFontFaces;
|
|
60
|
+
private precompiledCounterStyles;
|
|
61
|
+
private precompiledFunctions;
|
|
62
|
+
private precompiledRSCKeys;
|
|
63
|
+
private appliedPrecompiledRevision;
|
|
64
|
+
private externalProperties;
|
|
65
|
+
private externalKeyframes;
|
|
66
|
+
private externalFontFaces;
|
|
67
|
+
private externalCounterStyles;
|
|
68
|
+
private externalFunctions;
|
|
69
|
+
private precompileRecording;
|
|
26
70
|
/**
|
|
27
71
|
* @param namePrefix - Optional override for the configured prefix.
|
|
28
72
|
* Defaults to the value from `configure({ namePrefix })` (or `'t'`).
|
|
@@ -31,7 +75,32 @@ declare class ServerStyleCollector {
|
|
|
31
75
|
* so misconfiguration fails before any CSS is collected.
|
|
32
76
|
*/
|
|
33
77
|
constructor(namePrefix?: string);
|
|
78
|
+
private sourceKey;
|
|
79
|
+
private setSource;
|
|
80
|
+
/**
|
|
81
|
+
* Pick up manifests registered after this collector was constructed.
|
|
82
|
+
*
|
|
83
|
+
* Deliberately not called from the constructor. Reading the registered
|
|
84
|
+
* dependencies is what validates the catalogs against the host's
|
|
85
|
+
* configuration, and registration is a side-effect import that routinely
|
|
86
|
+
* runs before the host's own `configure()` call — so a collector built in
|
|
87
|
+
* between would validate against defaults and permanently drop a catalog
|
|
88
|
+
* that matches once configuration is installed.
|
|
89
|
+
*
|
|
90
|
+
* Instead every method that consults an `external*` set calls this first, so
|
|
91
|
+
* the seed lands at whichever style-producing operation happens to come
|
|
92
|
+
* first. That gate belongs here rather than at the call sites: the standalone
|
|
93
|
+
* at-rule hooks (`useKeyframes`, `useCounterStyle`, `useFontFace`) go
|
|
94
|
+
* straight to `collect*` and never reach `collectInternals()`, so a catalog's
|
|
95
|
+
* standalone rule would otherwise be emitted a second time during SSR.
|
|
96
|
+
* After the first call this is an integer comparison.
|
|
97
|
+
*/
|
|
98
|
+
applyRegisteredPrecompiledDependencies(): void;
|
|
34
99
|
private generateClassName;
|
|
100
|
+
/** @internal Enable build-time chunk lookup metadata collection. */
|
|
101
|
+
enablePrecompileRecording(): void;
|
|
102
|
+
/** @internal Whether this collector is producing a catalog artifact. */
|
|
103
|
+
isPrecompileRecording(): boolean;
|
|
35
104
|
/**
|
|
36
105
|
* Collect internal @property rules and :root token defaults.
|
|
37
106
|
* Mirrors markStylesGenerated() from the client-side injector.
|
|
@@ -55,14 +124,16 @@ declare class ServerStyleCollector {
|
|
|
55
124
|
* Called by useStyles during server render.
|
|
56
125
|
*/
|
|
57
126
|
collectChunk(cacheKey: string, className: string, rules: StyleResult[]): void;
|
|
127
|
+
/** Record the pre-render lookup key corresponding to a collected chunk. */
|
|
128
|
+
recordPrecompiledChunk(lookupKey: string, className: string, animations: readonly string[]): void;
|
|
58
129
|
/**
|
|
59
130
|
* Record a @property rule. Deduplicated by name.
|
|
60
131
|
*/
|
|
61
|
-
collectProperty(name: string, css: string): void;
|
|
132
|
+
collectProperty(name: string, css: string, options?: CollectPropertyOptions): void;
|
|
62
133
|
/**
|
|
63
134
|
* Record a @keyframes rule. Deduplicated by name.
|
|
64
135
|
*/
|
|
65
|
-
collectKeyframes(name: string, css: string): void;
|
|
136
|
+
collectKeyframes(name: string, css: string, options?: CollectKeyframesOptions): void;
|
|
66
137
|
/**
|
|
67
138
|
* Allocate a keyframe name for SSR. Uses provided name or generates one.
|
|
68
139
|
*/
|
|
@@ -70,15 +141,13 @@ declare class ServerStyleCollector {
|
|
|
70
141
|
/**
|
|
71
142
|
* Record a @font-face rule. Deduplicated by key (content hash).
|
|
72
143
|
*/
|
|
73
|
-
collectFontFace(key: string, css: string): void;
|
|
144
|
+
collectFontFace(key: string, css: string, options?: CollectArtifactOptions): void;
|
|
74
145
|
/**
|
|
75
146
|
* Record a @counter-style rule. Deduplicated by name and overrides an
|
|
76
147
|
* existing rule by default. Pass `weak: true` for global `configure()`
|
|
77
148
|
* definitions, which never clobber an existing rule.
|
|
78
149
|
*/
|
|
79
|
-
collectCounterStyle(name: string, css: string, options?:
|
|
80
|
-
weak?: boolean;
|
|
81
|
-
}): void;
|
|
150
|
+
collectCounterStyle(name: string, css: string, options?: CollectCounterStyleOptions): void;
|
|
82
151
|
/**
|
|
83
152
|
* Record a @function rule. Deduplicated by CSS function name and overrides an
|
|
84
153
|
* existing rule by default. Pass `weak: true` for global `configure()`
|
|
@@ -86,6 +155,7 @@ declare class ServerStyleCollector {
|
|
|
86
155
|
*/
|
|
87
156
|
collectFunction(name: string, css: string, options?: {
|
|
88
157
|
weak?: boolean;
|
|
158
|
+
source?: TastyStyleArtifactSource;
|
|
89
159
|
}): void;
|
|
90
160
|
/**
|
|
91
161
|
* Allocate a counter-style name for SSR. Uses provided name or generates one.
|
|
@@ -97,14 +167,27 @@ declare class ServerStyleCollector {
|
|
|
97
167
|
* Pass `replace` for slot-keyed entries (an explicit `id`), where the last
|
|
98
168
|
* write must win to match the client's update-tracking behavior.
|
|
99
169
|
*/
|
|
100
|
-
collectGlobalStyles(key: string, css: string, replace?: boolean): void;
|
|
170
|
+
collectGlobalStyles(key: string, css: string, replace?: boolean, options?: CollectArtifactOptions): void;
|
|
101
171
|
/**
|
|
102
172
|
* Record raw CSS text (from useRawCSS). Deduplicated by key.
|
|
103
173
|
*
|
|
104
174
|
* Pass `replace` for slot-keyed entries (an explicit `id`), where the last
|
|
105
175
|
* write must win to match the client's update-tracking behavior.
|
|
106
176
|
*/
|
|
107
|
-
collectRawCSS(key: string, css: string, replace?: boolean): void;
|
|
177
|
+
collectRawCSS(key: string, css: string, replace?: boolean, options?: CollectArtifactOptions): void;
|
|
178
|
+
getPrecompiledChunks(): TastyPrecompiledChunk[];
|
|
179
|
+
getPrecompiledDependencies(): TastyPrecompiledDependencies;
|
|
180
|
+
/** @internal Structural top-level rule count for component artifacts. */
|
|
181
|
+
getPrecompiledRuleCount(): number;
|
|
182
|
+
/**
|
|
183
|
+
* Return the collected CSS as structured, ordered artifacts.
|
|
184
|
+
*
|
|
185
|
+
* Artifact boundaries are part of the collector output so build tools never
|
|
186
|
+
* need to split or parse CSS text. IDs include the logical collection key
|
|
187
|
+
* and content, making them stable across equivalent page renders while a CSS
|
|
188
|
+
* change always produces a different ID.
|
|
189
|
+
*/
|
|
190
|
+
getArtifacts(): ServerStyleArtifact[];
|
|
108
191
|
/**
|
|
109
192
|
* Extract all CSS collected so far as a single string.
|
|
110
193
|
* Includes @property and @keyframes rules.
|
|
@@ -141,5 +224,5 @@ declare class ServerStyleCollector {
|
|
|
141
224
|
*/
|
|
142
225
|
declare function createServerStyleCollector(namePrefix?: string): ServerStyleCollector;
|
|
143
226
|
//#endregion
|
|
144
|
-
export { createServerStyleCollector as n, ServerStyleCollector as t };
|
|
145
|
-
//# sourceMappingURL=collector-
|
|
227
|
+
export { createServerStyleCollector as i, ServerStyleArtifactKind as n, ServerStyleCollector as r, ServerStyleArtifact as t };
|
|
228
|
+
//# sourceMappingURL=collector-DBY6liC2.d.ts.map
|