@tenphi/tasty 0.0.0-snapshot.533ac40 → 0.0.0-snapshot.54483c7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/{astro-1-lpJJ41.js → astro-Dj8YpRd7.js} +3 -3
  2. package/dist/{astro-1-lpJJ41.js.map → astro-Dj8YpRd7.js.map} +1 -1
  3. package/dist/{babel-BMzzohY1.d.ts → babel-Cbp2C2bj.d.ts} +2 -2
  4. package/dist/{collector-CD8mO5gV.d.ts → collector-DBY6liC2.d.ts} +20 -3
  5. package/dist/{collector-C_fa7j2X.js → collector-NjmUiB8f.js} +27 -5
  6. package/dist/collector-NjmUiB8f.js.map +1 -0
  7. package/dist/{config-wc1IKOU3.js → config-Bd2vOF0Z.js} +24 -12
  8. package/dist/{config-wc1IKOU3.js.map → config-Bd2vOF0Z.js.map} +1 -1
  9. package/dist/{config-D-8U-_Ip.d.ts → config-CA7iAlEI.d.ts} +2 -2
  10. package/dist/core/index.d.ts +2 -2
  11. package/dist/core/index.js +5 -5
  12. package/dist/{core---gRPaWd.js → core-ClInK6YG.js} +5 -5
  13. package/dist/{core---gRPaWd.js.map → core-ClInK6YG.js.map} +1 -1
  14. package/dist/{css-writer-CoEf4ymg.js → css-writer-BDQXG9Jo.js} +3 -3
  15. package/dist/{css-writer-CoEf4ymg.js.map → css-writer-BDQXG9Jo.js.map} +1 -1
  16. package/dist/{format-rules-C7Lq98bG.js → format-rules-CGhgoVLR.js} +2 -2
  17. package/dist/{format-rules-C7Lq98bG.js.map → format-rules-CGhgoVLR.js.map} +1 -1
  18. package/dist/{hydrate-c4WM7IcW.js → hydrate-CqbxwVh_.js} +2 -2
  19. package/dist/{hydrate-c4WM7IcW.js.map → hydrate-CqbxwVh_.js.map} +1 -1
  20. package/dist/{index-UUB866In.d.ts → index-FpYK0H5g.d.ts} +3 -3
  21. package/dist/index.d.ts +2 -2
  22. package/dist/index.js +6 -6
  23. package/dist/{keyframes-izsuyyCo.js → keyframes-BjfNVhaB.js} +2 -2
  24. package/dist/{keyframes-izsuyyCo.js.map → keyframes-BjfNVhaB.js.map} +1 -1
  25. package/dist/{merge-styles-Cn_rhF9e.js → merge-styles-BbJhjesV.js} +2 -2
  26. package/dist/{merge-styles-Cn_rhF9e.js.map → merge-styles-BbJhjesV.js.map} +1 -1
  27. package/dist/precompile/index.d.ts +1 -1
  28. package/dist/precompile/index.js +3 -3
  29. package/dist/precompile/register.d.ts +1 -1
  30. package/dist/precompile/register.js +1 -1
  31. package/dist/{register-uTQZDMJT.js → register-BPKpxsfQ.js} +17 -13
  32. package/dist/register-BPKpxsfQ.js.map +1 -0
  33. package/dist/{resolve-recipes-DUMcQjt2.js → resolve-recipes-B2Sf36AH.js} +3 -3
  34. package/dist/{resolve-recipes-DUMcQjt2.js.map → resolve-recipes-B2Sf36AH.js.map} +1 -1
  35. package/dist/ssr/astro-client.js +1 -1
  36. package/dist/ssr/astro-middleware-extract-static.js +1 -1
  37. package/dist/ssr/astro-middleware-extract.js +1 -1
  38. package/dist/ssr/astro-middleware-static.js +1 -1
  39. package/dist/ssr/astro-middleware.js +1 -1
  40. package/dist/ssr/astro.js +1 -1
  41. package/dist/ssr/index.d.ts +1 -1
  42. package/dist/ssr/index.js +2 -2
  43. package/dist/ssr/next-config.d.ts +1 -1
  44. package/dist/ssr/next-config.js +2 -2
  45. package/dist/ssr/next.d.ts +1 -1
  46. package/dist/ssr/next.js +3 -3
  47. package/dist/static/index.js +1 -1
  48. package/dist/{types-D2gO2QKz.d.ts → types-Bo5ePLZh.d.ts} +14 -3
  49. package/dist/zero/babel.d.ts +1 -1
  50. package/dist/zero/babel.js +4 -4
  51. package/dist/zero/index.js +1 -1
  52. package/dist/zero/next.d.ts +1 -1
  53. package/docs/precompile.md +22 -6
  54. package/package.json +1 -1
  55. package/dist/collector-C_fa7j2X.js.map +0 -1
  56. package/dist/register-uTQZDMJT.js.map +0 -1
@@ -1,6 +1,6 @@
1
- import { n as getConfig } from "./config-wc1IKOU3.js";
1
+ import { n as getConfig } from "./config-Bd2vOF0Z.js";
2
2
  import { r as registerSSRCollectorGetterGlobal } from "./ssr-collector-ref-COs_ioWl.js";
3
- import { t as ServerStyleCollector } from "./collector-C_fa7j2X.js";
3
+ import { t as ServerStyleCollector } from "./collector-NjmUiB8f.js";
4
4
  import { n as runWithCollector, t as getSSRCollector } from "./async-storage-DKK-wTD4.js";
5
5
  import { t as findUnsafeCSSResource } from "./css-resources-Cyl_axbI.js";
6
6
  import { createHash } from "node:crypto";
