@tiqian/precompute 0.0.0-stage → 0.1.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,324 @@
1
+ // The HTML preparer entry over the generated shared lanes (Html-B2). The
2
+ // exported surface matches the former `@tiqian/web-component/precompute-html` module.
3
+ // Parsing, selection, projection and the prepare orchestration run here in
4
+ // TypeScript over linkedom and the B1 generated modules; the paragraph and
5
+ // font-contract lanes, the snapshot tables and the bundle assembly stay in the
6
+ // native precomputer calls the precompute module wraps. The DOM projection
7
+ // callback needs a host DOM, so this lane rejects it by name.
8
+ import { createHash } from "node:crypto";
9
+ import { parseHTML } from "linkedom";
10
+ import { absorbSnapshotTables, assembleFontContractBundle, assembleSnapshotBundle, closeSnapshotTables, createPrecomputer, createSnapshotTables, finalizeSnapshotTables, precomputerHandle, renderFontContractBundleData, renderSnapshotBundleData, } from "./precompute.js";
11
+ import { projectedTextOnly, snapshotProjection } from "./precompute-html-projection.js";
12
+ import { CompoundSelector } from "@tiqian/shared/org/tiqian/shared/html/CompoundSelector";
13
+ import { DomParser } from "@tiqian/shared/org/tiqian/shared/html/DomParser";
14
+ import { HtmlParseException } from "@tiqian/shared/org/tiqian/shared/html/HtmlParseException";
15
+ import { HtmlScan } from "@tiqian/shared/org/tiqian/shared/html/HtmlScan";
16
+ const DEFAULT_PARAGRAPH_SELECTOR = "p, li";
17
+ const DEFAULT_SKIPPED_ANCESTOR_SELECTOR = "[data-tiqian-skip], pre, table, .not-prose, .katex, .katex-display, .expressive-code";
18
+ const SOURCE_MAP_IGNORED_ANCESTOR_SELECTOR = "iframe, noembed, noframes, noscript, plaintext, xmp";
19
+ const LIST_ITEM_CONTAINER_TAGS = new Set(["p", "ul", "ol", "blockquote", "pre", "table"]);
20
+ const PREPARE_ROOT_MARKUP = "<main data-tq-html-prepare-root>";
21
+ /**
22
+ * Locates source opening tags without serializing the host's HTML; the scan
23
+ * runs on UTF-16 code units and skips raw-text containers and inert templates
24
+ * so a literal `<p>` example never receives a live snapshot key.
25
+ */
26
+ export function findHtmlOpeningTags(html, tagNames = ["p", "li"]) {
27
+ return HtmlScan.findHtmlOpeningTags(html, Array.from(tagNames ?? []));
28
+ }
29
+ /** Inserts attribute strings at the given offsets, highest offset first. */
30
+ export function injectHtmlAttributes(html, insertions) {
31
+ const rows = Array.from(insertions ?? []).map(({ offset, attribute }) => ({ offset, attribute }));
32
+ try {
33
+ return HtmlScan.injectHtmlAttributes(html, rows);
34
+ }
35
+ catch (error) {
36
+ if (error instanceof HtmlParseException) {
37
+ throw new Error(error.message, { cause: error });
38
+ }
39
+ throw error;
40
+ }
41
+ }
42
+ /** The payload a server template inlines. */
43
+ export function snapshotServerAssets(bundle) {
44
+ if (!bundle)
45
+ return null;
46
+ return Object.freeze({
47
+ id: bundle.id,
48
+ initialStyle: bundle.initialStyle,
49
+ inertTemplate: bundle.inertTemplate,
50
+ fontPreloads: Object.freeze([...bundle.fontPreloads]),
51
+ });
52
+ }
53
+ /** Preload links, the first paint style and the inert template, concatenated. */
54
+ export function renderSnapshotServerAssets(assets) {
55
+ if (!assets)
56
+ return "";
57
+ const preloads = assets.fontPreloads
58
+ .map((href) => `<link rel="preload" as="font" type="font/woff2" crossorigin href="${escapeAttribute(href)}">`)
59
+ .join("");
60
+ return `${preloads}<style data-tq-initial-snapshot="${escapeAttribute(assets.id)}">${assets.initialStyle}</style>${assets.inertTemplate}`;
61
+ }
62
+ function escapeAttribute(value) {
63
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
64
+ }
65
+ function parseSelectorList(selector) {
66
+ try {
67
+ return CompoundSelector.parseCompoundSelectorList(selector);
68
+ }
69
+ catch (error) {
70
+ if (error instanceof HtmlParseException)
71
+ throw new Error(error.message, { cause: error });
72
+ throw error;
73
+ }
74
+ }
75
+ /** selectedTagNames: comma separated tag names only, trimmed and lowercased. */
76
+ function selectedTagNames(selector) {
77
+ const names = selector.split(",").map((item) => item.trim().toLowerCase());
78
+ const valid = (name) => /^[a-z][a-z0-9-]*$/u.test(name);
79
+ if (names.some((name) => !valid(name))) {
80
+ throw new Error("UnsupportedHtmlParagraphSelector");
81
+ }
82
+ return names;
83
+ }
84
+ function parseDocument(markup) {
85
+ const window = parseHTML(markup);
86
+ return new DomParser(window.document);
87
+ }
88
+ /** nestedListItem: a list item that owns a block container keeps its layout in the host. */
89
+ function nestedListItem(parser, element) {
90
+ if (parser.tagName(element) !== "li")
91
+ return false;
92
+ return parser
93
+ .elementChildren(element)
94
+ .some((child) => LIST_ITEM_CONTAINER_TAGS.has(parser.tagName(child)));
95
+ }
96
+ function prepareId(html, width, explicit) {
97
+ if (typeof explicit === "string")
98
+ return explicit;
99
+ const hash = createHash("sha256").update(html, "utf8").update(Buffer.from([0]));
100
+ hash.update(width === null ? "runtime" : String(width), "utf8");
101
+ return `tq-prose-${hash.digest("hex").slice(0, 16)}`;
102
+ }
103
+ /**
104
+ * Creates the framework-neutral server boundary consumed by SvelteKit and
105
+ * Astro integrations. Host HTML remains byte-for-byte intact except for
106
+ * snapshot keys inserted into paragraphs that produced reusable geometry.
107
+ * `projectSnapshotParagraph` needs a host DOM and throws
108
+ * `UnsupportedHtmlProjector` here; hosts projecting rich semantics keep the
109
+ * `@tiqian/web-component` entry.
110
+ */
111
+ export async function createHtmlPreparer(options) {
112
+ if (typeof options.projectSnapshotParagraph === "function") {
113
+ throw new Error("UnsupportedHtmlProjector");
114
+ }
115
+ let precomputer;
116
+ let ownsPrecomputer;
117
+ if (options.precomputer) {
118
+ if (precomputerHandle(options.precomputer) === null) {
119
+ throw new Error("ForeignPrecomputer");
120
+ }
121
+ precomputer = options.precomputer;
122
+ ownsPrecomputer = false;
123
+ }
124
+ else {
125
+ // The typography validates before any font file is read, the js order.
126
+ precomputer = await createPrecomputer({
127
+ typography: options.typography,
128
+ faces: options.faces,
129
+ fontStylesheets: options.fontStylesheets,
130
+ });
131
+ ownsPrecomputer = true;
132
+ }
133
+ const tagNames = selectedTagNames(options.paragraphSelector ?? DEFAULT_PARAGRAPH_SELECTOR);
134
+ const skipped = parseSelectorList(options.skippedAncestorSelector ?? DEFAULT_SKIPPED_ANCESTOR_SELECTOR);
135
+ const sourceMapIgnored = parseSelectorList(SOURCE_MAP_IGNORED_ANCESTOR_SELECTOR);
136
+ let closed = false;
137
+ async function prepare(html, prepareOptions = {}) {
138
+ if (closed)
139
+ throw new Error("HtmlPreparerClosed");
140
+ const rawWidth = prepareOptions.snapshot?.maxWidthPx;
141
+ const width = rawWidth === undefined || rawWidth === null ? null : Number(rawWidth);
142
+ if (width !== null && (!Number.isFinite(width) || width <= 0)) {
143
+ throw new Error("InvalidMaximumMeasure");
144
+ }
145
+ const id = prepareId(String(html), width, prepareOptions.id);
146
+ const parser = parseDocument(`${PREPARE_ROOT_MARKUP}${html}</main>`);
147
+ const root = parser
148
+ .descendantsByTag(parser.documentNode(), ["main"])
149
+ .find((element) => parser.attributeValue(element, "data-tq-html-prepare-root") !== null);
150
+ if (root === undefined)
151
+ throw new Error("HtmlPrepareRootUnavailable");
152
+ const sourceElements = parser
153
+ .descendantsByTag(root, tagNames)
154
+ .filter((element) => !parser.closest(element, sourceMapIgnored));
155
+ const openingTags = HtmlScan.findHtmlOpeningTags(String(html), tagNames);
156
+ if (sourceElements.length !== openingTags.length) {
157
+ throw new Error(`HtmlParagraphSourceMapMismatch:${sourceElements.length}:${openingTags.length}`);
158
+ }
159
+ const plans = [];
160
+ for (let index = 0; index < sourceElements.length; index += 1) {
161
+ const element = sourceElements[index];
162
+ const openingTag = openingTags[index];
163
+ if (openingTag.tagName !== parser.tagName(element)) {
164
+ throw new Error(`HtmlParagraphSourceOrderMismatch:${index}`);
165
+ }
166
+ if (parser.closest(element, skipped) || nestedListItem(parser, element))
167
+ continue;
168
+ const projected = snapshotProjection(element);
169
+ const text = projected === null ? projectedTextOnly(element) : projected.text;
170
+ if (text.trim().length === 0)
171
+ continue;
172
+ plans.push({ index, openingTagEnd: openingTag.end, projected, text });
173
+ }
174
+ // Phase one: one whole element sequence per native batch. The snapshot
175
+ // attempt runs first and the contract fallback runs after it, so an element
176
+ // keeps the sequential lane's branching and issue order.
177
+ const snapshotByIndex = new Map();
178
+ const snapshotPlans = width === null ? [] : plans.filter((plan) => plan.projected !== null);
179
+ if (snapshotPlans.length > 0 && width !== null) {
180
+ const inputs = snapshotPlans.map((plan) => ({
181
+ key: `p-${plan.index}`,
182
+ text: plan.projected.text,
183
+ maxWidthPx: width,
184
+ semantics: [],
185
+ textSpans: [],
186
+ inlineBoxes: [],
187
+ sourceBoundaries: [],
188
+ }));
189
+ const entries = await precomputer.prepareParagraphs(inputs);
190
+ for (let index = 0; index < snapshotPlans.length; index += 1) {
191
+ snapshotByIndex.set(snapshotPlans[index].index, entries[index]);
192
+ }
193
+ }
194
+ const contractPlans = plans.filter((plan) => {
195
+ const snapshot = snapshotByIndex.get(plan.index);
196
+ return snapshot === undefined || snapshot.status !== "prepared";
197
+ });
198
+ const contractByIndex = new Map();
199
+ if (contractPlans.length > 0) {
200
+ const inputs = contractPlans.map((plan) => ({
201
+ key: `f-${plan.index}`,
202
+ text: plan.text,
203
+ ...(plan.projected === null
204
+ ? {}
205
+ : { semantics: [], textSpans: [], inlineBoxes: [], sourceBoundaries: [] }),
206
+ }));
207
+ const entries = await precomputer.prepareFontContracts(inputs);
208
+ for (let index = 0; index < contractPlans.length; index += 1) {
209
+ contractByIndex.set(contractPlans[index].index, entries[index]);
210
+ }
211
+ }
212
+ // Phase two: rebuild the sequential arrays. Document order holds, and an
213
+ // element's snapshot issue stays ahead of its contract issue.
214
+ const preparedParagraphs = [];
215
+ const fontContracts = [];
216
+ const insertions = [];
217
+ const issues = [];
218
+ for (const plan of plans) {
219
+ const snapshot = snapshotByIndex.get(plan.index);
220
+ if (snapshot !== undefined) {
221
+ if (snapshot.status === "prepared") {
222
+ preparedParagraphs.push(snapshot);
223
+ insertions.push({
224
+ offset: plan.openingTagEnd,
225
+ attribute: ` data-tq-snapshot-key="p-${plan.index}"`,
226
+ });
227
+ }
228
+ else {
229
+ issues.push({ index: plan.index, key: `p-${plan.index}`, stage: "snapshot", issue: snapshot.issue });
230
+ }
231
+ }
232
+ const contract = contractByIndex.get(plan.index);
233
+ if (contract !== undefined) {
234
+ if (contract.status === "prepared") {
235
+ fontContracts.push(contract);
236
+ }
237
+ else {
238
+ issues.push({
239
+ index: plan.index,
240
+ key: `f-${plan.index}`,
241
+ stage: "font-contract",
242
+ issue: contract.issue,
243
+ });
244
+ }
245
+ }
246
+ }
247
+ let bundle = null;
248
+ let tables = null;
249
+ if (preparedParagraphs.length > 0) {
250
+ const handles = createSnapshotTables();
251
+ try {
252
+ absorbSnapshotTables(handles, [...preparedParagraphs, ...fontContracts]);
253
+ const data = renderSnapshotBundleData(preparedParagraphs, {
254
+ id,
255
+ fontContractParagraphs: fontContracts,
256
+ snapshotTables: handles,
257
+ });
258
+ const file = finalizeSnapshotTables(handles);
259
+ bundle = assembleSnapshotBundle(data, handles);
260
+ tables = Object.freeze({ bytes: file.bytes, sha256: file.sha256 });
261
+ }
262
+ finally {
263
+ closeSnapshotTables(handles);
264
+ }
265
+ }
266
+ else if (fontContracts.length > 0) {
267
+ const handles = createSnapshotTables();
268
+ try {
269
+ absorbSnapshotTables(handles, fontContracts);
270
+ const data = renderFontContractBundleData(fontContracts, { id, snapshotTables: handles });
271
+ const file = finalizeSnapshotTables(handles);
272
+ bundle = assembleFontContractBundle(data, handles);
273
+ tables = Object.freeze({ bytes: file.bytes, sha256: file.sha256 });
274
+ }
275
+ finally {
276
+ closeSnapshotTables(handles);
277
+ }
278
+ }
279
+ const preparedHtml = injectHtmlAttributes(String(html), insertions);
280
+ const rootAttributes = {};
281
+ if (bundle) {
282
+ rootAttributes["snapshot-ref"] = bundle.id;
283
+ for (const [name, value] of Object.entries(bundle.rootAttributes)) {
284
+ rootAttributes[name] = String(value);
285
+ }
286
+ }
287
+ const clientBundle = bundle
288
+ ? Object.freeze({
289
+ id: bundle.id,
290
+ clientTemplate: bundle.clientTemplate,
291
+ initialStyle: bundle.initialStyle,
292
+ fontPreloads: Object.freeze([...bundle.fontPreloads]),
293
+ })
294
+ : null;
295
+ const serverAssets = bundle
296
+ ? Object.freeze({
297
+ id: bundle.id,
298
+ initialStyle: bundle.initialStyle,
299
+ inertTemplate: bundle.inertTemplate,
300
+ fontPreloads: Object.freeze([...bundle.fontPreloads]),
301
+ })
302
+ : null;
303
+ return Object.freeze({
304
+ html: preparedHtml,
305
+ rootAttributes: Object.freeze(rootAttributes),
306
+ bundle,
307
+ clientBundle,
308
+ serverAssets,
309
+ tables,
310
+ issues: Object.freeze(issues),
311
+ });
312
+ }
313
+ return Object.freeze({
314
+ typography: precomputer.typography,
315
+ prepare,
316
+ close() {
317
+ if (closed)
318
+ return;
319
+ closed = true;
320
+ if (ownsPrecomputer)
321
+ precomputer.close();
322
+ },
323
+ });
324
+ }
@@ -0,0 +1,323 @@
1
+ import { ValueStyleInterner } from "@tiqian/shared/org/tiqian/shared/ValueStyleInterner";
2
+ import type { CacheBridge } from "./cache.js";
3
+ /** The wire face + font byte arrays the native create calls consume. */
4
+ export interface ResolvedFaces {
5
+ faces: Array<{
6
+ family: string;
7
+ publicUrl: string;
8
+ font: number;
9
+ faceIndex: number | null;
10
+ weight?: number | readonly [number, number];
11
+ style?: string;
12
+ unicodeRange: string | null;
13
+ sourceOrder: number | null;
14
+ }>;
15
+ sources: Buffer[];
16
+ }
17
+ /**
18
+ * Resolves the face inputs of the create calls. Explicit faces carry their
19
+ * bytes; the stylesheet lane reads the CSS here, parses it in Rust and reads
20
+ * the font files the parse resolved. `sourceOrder` accumulates across
21
+ * stylesheets, the js order.
22
+ */
23
+ export declare function resolveFaces(options: CreatePrecomputerOptions): Promise<ResolvedFaces>;
24
+ export interface BuildFontFace {
25
+ /** Host CSS family used for both build-time measurement and browser paint. */
26
+ family: string;
27
+ source: string | URL | Uint8Array | ArrayBuffer;
28
+ publicUrl: string;
29
+ faceIndex?: 0;
30
+ weight?: number | readonly [number, number];
31
+ style?: "normal" | "italic";
32
+ unicodeRange?: string;
33
+ }
34
+ export interface BuildFontStylesheet {
35
+ /** Local CSS file read by the Node precomputer. */
36
+ source: string | URL;
37
+ /** URL where the host serves that same stylesheet; relative font URLs resolve from here. */
38
+ publicUrl?: string;
39
+ }
40
+ export interface SnapshotTypography {
41
+ readonly fontFamilies: readonly string[];
42
+ readonly fontSizePx: number;
43
+ readonly lineHeightPx: number;
44
+ readonly locale?: "zh-Hans";
45
+ readonly fontWeight?: number;
46
+ readonly italic?: boolean;
47
+ readonly firstLineIndentIc?: 0;
48
+ readonly lineLengthGridEnabled?: true;
49
+ readonly letterSpacingPx?: 0;
50
+ readonly fontFeatureSettings?: "normal";
51
+ readonly fontVariationSettings?: "normal";
52
+ readonly fontVariantNumeric?: "normal" | "lining-nums";
53
+ }
54
+ /** The normalized typography the precomputer froze at creation. */
55
+ export interface NormalizedTypography {
56
+ readonly fontFamilies: readonly string[];
57
+ readonly fontSizePx: number;
58
+ readonly lineHeightPx: number;
59
+ readonly locale: string;
60
+ readonly fontWeight: number;
61
+ readonly italic: boolean;
62
+ readonly firstLineIndentIc: number;
63
+ readonly lineLengthGridEnabled: boolean;
64
+ readonly letterSpacingPx: number;
65
+ readonly fontFeatureSettings: string;
66
+ readonly fontVariationSettings: string;
67
+ readonly fontVariantNumeric: string;
68
+ }
69
+ export interface SnapshotSemanticSpan {
70
+ readonly start: number;
71
+ readonly end: number;
72
+ readonly tagName: "a" | "abbr" | "b" | "bdi" | "bdo" | "cite" | "code" | "data" | "del" | "dfn" | "em" | "i" | "ins" | "kbd" | "mark" | "q" | "s" | "samp" | "small" | "span" | "strong" | "sub" | "sup" | "time" | "u" | "var";
73
+ readonly attributes?: Readonly<Record<string, string>> | readonly (readonly [string, string])[];
74
+ }
75
+ export interface SnapshotTextSpan {
76
+ readonly start: number;
77
+ readonly end: number;
78
+ readonly fontFamilies?: readonly string[];
79
+ readonly fontSizePx?: number;
80
+ readonly fontWeight?: number;
81
+ readonly italic?: boolean;
82
+ readonly baselineShiftPx?: number;
83
+ /** Complete CSS numeric variant for this run, replacing paragraph defaults. */
84
+ readonly fontVariantNumeric?: string;
85
+ }
86
+ export interface SnapshotInlineBox {
87
+ readonly start: number;
88
+ readonly end: number;
89
+ readonly inlineStartPx?: number;
90
+ readonly inlineEndPx?: number;
91
+ }
92
+ export interface SnapshotParagraphInput {
93
+ key: string;
94
+ text: string;
95
+ maxWidthPx: number;
96
+ semantics?: readonly SnapshotSemanticSpan[];
97
+ /** Required with full explicit metrics for every `code` semantic range. */
98
+ textSpans?: readonly SnapshotTextSpan[];
99
+ /** Required even for zero edges for every `code` semantic range. */
100
+ inlineBoxes?: readonly SnapshotInlineBox[];
101
+ sourceBoundaries?: readonly number[];
102
+ }
103
+ export interface FontContractInput {
104
+ key: string;
105
+ text: string;
106
+ semantics?: readonly SnapshotSemanticSpan[];
107
+ textSpans?: readonly SnapshotTextSpan[];
108
+ inlineBoxes?: readonly SnapshotInlineBox[];
109
+ sourceBoundaries?: readonly number[];
110
+ /** @deprecated Font evidence is width-independent; this value is ignored. */
111
+ maxWidthPx?: number;
112
+ }
113
+ export type PreparedParagraph = {
114
+ readonly status: "prepared";
115
+ readonly schema: 1;
116
+ readonly layoutRevision: string;
117
+ readonly renderRevision: string;
118
+ readonly key: string;
119
+ readonly sourceText: string;
120
+ readonly sourceSha256: string;
121
+ readonly sourceArtifactSha256: string;
122
+ readonly semantics: readonly SnapshotSemanticSpan[];
123
+ readonly inlineBoxes: readonly SnapshotInlineBox[];
124
+ readonly renderTextSpans: readonly {
125
+ readonly start: number;
126
+ readonly end: number;
127
+ readonly fontFamilies: readonly string[];
128
+ }[];
129
+ readonly typographySha256: string;
130
+ readonly maxWidthPx: number;
131
+ readonly typography: NormalizedTypography;
132
+ readonly renderFontFamilies: readonly string[];
133
+ readonly fontEvidence: unknown;
134
+ readonly plan: unknown;
135
+ readonly html: string;
136
+ readonly renderArtifactSha256: string;
137
+ } | {
138
+ readonly status: "unsupported";
139
+ readonly key: string;
140
+ readonly issue: string;
141
+ readonly detail?: string;
142
+ };
143
+ export type PreparedEntry = PreparedParagraph;
144
+ export interface Precomputer {
145
+ readonly typography: NormalizedTypography;
146
+ readonly renderFontFamilies: readonly string[];
147
+ prepareParagraph(input: SnapshotParagraphInput): Promise<PreparedEntry>;
148
+ /**
149
+ * The batch snapshot lane: every paragraph in one native call, the loop in
150
+ * Rust. Session evidence accumulates in input order, matching the sequence
151
+ * of individual `prepareParagraph` calls.
152
+ */
153
+ prepareParagraphs(inputs: readonly SnapshotParagraphInput[]): Promise<PreparedEntry[]>;
154
+ /** Capture exact-font and server-replay evidence for runtime-only or semantic prose. */
155
+ prepareFontContract(input: FontContractInput): Promise<PreparedEntry>;
156
+ /**
157
+ * The batch contract lane: every contract in one native call, the loop in
158
+ * Rust. Entries come back in input order with the lowest failing index
159
+ * reported as an error, matching the sequence of individual
160
+ * `prepareFontContract` calls.
161
+ */
162
+ prepareFontContracts(inputs: readonly FontContractInput[]): Promise<PreparedEntry[]>;
163
+ /**
164
+ * The cache and submission bridge of this precomputer (ADR 0052). The
165
+ * property is present only when the platform build carries the bridge;
166
+ * the batch renderer and the layered cache live behind it.
167
+ */
168
+ readonly cache: CacheBridge;
169
+ close(): void;
170
+ }
171
+ /**
172
+ * The write-budget posture of a precomputer's drain queue (ADR 0052): the
173
+ * host picks a tier by environment, the engine owns the tier-to-bytes table.
174
+ * Every tier clears the largest single record; a submit past the budget
175
+ * throws `CacheWriteBufferFull` until the host flushes.
176
+ */
177
+ export type CacheWriteBudget = "tight" | "normal" | "generous";
178
+ /** Name constants of {@link CacheWriteBudget}. */
179
+ export declare const CacheWriteBudget: Readonly<{
180
+ readonly Tight: "tight";
181
+ readonly Normal: "normal";
182
+ readonly Generous: "generous";
183
+ }>;
184
+ /**
185
+ * Sets the process default every later `createPrecomputer` call uses when its
186
+ * options name no tier. Precomputers already created keep theirs.
187
+ */
188
+ export declare function setCacheWriteBudget(budget: CacheWriteBudget): void;
189
+ export interface CreatePrecomputerOptions {
190
+ /** Normal integration: reuse the host's existing @font-face stylesheet. */
191
+ fontStylesheets?: readonly BuildFontStylesheet[];
192
+ /** Low-level integration for generated font systems. Mutually exclusive with fontStylesheets. */
193
+ faces?: readonly BuildFontFace[];
194
+ typography: SnapshotTypography;
195
+ /**
196
+ * The drain-queue write budget of this precomputer; defaults to the
197
+ * process default, initially "normal".
198
+ */
199
+ cacheWriteBudget?: CacheWriteBudget;
200
+ }
201
+ /**
202
+ * Internal: the native registry handle of a precomputer created by this
203
+ * package, for the HTML preparer entry in `precompute-html.ts`.
204
+ */
205
+ export declare function precomputerHandle(precomputer: Precomputer): string | null;
206
+ /**
207
+ * Overwrites the render fields of a prepared entry with the Node-computed
208
+ * values, then freezes the entry. This applies to snapshots and font contracts.
209
+ * Unsupported entries are frozen without adding render fields.
210
+ */
211
+ export declare function backfillRenderFields(entry: PreparedEntry): PreparedEntry;
212
+ /**
213
+ * Creates a precomputer from explicit faces or a host font stylesheet. The
214
+ * typography is normalized in Rust; every named validation error of the js
215
+ * implementation is thrown at the same step.
216
+ */
217
+ export declare function createPrecomputer(options: CreatePrecomputerOptions): Promise<Precomputer>;
218
+ /**
219
+ * Renders one prepared plan to prepared DOM. The implementation is the exact
220
+ * browser-shared module `@tiqian/web-component` ships, so server embedders and the
221
+ * browser agree on every revision.
222
+ */
223
+ export declare function renderPreparedParagraph(plan: unknown, typography: SnapshotTypography): string;
224
+ /** The named plain-text gate of the snapshot lane. */
225
+ export declare function snapshotPlainTextIssue(text: string): string | null;
226
+ export interface SnapshotBundle {
227
+ readonly id: string;
228
+ /** Backward-compatible alias of inertTemplate. */
229
+ readonly template: string;
230
+ /** Inert manifest and prepared DOM adopted only after live geometry validation. */
231
+ readonly inertTemplate: string;
232
+ /** Compact exact-font and server-replay manifest for client-side navigation fallback. */
233
+ readonly clientTemplate: string;
234
+ readonly initialStyle: string;
235
+ readonly renderFontFamilies: readonly string[];
236
+ readonly fontPreloads: readonly string[];
237
+ readonly rootAttributes: Readonly<Partial<Record<"data-tiqian-snapshot-render-font", "true">>>;
238
+ readonly entries: readonly {
239
+ readonly key: string;
240
+ readonly html: string;
241
+ }[];
242
+ }
243
+ /** One build's snapshot tables (ADR 0052 `BundleLayering`): the shared rows
244
+ * every article of the build shares. Absorb first, render every article,
245
+ * then finalize; the finalized bytes are content-addressed by their sha256.
246
+ *
247
+ * Value styles are a TS-side concern: the shared layer
248
+ * (`ValueStyleInterner`/`SnapshotValueStyle`) mints the `tqv-` classes and
249
+ * the first-paint rules, so the native table carries no value-style rows.
250
+ */
251
+ export interface SnapshotTables {
252
+ readonly kind: "snapshot-tables";
253
+ readonly handle: string;
254
+ /** The build's value-style rows in first-seen order; TS-side only. */
255
+ readonly valueStyles: ValueStyleInterner;
256
+ }
257
+ /** The finalized table file a host serves verbatim under its sha address. */
258
+ export interface FinalizedSnapshotTables {
259
+ readonly bytes: Buffer;
260
+ readonly sha256: string;
261
+ }
262
+ /**
263
+ * The data phase of one bundle (ADR 0052 schema 2): rendered bodies plus the
264
+ * table indexes the classes used. Hold this until every article of the build
265
+ * rendered and the table froze, then assemble.
266
+ */
267
+ export interface SnapshotBundleData {
268
+ readonly kind: "snapshot-bundle-data";
269
+ /** The wire form the native assembly reads. */
270
+ readonly json: string;
271
+ /** The template id the first-paint rules scope to. */
272
+ readonly id: string;
273
+ /** Value-style rows this bundle's classes used, in first-mint order. */
274
+ readonly usedValueStyleIndexes: readonly number[];
275
+ }
276
+ /** Creates the empty, unfrozen table set of one build. */
277
+ export declare function createSnapshotTables(): SnapshotTables;
278
+ /** Restores a previous build's frozen table so a rebuild extends the union. */
279
+ export declare function restoreSnapshotTables(bytes: Buffer): SnapshotTables;
280
+ /**
281
+ * Absorbs one batch of prepared entries into the table; returns the absorbed
282
+ * entry count. Absorb and data-phase calls share one mutable table and may
283
+ * interleave in any order; both throw once the table froze.
284
+ */
285
+ export declare function absorbSnapshotTables(tables: SnapshotTables, prepared: readonly PreparedEntry[]): number;
286
+ /**
287
+ * Absorbs table-scoped render metadata; value styles append to the TS-side
288
+ * interner in first-seen order, and re-absorbing an existing declaration
289
+ * keeps its index. The native table rows stay untouched, so the table hash
290
+ * does not change.
291
+ */
292
+ export declare function absorbSnapshotTablesMetadata(tables: SnapshotTables, metadata: {
293
+ readonly valueStyles: readonly string[];
294
+ }): void;
295
+ /**
296
+ * Freezes the rows and returns `{bytes, sha256}`; hosts serve the binary
297
+ * verbatim under the sha address. The handle stays usable for assembly.
298
+ */
299
+ export declare function finalizeSnapshotTables(tables: SnapshotTables): FinalizedSnapshotTables;
300
+ /** Drops the table set once every bundle assembled. */
301
+ export declare function closeSnapshotTables(tables: SnapshotTables): void;
302
+ /** The ts entry of one bundle data phase. */
303
+ interface BundleRenderOptions {
304
+ id: string;
305
+ paragraphSelector?: string;
306
+ fontContractParagraphs?: readonly PreparedEntry[];
307
+ snapshotTables: SnapshotTables;
308
+ }
309
+ /**
310
+ * The data phase for plain snapshot bundles: renders the bodies with the
311
+ * shared TS renderer and mints `tqv-` classes into the build's TS interner.
312
+ */
313
+ export declare function renderSnapshotBundleData(preparedParagraphs: readonly PreparedEntry[], options: BundleRenderOptions): SnapshotBundleData;
314
+ /** The data phase for font-contract bundles. */
315
+ export declare function renderFontContractBundleData(preparedParagraphs: readonly PreparedEntry[], options: BundleRenderOptions): SnapshotBundleData;
316
+ /**
317
+ * The assembly phase: compacts the manifest against the frozen table, builds
318
+ * the templates and the first-paint style. Requires finalizeSnapshotTables.
319
+ */
320
+ export declare function assembleSnapshotBundle(data: SnapshotBundleData, tables: SnapshotTables): SnapshotBundle;
321
+ /** The assembly phase for font-contract bundles. */
322
+ export declare function assembleFontContractBundle(data: SnapshotBundleData, tables: SnapshotTables): SnapshotBundle;
323
+ export {};