@@ -298,4 +298,4 @@ function tastyIntegration(options) {
298
298
  //#endregion
299
299
  export { tastyMiddleware as n, tastyIntegration as t };
300
300
 
301
- //# sourceMappingURL=astro-1-lpJJ41.js.map
301
+ //# sourceMappingURL=astro-Dj8YpRd7.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"astro-1-lpJJ41.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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AQ,OAAO,gBAAgB;EAE/B,OAAO,IAAI,SAAS,MAAM;GACxB,QAAQ,SAAS;GACjB;EACF,CAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,wBAAwB;AAC9B,MAAM,+BACJ;AACF,MAAM,gCACJ;AACF,MAAM,uCACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDF,SAAgB,iBAAiB,SAAmC;CAClE,MAAM,EAAE,UAAU,SAAS,WAAW,CAAC;CACvC,MAAM,UAAU,SAAS,KAAK,QAAQ;CACtC,IAAI,OAAO;CACX,IAAI,SAAS;CACb,IAAI;CACJ,IAAI;CAEJ,OAAO;EACL,MAAM;EACN,OAAO;GACL,uBAAuB,EACrB,eACA,mBAUI;IACJ,cAAc;KACZ,YACE,YAAY,YACR,UACE,gCACA,uCACF,UACE,wBACA;KACR,OAAO;IACT,CAAC;IAED,IAAI,SACF,aACE,oBACA,0CACF;GAEJ;GACA,sBAAsB,EACpB,aAUI;IACJ,OAAO,OAAO,QAAQ;IACtB,SAAS,OAAO,OAAO,UAAU;IACjC,eAAe,OAAO,OAAO;IAC7B,OAAO,OAAO;GAChB;GACA,oBAAoB,OAAO,EAAE,UAAwB;IACnD,IAAI,YAAY,WAAW;IAC3B,MAAM,gBAAgB;KAAE;KAAK;KAAM;KAAQ;KAAc;IAAK,CAAC;GACjE;EACF;CACF;AACF"}
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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-8U-_Ip.js";
1
+ import { t as TastyConfig } from "./config-CA7iAlEI.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-BMzzohY1.d.ts.map
83
+ //# sourceMappingURL=babel-Cbp2C2bj.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { n as StyleResult } from "./index-C8RFYeFW.js";
2
- import { c as TastyPrecompiledChunk, f as TastyStyleArtifactSource, l as TastyPrecompiledDependencies } from "./types-D2gO2QKz.js";
2
+ import { c as TastyPrecompiledChunk, f as TastyStyleArtifactSource, l as TastyPrecompiledDependencies } from "./types-Bo5ePLZh.js";
3
3
 
4
4
  //#region src/ssr/collector.d.ts
5
5
  type ServerStyleArtifactKind = 'property' | 'font-face' | 'counter-style' | 'function' | 'raw' | 'global' | 'chunk' | 'keyframes';
@@ -77,7 +77,24 @@ declare class ServerStyleCollector {
77
77
  constructor(namePrefix?: string);
78
78
  private sourceKey;
79
79
  private setSource;
80
- /** Pick up manifests registered after this collector was constructed. */
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
+ */
81
98
  applyRegisteredPrecompiledDependencies(): void;
82
99
  private generateClassName;
83
100
  /** @internal Enable build-time chunk lookup metadata collection. */
@@ -208,4 +225,4 @@ declare class ServerStyleCollector {
208
225
  declare function createServerStyleCollector(namePrefix?: string): ServerStyleCollector;
209
226
  //#endregion
210
227
  export { createServerStyleCollector as i, ServerStyleArtifactKind as n, ServerStyleCollector as r, ServerStyleArtifact as t };
211
- //# sourceMappingURL=collector-CD8mO5gV.d.ts.map
228
+ //# sourceMappingURL=collector-DBY6liC2.d.ts.map
@@ -1,5 +1,5 @@
1
- import { $ as getRegisteredPrecompiledDependencies, Et as makeKeyframeName, Gt as formatFunctionRule, Nt as normalizePropertyDefinition, Ot as validateNamePrefix, Q as getPrecompiledRevision, R as renderStyles, Tt as makeCounterStyleName, a as getGlobalConfigTokens, at as formatCounterStyleRule, c as getGlobalFunctions, ct as fontFaceContentHash, f as getGlobalStyles, i as getEffectiveProperties, jt as getEffectiveDefinition, kt as hashString, lt as formatFontFaceRule, o as getGlobalCounterStyles, p as getNamePrefix, qt as parseFunctionName, s as getGlobalFontFaces, wt as makeClassName } from "./config-wc1IKOU3.js";
2
- import { n as formatRulesWithStats, r as formatPropertyCSS } from "./format-rules-C7Lq98bG.js";
1
+ import { $ as getRegisteredPrecompiledDependencies, Et as makeKeyframeName, Gt as formatFunctionRule, Nt as normalizePropertyDefinition, Ot as validateNamePrefix, Q as getPrecompiledRevision, R as renderStyles, Tt as makeCounterStyleName, a as getGlobalConfigTokens, at as formatCounterStyleRule, c as getGlobalFunctions, ct as fontFaceContentHash, f as getGlobalStyles, i as getEffectiveProperties, jt as getEffectiveDefinition, kt as hashString, lt as formatFontFaceRule, o as getGlobalCounterStyles, p as getNamePrefix, qt as parseFunctionName, s as getGlobalFontFaces, wt as makeClassName } from "./config-Bd2vOF0Z.js";
2
+ import { n as formatRulesWithStats, r as formatPropertyCSS } from "./format-rules-CGhgoVLR.js";
3
3
  import { t as formatGlobalRules } from "./format-global-rules-DklyaXv-.js";
4
4
  //#region src/ssr/collector.ts
5
5
  /**
@@ -66,7 +66,6 @@ var ServerStyleCollector = class {
66
66
  constructor(namePrefix) {
67
67
  if (namePrefix !== void 0) validateNamePrefix(namePrefix);
68
68
  this.namePrefix = namePrefix ?? getNamePrefix();
69
- this.applyRegisteredPrecompiledDependencies();
70
69
  }
71
70
  sourceKey(kind, key) {
72
71
  return `${kind}\0${key}`;
@@ -74,7 +73,24 @@ var ServerStyleCollector = class {
74
73
  setSource(kind, key, source) {
75
74
  this.artifactSources.set(this.sourceKey(kind, key), source);
76
75
  }
77
- /** Pick up manifests registered after this collector was constructed. */
76
+ /**
77
+ * Pick up manifests registered after this collector was constructed.
78
+ *
79
+ * Deliberately not called from the constructor. Reading the registered
80
+ * dependencies is what validates the catalogs against the host's
81
+ * configuration, and registration is a side-effect import that routinely
82
+ * runs before the host's own `configure()` call — so a collector built in
83
+ * between would validate against defaults and permanently drop a catalog
84
+ * that matches once configuration is installed.
85
+ *
86
+ * Instead every method that consults an `external*` set calls this first, so
87
+ * the seed lands at whichever style-producing operation happens to come
88
+ * first. That gate belongs here rather than at the call sites: the standalone
89
+ * at-rule hooks (`useKeyframes`, `useCounterStyle`, `useFontFace`) go
90
+ * straight to `collect*` and never reach `collectInternals()`, so a catalog's
91
+ * standalone rule would otherwise be emitted a second time during SSR.
92
+ * After the first call this is an integer comparison.
93
+ */
78
94
  applyRegisteredPrecompiledDependencies() {
79
95
  const revision = getPrecompiledRevision();
80
96
  if (revision === this.appliedPrecompiledRevision) return;
@@ -120,6 +136,7 @@ var ServerStyleCollector = class {
120
136
  collectInternals() {
121
137
  if (this.internalsCollected) return;
122
138
  this.internalsCollected = true;
139
+ this.applyRegisteredPrecompiledDependencies();
123
140
  for (const [token, definition] of Object.entries(getEffectiveProperties())) {
124
141
  const css = formatPropertyCSS(token, definition);
125
142
  if (css) {
@@ -217,6 +234,7 @@ var ServerStyleCollector = class {
217
234
  * Record a @property rule. Deduplicated by name.
218
235
  */
219
236
  collectProperty(name, css, options) {
237
+ this.applyRegisteredPrecompiledDependencies();
220
238
  if (options?.cssName && this.externalProperties.has(options.cssName)) return;
221
239
  if (!this.propertyRules.has(name)) {
222
240
  this.propertyRules.set(name, css);
@@ -234,6 +252,7 @@ var ServerStyleCollector = class {
234
252
  * Record a @keyframes rule. Deduplicated by name.
235
253
  */
236
254
  collectKeyframes(name, css, options) {
255
+ this.applyRegisteredPrecompiledDependencies();
237
256
  if (options?.contentKey && this.externalKeyframes.has(options.contentKey)) return;
238
257
  if (!this.keyframeRules.has(name)) {
239
258
  this.keyframeRules.set(name, css);
@@ -260,6 +279,7 @@ var ServerStyleCollector = class {
260
279
  * Record a @font-face rule. Deduplicated by key (content hash).
261
280
  */
262
281
  collectFontFace(key, css, options) {
282
+ this.applyRegisteredPrecompiledDependencies();
263
283
  if (this.externalFontFaces.has(key)) return;
264
284
  if (!this.fontFaceRules.has(key)) {
265
285
  this.fontFaceRules.set(key, css);
@@ -276,6 +296,7 @@ var ServerStyleCollector = class {
276
296
  * definitions, which never clobber an existing rule.
277
297
  */
278
298
  collectCounterStyle(name, css, options) {
299
+ this.applyRegisteredPrecompiledDependencies();
279
300
  if (this.externalCounterStyles.has(name)) return;
280
301
  const source = options?.source ?? "component";
281
302
  const existing = this.counterStyleRules.get(name);
@@ -310,6 +331,7 @@ var ServerStyleCollector = class {
310
331
  * definitions, which never clobber an existing rule.
311
332
  */
312
333
  collectFunction(name, css, options) {
334
+ this.applyRegisteredPrecompiledDependencies();
313
335
  if (this.externalFunctions.has(name)) return;
314
336
  const source = options?.source ?? "component";
315
337
  const existing = this.functionRules.get(name);
@@ -504,4 +526,4 @@ function createServerStyleCollector(namePrefix) {
504
526
  //#endregion
505
527
  export { createServerStyleCollector as n, ServerStyleCollector as t };
506
528
 
507
- //# sourceMappingURL=collector-C_fa7j2X.js.map
529
+ //# sourceMappingURL=collector-NjmUiB8f.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collector-NjmUiB8f.js","names":[],"sources":["../src/ssr/collector.ts"],"sourcesContent":["/**\n * ServerStyleCollector — server-safe style collector for SSR.\n *\n * Accumulates CSS rules and cache metadata during server rendering.\n * This is the server-side counterpart to StyleInjector: it allocates\n * hash-based class names using the configured `namePrefix` (defaults\n * to `'t'`), formats CSS rules into text, and tracks rendered class\n * names for lightweight client transfer.\n *\n * One instance is created per HTTP request. Concurrent requests\n * each get their own collector (via AsyncLocalStorage or React context).\n */\n\nimport {\n getEffectiveProperties,\n getGlobalStyles,\n getGlobalCounterStyles,\n getGlobalFontFaces,\n getGlobalFunctions,\n getGlobalConfigTokens,\n getNamePrefix,\n} from '../config';\nimport { formatCounterStyleRule } from '../counter-style';\nimport { fontFaceContentHash, formatFontFaceRule } from '../font-face';\nimport { formatFunctionRule, parseFunctionName } from '../functions';\nimport { renderStyles } from '../pipeline';\nimport type { StyleResult } from '../pipeline';\nimport {\n getEffectiveDefinition,\n normalizePropertyDefinition,\n} from '../properties';\nimport { hashString } from '../utils/hash';\nimport {\n makeClassName,\n makeCounterStyleName,\n makeKeyframeName,\n validateNamePrefix,\n} from '../utils/name-prefix';\nimport { formatPropertyCSS } from './format-property';\nimport { formatGlobalRules } from './format-global-rules';\nimport { formatRulesWithStats } from './format-rules';\nimport {\n getPrecompiledRevision,\n getRegisteredPrecompiledDependencies,\n} from '../precompile/runtime';\nimport type {\n PrecompiledCounterStyleCacheEntry,\n PrecompiledKeyframeCacheEntry,\n PrecompiledPropertyCacheEntry,\n TastyPrecompiledChunk,\n TastyPrecompiledDependencies,\n TastyStyleArtifactSource,\n} from '../precompile/types';\n\nexport type ServerStyleArtifactKind =\n | 'property'\n | 'font-face'\n | 'counter-style'\n | 'function'\n | 'raw'\n | 'global'\n | 'chunk'\n | 'keyframes';\n\nexport interface ServerStyleArtifact {\n /** Stable identifier derived from the artifact kind, logical key, and CSS. */\n id: string;\n kind: ServerStyleArtifactKind;\n css: string;\n /** Zero-based position in the collector's final cascade order. */\n order: number;\n /** Origin of the rule. */\n source: TastyStyleArtifactSource;\n}\n\ninterface CollectArtifactOptions {\n source?: TastyStyleArtifactSource;\n}\n\ninterface CollectPropertyOptions extends CollectArtifactOptions {\n cssName?: string;\n normalizedDefinition?: string;\n rscKey?: string;\n}\n\ninterface CollectKeyframesOptions extends CollectArtifactOptions {\n contentKey?: string;\n rscKeys?: readonly string[];\n}\n\ninterface CollectCounterStyleOptions extends CollectArtifactOptions {\n weak?: boolean;\n rscKeys?: readonly string[];\n}\n\nfunction artifactId(kind: ServerStyleArtifactKind, key: string, css: string) {\n const content = `${kind}\\0${key}\\0${css}`;\n return `${kind}:${hashString(content)}:${content.length.toString(36)}`;\n}\n\nexport class ServerStyleCollector {\n private chunks = new Map<string, string>();\n private chunkRuleCounts = new Map<string, number>();\n private cacheKeyToClassName = new Map<string, string>();\n private flushedKeys = new Set<string>();\n private propertyRules = new Map<string, string>();\n private flushedPropertyKeys = new Set<string>();\n private keyframeRules = new Map<string, string>();\n private flushedKeyframeKeys = new Set<string>();\n private globalStyles = new Map<string, string>();\n private flushedGlobalKeys = new Set<string>();\n private rawCSS = new Map<string, string>();\n private flushedRawKeys = new Set<string>();\n private fontFaceRules = new Map<string, string>();\n private flushedFontFaceKeys = new Set<string>();\n private counterStyleRules = new Map<string, string>();\n private flushedCounterStyleKeys = new Set<string>();\n private functionRules = new Map<string, string>();\n private flushedFunctionKeys = new Set<string>();\n private keyframesCounter = 0;\n private counterStyleCounter = 0;\n private internalsCollected = false;\n private namePrefix: string;\n private artifactSources = new Map<string, TastyStyleArtifactSource>();\n private precompiledChunks = new Map<string, TastyPrecompiledChunk>();\n private precompiledProperties = new Map<\n string,\n PrecompiledPropertyCacheEntry\n >();\n private precompiledKeyframes = new Map<\n string,\n PrecompiledKeyframeCacheEntry\n >();\n private precompiledFontFaces = new Set<string>();\n private precompiledCounterStyles = new Map<\n string,\n PrecompiledCounterStyleCacheEntry\n >();\n private precompiledFunctions = new Set<string>();\n private precompiledRSCKeys = new Set<string>();\n private appliedPrecompiledRevision = -1;\n private externalProperties = new Set<string>();\n private externalKeyframes = new Set<string>();\n private externalFontFaces = new Set<string>();\n private externalCounterStyles = new Set<string>();\n private externalFunctions = new Set<string>();\n private precompileRecording = false;\n\n /**\n * @param namePrefix - Optional override for the configured prefix.\n * Defaults to the value from `configure({ namePrefix })` (or `'t'`).\n * Pass an explicit prefix when constructing a collector outside the\n * normal configure() lifecycle (e.g. in tests). Validated eagerly\n * so misconfiguration fails before any CSS is collected.\n */\n constructor(namePrefix?: string) {\n if (namePrefix !== undefined) {\n validateNamePrefix(namePrefix);\n }\n this.namePrefix = namePrefix ?? getNamePrefix();\n }\n\n private sourceKey(kind: ServerStyleArtifactKind, key: string): string {\n return `${kind}\\0${key}`;\n }\n\n private setSource(\n kind: ServerStyleArtifactKind,\n key: string,\n source: TastyStyleArtifactSource,\n ): void {\n this.artifactSources.set(this.sourceKey(kind, key), source);\n }\n\n /**\n * Pick up manifests registered after this collector was constructed.\n *\n * Deliberately not called from the constructor. Reading the registered\n * dependencies is what validates the catalogs against the host's\n * configuration, and registration is a side-effect import that routinely\n * runs before the host's own `configure()` call — so a collector built in\n * between would validate against defaults and permanently drop a catalog\n * that matches once configuration is installed.\n *\n * Instead every method that consults an `external*` set calls this first, so\n * the seed lands at whichever style-producing operation happens to come\n * first. That gate belongs here rather than at the call sites: the standalone\n * at-rule hooks (`useKeyframes`, `useCounterStyle`, `useFontFace`) go\n * straight to `collect*` and never reach `collectInternals()`, so a catalog's\n * standalone rule would otherwise be emitted a second time during SSR.\n * After the first call this is an integer comparison.\n */\n applyRegisteredPrecompiledDependencies(): void {\n const revision = getPrecompiledRevision();\n if (revision === this.appliedPrecompiledRevision) return;\n this.appliedPrecompiledRevision = revision;\n\n this.externalProperties.clear();\n this.externalKeyframes.clear();\n this.externalFontFaces.clear();\n this.externalCounterStyles.clear();\n this.externalFunctions.clear();\n\n // Catalog generation deliberately records a self-contained artifact even\n // when another package registered precompiled styles in this process.\n if (this.precompileRecording) return;\n\n const dependencies = getRegisteredPrecompiledDependencies(this.namePrefix);\n for (const item of dependencies.properties) {\n this.externalProperties.add(item.name);\n }\n for (const item of dependencies.keyframes) {\n this.externalKeyframes.add(item.contentKey);\n }\n for (const hash of dependencies.fontFaces) this.externalFontFaces.add(hash);\n for (const item of dependencies.counterStyles) {\n this.externalCounterStyles.add(item.name);\n }\n for (const name of dependencies.functions) this.externalFunctions.add(name);\n }\n\n private generateClassName(cacheKey: string): string {\n return makeClassName(this.namePrefix, hashString(cacheKey));\n }\n\n /** @internal Enable build-time chunk lookup metadata collection. */\n enablePrecompileRecording(): void {\n this.precompileRecording = true;\n // A catalog build must be self-contained even if this process previously\n // registered another package's manifest.\n this.externalProperties.clear();\n this.externalKeyframes.clear();\n this.externalFontFaces.clear();\n this.externalCounterStyles.clear();\n this.externalFunctions.clear();\n }\n\n /** @internal Whether this collector is producing a catalog artifact. */\n isPrecompileRecording(): boolean {\n return this.precompileRecording;\n }\n\n /**\n * Collect internal @property rules and :root token defaults.\n * Mirrors markStylesGenerated() from the client-side injector.\n * Called automatically on first chunk collection; idempotent.\n *\n * Internals are always emitted here — the RSC path deliberately\n * defers to SSR so that tokens appear exactly once per page in\n * <style data-tasty-ssr> (avoiding duplication of large token sets).\n */\n collectInternals(): void {\n if (this.internalsCollected) return;\n this.internalsCollected = true;\n\n this.applyRegisteredPrecompiledDependencies();\n\n for (const [token, definition] of Object.entries(\n getEffectiveProperties(),\n )) {\n const css = formatPropertyCSS(token, definition);\n if (css) {\n const effective = getEffectiveDefinition(token, definition);\n this.collectProperty(`__prop:${token}`, css, {\n source: 'config',\n cssName: effective.isValid ? effective.cssName : undefined,\n normalizedDefinition: effective.isValid\n ? normalizePropertyDefinition(effective.definition)\n : undefined,\n });\n }\n }\n\n const tokenStyles = getGlobalConfigTokens();\n if (tokenStyles && Object.keys(tokenStyles).length > 0) {\n const tokenRules = renderStyles(tokenStyles, ':root') as StyleResult[];\n if (tokenRules.length > 0) {\n const css = formatGlobalRules(tokenRules);\n if (css) {\n this.collectGlobalStyles('__global:tokens', css, false, {\n source: 'config',\n });\n }\n }\n }\n\n const globalFF = getGlobalFontFaces();\n if (globalFF) {\n for (const [family, input] of Object.entries(globalFF)) {\n const descriptors = Array.isArray(input) ? input : [input];\n for (const desc of descriptors) {\n const hash = fontFaceContentHash(family, desc);\n const css = formatFontFaceRule(family, desc);\n this.collectFontFace(hash, css, { source: 'config' });\n }\n }\n }\n\n const globalCS = getGlobalCounterStyles();\n if (globalCS) {\n for (const [name, descriptors] of Object.entries(globalCS)) {\n const css = formatCounterStyleRule(name, descriptors);\n this.collectCounterStyle(name, css, {\n weak: true,\n source: 'config',\n });\n }\n }\n\n const globalFn = getGlobalFunctions();\n if (globalFn) {\n for (const [name, definition] of Object.entries(globalFn)) {\n const css = formatFunctionRule(name, definition);\n this.collectFunction(parseFunctionName(name), css, {\n weak: true,\n source: 'config',\n });\n }\n }\n\n const globalStyles = getGlobalStyles();\n if (globalStyles) {\n for (const [selector, styles] of Object.entries(globalStyles)) {\n if (Object.keys(styles).length > 0) {\n const rules = renderStyles(styles, selector) as StyleResult[];\n if (rules.length > 0) {\n const css = formatGlobalRules(rules);\n if (css) {\n this.collectGlobalStyles(\n `__global:styles:${selector}`,\n css,\n false,\n { source: 'config' },\n );\n }\n }\n }\n }\n }\n }\n\n /**\n * Allocate a className for a cache key, server-side.\n * Mirrors StyleInjector.allocateClassName but without DOM access.\n */\n allocateClassName(cacheKey: string): {\n className: string;\n isNewAllocation: boolean;\n } {\n const existing = this.cacheKeyToClassName.get(cacheKey);\n if (existing) {\n return { className: existing, isNewAllocation: false };\n }\n\n const className = this.generateClassName(cacheKey);\n this.cacheKeyToClassName.set(cacheKey, className);\n\n return { className, isNewAllocation: true };\n }\n\n /**\n * Record CSS rules for a chunk.\n * Called by useStyles during server render.\n */\n collectChunk(\n cacheKey: string,\n className: string,\n rules: StyleResult[],\n ): void {\n if (this.chunks.has(cacheKey)) return;\n const { css, ruleCount } = formatRulesWithStats(rules, className);\n if (css) {\n this.chunks.set(cacheKey, css);\n this.chunkRuleCounts.set(cacheKey, ruleCount);\n this.setSource('chunk', cacheKey, 'component');\n }\n }\n\n /** Record the pre-render lookup key corresponding to a collected chunk. */\n recordPrecompiledChunk(\n lookupKey: string,\n className: string,\n animations: readonly string[],\n ): void {\n if (!this.precompiledChunks.has(lookupKey)) {\n this.precompiledChunks.set(lookupKey, {\n lookupKey,\n className,\n animations: [...animations],\n });\n }\n }\n\n /**\n * Record a @property rule. Deduplicated by name.\n */\n collectProperty(\n name: string,\n css: string,\n options?: CollectPropertyOptions,\n ): void {\n this.applyRegisteredPrecompiledDependencies();\n if (options?.cssName && this.externalProperties.has(options.cssName))\n return;\n if (!this.propertyRules.has(name)) {\n this.propertyRules.set(name, css);\n this.setSource('property', name, options?.source ?? 'component');\n } else if ((options?.source ?? 'component') === 'component') {\n this.setSource('property', name, 'component');\n }\n if (\n (options?.source ?? 'component') === 'component' &&\n options?.cssName &&\n options.normalizedDefinition !== undefined\n ) {\n this.precompiledProperties.set(options.cssName, {\n name: options.cssName,\n definition: options.normalizedDefinition,\n });\n if (options.rscKey) this.precompiledRSCKeys.add(options.rscKey);\n }\n }\n\n /**\n * Record a @keyframes rule. Deduplicated by name.\n */\n collectKeyframes(\n name: string,\n css: string,\n options?: CollectKeyframesOptions,\n ): void {\n this.applyRegisteredPrecompiledDependencies();\n if (options?.contentKey && this.externalKeyframes.has(options.contentKey)) {\n return;\n }\n if (!this.keyframeRules.has(name)) {\n this.keyframeRules.set(name, css);\n this.setSource('keyframes', name, options?.source ?? 'component');\n } else if ((options?.source ?? 'component') === 'component') {\n this.setSource('keyframes', name, 'component');\n }\n if (\n (options?.source ?? 'component') === 'component' &&\n options?.contentKey\n ) {\n const existing = this.precompiledKeyframes.get(options.contentKey);\n const rscKeys = new Set(existing?.rscKeys ?? []);\n for (const key of options.rscKeys ?? []) rscKeys.add(key);\n this.precompiledKeyframes.set(options.contentKey, {\n name,\n contentKey: options.contentKey,\n rscKeys: [...rscKeys],\n });\n }\n }\n\n /**\n * Allocate a keyframe name for SSR. Uses provided name or generates one.\n */\n allocateKeyframeName(providedName?: string): string {\n return (\n providedName ??\n makeKeyframeName(this.namePrefix, String(this.keyframesCounter++))\n );\n }\n\n /**\n * Record a @font-face rule. Deduplicated by key (content hash).\n */\n collectFontFace(\n key: string,\n css: string,\n options?: CollectArtifactOptions,\n ): void {\n this.applyRegisteredPrecompiledDependencies();\n if (this.externalFontFaces.has(key)) return;\n if (!this.fontFaceRules.has(key)) {\n this.fontFaceRules.set(key, css);\n this.setSource('font-face', key, options?.source ?? 'component');\n } else if ((options?.source ?? 'component') === 'component') {\n this.setSource('font-face', key, 'component');\n }\n if ((options?.source ?? 'component') === 'component') {\n this.precompiledFontFaces.add(key);\n this.precompiledRSCKeys.add(`__ff:${key}`);\n }\n }\n\n /**\n * Record a @counter-style rule. Deduplicated by name and overrides an\n * existing rule by default. Pass `weak: true` for global `configure()`\n * definitions, which never clobber an existing rule.\n */\n collectCounterStyle(\n name: string,\n css: string,\n options?: CollectCounterStyleOptions,\n ): void {\n this.applyRegisteredPrecompiledDependencies();\n if (this.externalCounterStyles.has(name)) return;\n const source = options?.source ?? 'component';\n const existing = this.counterStyleRules.get(name);\n if (existing === undefined) {\n this.counterStyleRules.set(name, css);\n this.setSource('counter-style', name, source);\n if (source === 'component') {\n this.precompiledCounterStyles.set(name, {\n name,\n rscKeys: [...(options?.rscKeys ?? [])],\n });\n }\n return;\n }\n if (source === 'component') {\n this.precompiledCounterStyles.set(name, {\n name,\n rscKeys: [...(options?.rscKeys ?? [])],\n });\n if (existing === css) this.setSource('counter-style', name, 'component');\n }\n if (options?.weak || existing === css) return;\n this.counterStyleRules.set(name, css);\n this.setSource('counter-style', name, source);\n if (source === 'component') {\n this.precompiledCounterStyles.set(name, {\n name,\n rscKeys: [...(options?.rscKeys ?? [])],\n });\n }\n // If a rule with this name was already flushed (streaming), allow the\n // overriding rule to be flushed again so it wins by source order.\n this.flushedCounterStyleKeys.delete(name);\n }\n\n /**\n * Record a @function rule. Deduplicated by CSS function name and overrides an\n * existing rule by default. Pass `weak: true` for global `configure()`\n * definitions, which never clobber an existing rule.\n */\n collectFunction(\n name: string,\n css: string,\n options?: { weak?: boolean; source?: TastyStyleArtifactSource },\n ): void {\n this.applyRegisteredPrecompiledDependencies();\n if (this.externalFunctions.has(name)) return;\n const source = options?.source ?? 'component';\n const existing = this.functionRules.get(name);\n if (existing === undefined) {\n this.functionRules.set(name, css);\n this.setSource('function', name, source);\n if (source === 'component') {\n this.precompiledFunctions.add(name);\n this.precompiledRSCKeys.add(`__func:${name}`);\n }\n return;\n }\n if (source === 'component') {\n this.precompiledFunctions.add(name);\n this.precompiledRSCKeys.add(`__func:${name}`);\n if (existing === css) this.setSource('function', name, 'component');\n }\n if (options?.weak || existing === css) return;\n this.functionRules.set(name, css);\n this.setSource('function', name, source);\n if (source === 'component') {\n this.precompiledFunctions.add(name);\n this.precompiledRSCKeys.add(`__func:${name}`);\n }\n // If a rule with this name was already flushed (streaming), allow the\n // overriding rule to be flushed again so it wins by source order.\n this.flushedFunctionKeys.delete(name);\n }\n\n /**\n * Allocate a counter-style name for SSR. Uses provided name or generates one.\n */\n allocateCounterStyleName(providedName?: string): string {\n return (\n providedName ??\n makeCounterStyleName(this.namePrefix, String(this.counterStyleCounter++))\n );\n }\n\n /**\n * Record global styles (from useGlobalStyles). Deduplicated by key.\n *\n * Pass `replace` for slot-keyed entries (an explicit `id`), where the last\n * write must win to match the client's update-tracking behavior.\n */\n collectGlobalStyles(\n key: string,\n css: string,\n replace?: boolean,\n options?: CollectArtifactOptions,\n ): void {\n if (replace || !this.globalStyles.has(key)) {\n this.globalStyles.set(key, css);\n this.setSource('global', key, options?.source ?? 'global');\n }\n }\n\n /**\n * Record raw CSS text (from useRawCSS). Deduplicated by key.\n *\n * Pass `replace` for slot-keyed entries (an explicit `id`), where the last\n * write must win to match the client's update-tracking behavior.\n */\n collectRawCSS(\n key: string,\n css: string,\n replace?: boolean,\n options?: CollectArtifactOptions,\n ): void {\n if (replace || !this.rawCSS.has(key)) {\n this.rawCSS.set(key, css);\n this.setSource('raw', key, options?.source ?? 'global');\n }\n }\n\n getPrecompiledChunks(): TastyPrecompiledChunk[] {\n return [...this.precompiledChunks.values()];\n }\n\n getPrecompiledDependencies(): TastyPrecompiledDependencies {\n return {\n properties: [...this.precompiledProperties.values()],\n keyframes: [...this.precompiledKeyframes.values()],\n fontFaces: [...this.precompiledFontFaces],\n counterStyles: [...this.precompiledCounterStyles.values()],\n functions: [...this.precompiledFunctions],\n rscKeys: [...this.precompiledRSCKeys],\n };\n }\n\n /** @internal Structural top-level rule count for component artifacts. */\n getPrecompiledRuleCount(): number {\n const isComponent = (kind: ServerStyleArtifactKind, key: string) =>\n (this.artifactSources.get(this.sourceKey(kind, key)) ?? 'component') ===\n 'component';\n\n let count = 0;\n for (const key of this.propertyRules.keys()) {\n if (isComponent('property', key)) count++;\n }\n for (const key of this.fontFaceRules.keys()) {\n if (isComponent('font-face', key)) count++;\n }\n for (const key of this.counterStyleRules.keys()) {\n if (isComponent('counter-style', key)) count++;\n }\n for (const key of this.functionRules.keys()) {\n if (isComponent('function', key)) count++;\n }\n for (const key of this.chunks.keys()) {\n if (isComponent('chunk', key)) {\n count += this.chunkRuleCounts.get(key) ?? 0;\n }\n }\n for (const key of this.keyframeRules.keys()) {\n if (isComponent('keyframes', key)) count++;\n }\n\n return count;\n }\n\n /**\n * Return the collected CSS as structured, ordered artifacts.\n *\n * Artifact boundaries are part of the collector output so build tools never\n * need to split or parse CSS text. IDs include the logical collection key\n * and content, making them stable across equivalent page renders while a CSS\n * change always produces a different ID.\n */\n getArtifacts(): ServerStyleArtifact[] {\n const artifacts: ServerStyleArtifact[] = [];\n\n const append = (\n kind: ServerStyleArtifactKind,\n entries: Iterable<[string, string]>,\n ) => {\n for (const [key, css] of entries) {\n artifacts.push({\n id: artifactId(kind, key, css),\n kind,\n css,\n order: artifacts.length,\n source:\n this.artifactSources.get(this.sourceKey(kind, key)) ?? 'component',\n });\n }\n };\n\n append('property', this.propertyRules);\n append('font-face', this.fontFaceRules);\n append('counter-style', this.counterStyleRules);\n append('function', this.functionRules);\n append('raw', this.rawCSS);\n append('global', this.globalStyles);\n append('chunk', this.chunks);\n append('keyframes', this.keyframeRules);\n\n return artifacts;\n }\n\n /**\n * Extract all CSS collected so far as a single string.\n * Includes @property and @keyframes rules.\n * Used for non-streaming SSR (renderToString).\n */\n getCSS(): string {\n return this.getArtifacts()\n .map(({ css }) => css)\n .join('\\n');\n }\n\n /**\n * Flush only newly collected CSS since the last flush.\n * Used for streaming SSR (renderToPipeableStream + useServerInsertedHTML).\n */\n flushCSS(): string {\n const parts: string[] = [];\n\n for (const [name, css] of this.propertyRules) {\n if (!this.flushedPropertyKeys.has(name)) {\n parts.push(css);\n this.flushedPropertyKeys.add(name);\n }\n }\n\n for (const [key, css] of this.fontFaceRules) {\n if (!this.flushedFontFaceKeys.has(key)) {\n parts.push(css);\n this.flushedFontFaceKeys.add(key);\n }\n }\n\n for (const [key, css] of this.counterStyleRules) {\n if (!this.flushedCounterStyleKeys.has(key)) {\n parts.push(css);\n this.flushedCounterStyleKeys.add(key);\n }\n }\n\n for (const [key, css] of this.functionRules) {\n if (!this.flushedFunctionKeys.has(key)) {\n parts.push(css);\n this.flushedFunctionKeys.add(key);\n }\n }\n\n for (const [key, css] of this.rawCSS) {\n if (!this.flushedRawKeys.has(key)) {\n parts.push(css);\n this.flushedRawKeys.add(key);\n }\n }\n\n for (const [key, css] of this.globalStyles) {\n if (!this.flushedGlobalKeys.has(key)) {\n parts.push(css);\n this.flushedGlobalKeys.add(key);\n }\n }\n\n for (const [key, css] of this.chunks) {\n if (!this.flushedKeys.has(key)) {\n parts.push(css);\n this.flushedKeys.add(key);\n }\n }\n\n for (const [name, css] of this.keyframeRules) {\n if (!this.flushedKeyframeKeys.has(name)) {\n parts.push(css);\n this.flushedKeyframeKeys.add(name);\n }\n }\n\n return parts.join('\\n');\n }\n\n private flushedClassNames = new Set<string>();\n\n /**\n * Return class names rendered since the last call (for streaming).\n * Used to emit lightweight class-list scripts for client hydration.\n */\n getRenderedClassNames(): string[] {\n const names: string[] = [];\n for (const className of this.cacheKeyToClassName.values()) {\n if (!this.flushedClassNames.has(className)) {\n this.flushedClassNames.add(className);\n names.push(className);\n }\n }\n return names;\n }\n}\n\n/**\n * Factory for creating a {@link ServerStyleCollector} instance.\n *\n * Canonical functional entry point; the `ServerStyleCollector` class remains\n * exported for advanced/internal use.\n *\n * @param namePrefix - Optional override for the configured class-name prefix.\n * Defaults to the value from `configure({ namePrefix })` (or `'t'`).\n *\n * @example\n * ```ts\n * import { createServerStyleCollector } from '@tenphi/tasty/ssr';\n *\n * const collector = createServerStyleCollector();\n * ```\n */\nexport function createServerStyleCollector(\n namePrefix?: string,\n): ServerStyleCollector {\n return new ServerStyleCollector(namePrefix);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+FA,SAAS,WAAW,MAA+B,KAAa,KAAa;CAC3E,MAAM,UAAU,GAAG,KAAK,IAAI,IAAI,IAAI;CACpC,OAAO,GAAG,KAAK,GAAG,WAAW,OAAO,EAAE,GAAG,QAAQ,OAAO,SAAS,EAAE;AACrE;AAEA,IAAa,uBAAb,MAAkC;CAChC,yBAAiB,IAAI,IAAoB;CACzC,kCAA0B,IAAI,IAAoB;CAClD,sCAA8B,IAAI,IAAoB;CACtD,8BAAsB,IAAI,IAAY;CACtC,gCAAwB,IAAI,IAAoB;CAChD,sCAA8B,IAAI,IAAY;CAC9C,gCAAwB,IAAI,IAAoB;CAChD,sCAA8B,IAAI,IAAY;CAC9C,+BAAuB,IAAI,IAAoB;CAC/C,oCAA4B,IAAI,IAAY;CAC5C,yBAAiB,IAAI,IAAoB;CACzC,iCAAyB,IAAI,IAAY;CACzC,gCAAwB,IAAI,IAAoB;CAChD,sCAA8B,IAA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BAAoB,IAAI,IAAI,GAAG;GACvC,MAAM,KAAK,GAAG;GACd,KAAK,oBAAoB,IAAI,IAAI;EACnC;EAGF,OAAO,MAAM,KAAK,IAAI;CACxB;CAEA,oCAA4B,IAAI,IAAY;;;;;CAM5C,wBAAkC;EAChC,MAAM,QAAkB,CAAC;EACzB,KAAK,MAAM,aAAa,KAAK,oBAAoB,OAAO,GACtD,IAAI,CAAC,KAAK,kBAAkB,IAAI,SAAS,GAAG;GAC1C,KAAK,kBAAkB,IAAI,SAAS;GACpC,MAAM,KAAK,SAAS;EACtB;EAEF,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;AAkBA,SAAgB,2BACd,YACsB;CACtB,OAAO,IAAI,qBAAqB,UAAU;AAC5C"}
@@ -11902,25 +11902,33 @@ function warnOnce(key, message) {
11902
11902
  }
11903
11903
  let stylesGenerated = false;
11904
11904
  /**
11905
- * Names of the style handlers and props middleware this host configured,
11906
- * accumulated across every `configure()` call.
11905
+ * What the host passed to `configure()`, for the settings whose live registry
11906
+ * is not a faithful record of it. Accumulated across every `configure()` call.
11907
+ *
11908
+ * - Handlers and props middleware: `configure()` applies them into the handler
11909
+ * registry and then strips them from the stored config, and that registry is
11910
+ * populated lazily as styles are encountered — so neither is a stable record
11911
+ * of what the host asked for.
11912
+ * - Declarative `@function` definitions: with `polyfills.functions` enabled,
11913
+ * `configure()` compiles each into a parse-function closure and deliberately
11914
+ * leaves `getGlobalFunctions()` empty, so the definition body survives
11915
+ * nowhere a fingerprint can read it.
11907
11916
  *
11908
- * `configure()` applies these into the handler registry and then strips them
11909
- * from the stored config, and the registry itself is populated lazily as styles
11910
- * are encountered — so neither is a stable record of what the host asked for.
11911
11917
  * A precompiled catalog needs exactly that record: replacing a built-in handler
11912
- * changes what an already-compiled chunk should contain without changing its
11913
- * lookup key.
11918
+ * or rewriting a function body changes what an already-compiled chunk should
11919
+ * contain without changing its lookup key.
11914
11920
  */
11915
11921
  const configuredOverrides = {
11916
11922
  handlers: [],
11917
- propHandlers: []
11923
+ propHandlers: [],
11924
+ functions: []
11918
11925
  };
11919
11926
  /** @internal */
11920
11927
  function getConfiguredOverrides() {
11921
11928
  return {
11922
11929
  handlers: configuredOverrides.handlers,
11923
- propHandlers: configuredOverrides.propHandlers
11930
+ propHandlers: configuredOverrides.propHandlers,
11931
+ functions: configuredOverrides.functions
11924
11932
  };
11925
11933
  }
11926
11934
  let currentConfig = null;
@@ -12545,8 +12553,11 @@ function configure(config = {}) {
12545
12553
  parser.setFunctions(finalFuncs);
12546
12554
  Object.assign(currentFuncs, parseFuncs);
12547
12555
  }
12548
- if (Object.keys(functionDefs).length > 0) if (isFunctionsPolyfillEnabled()) for (const [name, definition] of Object.entries(functionDefs)) registerFunctionPolyfill(name, definition);
12549
- else setGlobalFunction(functionDefs);
12556
+ if (Object.keys(functionDefs).length > 0) {
12557
+ for (const entry of Object.entries(functionDefs)) configuredOverrides.functions.push(entry);
12558
+ if (isFunctionsPolyfillEnabled()) for (const [name, definition] of Object.entries(functionDefs)) registerFunctionPolyfill(name, definition);
12559
+ else setGlobalFunction(functionDefs);
12560
+ }
12550
12561
  if (Object.keys(mergedKeyframes).length > 0) setGlobalKeyframes(mergedKeyframes);
12551
12562
  if (Object.keys(mergedProperties).length > 0) setGlobalProperties(mergedProperties);
12552
12563
  if (Object.keys(mergedFontFaces).length > 0) setGlobalFontFace(mergedFontFaces);
@@ -12640,6 +12651,7 @@ function resetConfig() {
12640
12651
  resetPropHandlers();
12641
12652
  configuredOverrides.handlers.length = 0;
12642
12653
  configuredOverrides.propHandlers.length = 0;
12654
+ configuredOverrides.functions.length = 0;
12643
12655
  resetBaseStyleProps();
12644
12656
  clearPipelineCache();
12645
12657
  resetPrecompiledStyles();
@@ -12651,4 +12663,4 @@ function resetConfig() {
12651
12663
  //#endregion
12652
12664
  export { getRegisteredPrecompiledDependencies as $, getGlobalParseFunctions as $t, DIMENSION_STYLES as A, extractLocalProperties as At, camelToKebab as B, FONT_CHUNK_STYLES as Bt, baseStylePropsRegistry as C, DEFAULT_ZERO_NAME_PREFIX as Ct, BLOCK_STYLES as D, tastyClassRegex as Dt, BLOCK_OUTER_STYLES as E, makeKeyframeName as Et, TEXT_STYLES as F, propHandlerRegistry as Ft, setGlobalPredefinedStates as G, formatFunctionRule as Gt, extractLocalPredefinedStates as H, POSITION_CHUNK_STYLES as Ht, hasPipelineCacheEntry as I, APPEARANCE_CHUNK_STYLES as It, beginPrecompileBuild as J, registerFunctionPolyfill as Jt, applyRegisteredDependenciesToInjector as K, hasLocalFunctions as Kt, isSelector as L, CHUNK_NAMES as Lt, INNER_STYLES as M, hasLocalProperties as Mt, OUTER_STYLES as N, normalizePropertyDefinition as Nt, COLOR_STYLES as O, validateNamePrefix as Ot, POSITION_STYLES as P, parsePropertyToken as Pt, getPrecompiledRevision as Q, filterMods as Qt, renderStyles as R, DIMENSION_CHUNK_STYLES as Rt, generateTypographyTokens as S, DEFAULT_NAME_PREFIX as St, BLOCK_INNER_STYLES as T, makeCounterStyleName as Tt, extractPredefinedStateRefs as U, STYLE_TO_CHUNK as Ut, createStateParserContext as V, LAYOUT_CHUNK_STYLES as Vt, getGlobalPredefinedStates as W, extractLocalFunctions as Wt, findPrecompiledChunk as X, CUSTOM_UNITS as Xt, endPrecompileBuild as Y, registerLocalFunctionPolyfills as Yt, getPrecompileStore as Z, DIRECTIONS as Zt, isConfigLocked as _, hexToRgb as _n, closeBatchWindow as _t, getGlobalConfigTokens as a, stringifyStyles as an, formatCounterStyleRule as at, markStylesGenerated as b, normalizeDslName as bn, openBatchWindow as bt, getGlobalFunctions as c, okhslFunction as cn, fontFaceContentHash as ct, getGlobalRecipes as d, isDevEnv as dn, SheetManager as dt, getGlobalParser as en, getRegisteredPrecompiledStats as et, getGlobalStyles as f, StyleParser as fn, STYLE_HANDLER_MAP as ft, hasStylesGenerated as g, getRgbValuesFromRgbaString as gn, PropertyTypeResolver as gt, hasGlobalRecipes as h, getNamedColorHex as hn, createStyle as ht, getEffectiveProperties as i, parseStyle as in, extractLocalCounterStyle as it, FLOW_STYLES as j, getEffectiveDefinition as jt, CONTAINER_STYLES as k, hashString as kt, getGlobalInjector as l, okhslPlugin as ln, formatFontFaceRule as lt, hasGlobalKeyframes as m, overrideColorAlpha as mn, styleHandlers as mt, getConfig as n, normalizeColorTokenValue as nn, warnPrecompileOnce as nt, getGlobalCounterStyles as o, okhstFunction as on, hasLocalCounterStyle as ot, getNamePrefix as p, Lru as pn, defineHandler as pt, applyRegisteredDependenciesToRSC as q, parseFunctionName as qt, getConfiguredOverrides as r, parseColor as rn, StyleInjector as rt, getGlobalFontFaces as s, okhstPlugin as sn, extractLocalFontFace as st, configure as t, getGlobalPredefinedTokens as tn, precompileRuntimeState as tt, getGlobalKeyframes as u, createColorFunc as un, hasLocalFontFace as ut, isFunctionsPolyfillEnabled as v, hslToRgbValues as vn, flushStyles as vt, BASE_STYLES as w, makeClassName as wt, resetConfig as x, resetStyleBatch as xt, isTestEnvironment as y, strToRgb as yn, hasPendingStyleWrites as yt, parseStateKey as z, DISPLAY_CHUNK_STYLES as zt };
12653
12665
 
12654
- //# sourceMappingURL=config-wc1IKOU3.js.map
12666
+ //# sourceMappingURL=config-Bd2vOF0Z.js.map