@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.
package/LICENSE ADDED
@@ -0,0 +1,373 @@
1
+ Mozilla Public License Version 2.0
2
+ ==================================
3
+
4
+ 1. Definitions
5
+ --------------
6
+
7
+ 1.1. "Contributor"
8
+ means each individual or legal entity that creates, contributes to
9
+ the creation of, or owns Covered Software.
10
+
11
+ 1.2. "Contributor Version"
12
+ means the combination of the Contributions of others (if any) used
13
+ by a Contributor and that particular Contributor's Contribution.
14
+
15
+ 1.3. "Contribution"
16
+ means Covered Software of a particular Contributor.
17
+
18
+ 1.4. "Covered Software"
19
+ means Source Code Form to which the initial Contributor has attached
20
+ the notice in Exhibit A, the Executable Form of such Source Code
21
+ Form, and Modifications of such Source Code Form, in each case
22
+ including portions thereof.
23
+
24
+ 1.5. "Incompatible With Secondary Licenses"
25
+ means
26
+
27
+ (a) that the initial Contributor has attached the notice described
28
+ in Exhibit B to the Covered Software; or
29
+
30
+ (b) that the Covered Software was made available under the terms of
31
+ version 1.1 or earlier of the License, but not also under the
32
+ terms of a Secondary License.
33
+
34
+ 1.6. "Executable Form"
35
+ means any form of the work other than Source Code Form.
36
+
37
+ 1.7. "Larger Work"
38
+ means a work that combines Covered Software with other material, in
39
+ a separate file or files, that is not Covered Software.
40
+
41
+ 1.8. "License"
42
+ means this document.
43
+
44
+ 1.9. "Licensable"
45
+ means having the right to grant, to the maximum extent possible,
46
+ whether at the time of the initial grant or subsequently, any and
47
+ all of the rights conveyed by this License.
48
+
49
+ 1.10. "Modifications"
50
+ means any of the following:
51
+
52
+ (a) any file in Source Code Form that results from an addition to,
53
+ deletion from, or modification of the contents of Covered
54
+ Software; or
55
+
56
+ (b) any new file in Source Code Form that contains any Covered
57
+ Software.
58
+
59
+ 1.11. "Patent Claims" of a Contributor
60
+ means any patent claim(s), including without limitation, method,
61
+ process, and apparatus claims, in any patent Licensable by such
62
+ Contributor that would be infringed, but for the grant of the
63
+ License, by the making, using, selling, offering for sale, having
64
+ made, import, or transfer of either its Contributions or its
65
+ Contributor Version.
66
+
67
+ 1.12. "Secondary License"
68
+ means either the GNU General Public License, Version 2.0, the GNU
69
+ Lesser General Public License, Version 2.1, the GNU Affero General
70
+ Public License, Version 3.0, or any later versions of those
71
+ licenses.
72
+
73
+ 1.13. "Source Code Form"
74
+ means the form of the work preferred for making modifications.
75
+
76
+ 1.14. "You" (or "Your")
77
+ means an individual or a legal entity exercising rights under this
78
+ License. For legal entities, "You" includes any entity that
79
+ controls, is controlled by, or is under common control with You. For
80
+ purposes of this definition, "control" means (a) the power, direct
81
+ or indirect, to cause the direction or management of such entity,
82
+ whether by contract or otherwise, or (b) ownership of more than
83
+ fifty percent (50%) of the outstanding shares or beneficial
84
+ ownership of such entity.
85
+
86
+ 2. License Grants and Conditions
87
+ --------------------------------
88
+
89
+ 2.1. Grants
90
+
91
+ Each Contributor hereby grants You a world-wide, royalty-free,
92
+ non-exclusive license:
93
+
94
+ (a) under intellectual property rights (other than patent or trademark)
95
+ Licensable by such Contributor to use, reproduce, make available,
96
+ modify, display, perform, distribute, and otherwise exploit its
97
+ Contributions, either on an unmodified basis, with Modifications, or
98
+ as part of a Larger Work; and
99
+
100
+ (b) under Patent Claims of such Contributor to make, use, sell, offer
101
+ for sale, have made, import, and otherwise transfer either its
102
+ Contributions or its Contributor Version.
103
+
104
+ 2.2. Effective Date
105
+
106
+ The licenses granted in Section 2.1 with respect to any Contribution
107
+ become effective for each Contribution on the date the Contributor first
108
+ distributes such Contribution.
109
+
110
+ 2.3. Limitations on Grant Scope
111
+
112
+ The licenses granted in this Section 2 are the only rights granted under
113
+ this License. No additional rights or licenses will be implied from the
114
+ distribution or licensing of Covered Software under this License.
115
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
116
+ Contributor:
117
+
118
+ (a) for any code that a Contributor has removed from Covered Software;
119
+ or
120
+
121
+ (b) for infringements caused by: (i) Your and any other third party's
122
+ modifications of Covered Software, or (ii) the combination of its
123
+ Contributions with other software (except as part of its Contributor
124
+ Version); or
125
+
126
+ (c) under Patent Claims infringed by Covered Software in the absence of
127
+ its Contributions.
128
+
129
+ This License does not grant any rights in the trademarks, service marks,
130
+ or logos of any Contributor (except as may be necessary to comply with
131
+ the notice requirements in Section 3.4).
132
+
133
+ 2.4. Subsequent Licenses
134
+
135
+ No Contributor makes additional grants as a result of Your choice to
136
+ distribute the Covered Software under a subsequent version of this
137
+ License (see Section 10.2) or under the terms of a Secondary License (if
138
+ permitted under the terms of Section 3.3).
139
+
140
+ 2.5. Representation
141
+
142
+ Each Contributor represents that the Contributor believes its
143
+ Contributions are its original creation(s) or it has sufficient rights
144
+ to grant the rights to its Contributions conveyed by this License.
145
+
146
+ 2.6. Fair Use
147
+
148
+ This License is not intended to limit any rights You have under
149
+ applicable copyright doctrines of fair use, fair dealing, or other
150
+ equivalents.
151
+
152
+ 2.7. Conditions
153
+
154
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
155
+ in Section 2.1.
156
+
157
+ 3. Responsibilities
158
+ -------------------
159
+
160
+ 3.1. Distribution of Source Form
161
+
162
+ All distribution of Covered Software in Source Code Form, including any
163
+ Modifications that You create or to which You contribute, must be under
164
+ the terms of this License. You must inform recipients that the Source
165
+ Code Form of the Covered Software is governed by the terms of this
166
+ License, and how they can obtain a copy of this License. You may not
167
+ attempt to alter or restrict the recipients' rights in the Source Code
168
+ Form.
169
+
170
+ 3.2. Distribution of Executable Form
171
+
172
+ If You distribute Covered Software in Executable Form then:
173
+
174
+ (a) such Covered Software must also be made available in Source Code
175
+ Form, as described in Section 3.1, and You must inform recipients of
176
+ the Executable Form how they can obtain a copy of such Source Code
177
+ Form by reasonable means in a timely manner, at a charge no more
178
+ than the cost of distribution to the recipient; and
179
+
180
+ (b) You may distribute such Executable Form under the terms of this
181
+ License, or sublicense it under different terms, provided that the
182
+ license for the Executable Form does not attempt to limit or alter
183
+ the recipients' rights in the Source Code Form under this License.
184
+
185
+ 3.3. Distribution of a Larger Work
186
+
187
+ You may create and distribute a Larger Work under terms of Your choice,
188
+ provided that You also comply with the requirements of this License for
189
+ the Covered Software. If the Larger Work is a combination of Covered
190
+ Software with a work governed by one or more Secondary Licenses, and the
191
+ Covered Software is not Incompatible With Secondary Licenses, this
192
+ License permits You to additionally distribute such Covered Software
193
+ under the terms of such Secondary License(s), so that the recipient of
194
+ the Larger Work may, at their option, further distribute the Covered
195
+ Software under the terms of either this License or such Secondary
196
+ License(s).
197
+
198
+ 3.4. Notices
199
+
200
+ You may not remove or alter the substance of any license notices
201
+ (including copyright notices, patent notices, disclaimers of warranty,
202
+ or limitations of liability) contained within the Source Code Form of
203
+ the Covered Software, except that You may alter any license notices to
204
+ the extent required to remedy known factual inaccuracies.
205
+
206
+ 3.5. Application of Additional Terms
207
+
208
+ You may choose to offer, and to charge a fee for, warranty, support,
209
+ indemnity or liability obligations to one or more recipients of Covered
210
+ Software. However, You may do so only on Your own behalf, and not on
211
+ behalf of any Contributor. You must make it absolutely clear that any
212
+ such warranty, support, indemnity, or liability obligation is offered by
213
+ You alone, and You hereby agree to indemnify every Contributor for any
214
+ liability incurred by such Contributor as a result of warranty, support,
215
+ indemnity or liability terms You offer. You may include additional
216
+ disclaimers of warranty and limitations of liability specific to any
217
+ jurisdiction.
218
+
219
+ 4. Inability to Comply Due to Statute or Regulation
220
+ ---------------------------------------------------
221
+
222
+ If it is impossible for You to comply with any of the terms of this
223
+ License with respect to some or all of the Covered Software due to
224
+ statute, judicial order, or regulation then You must: (a) comply with
225
+ the terms of this License to the maximum extent possible; and (b)
226
+ describe the limitations and the code they affect. Such description must
227
+ be placed in a text file included with all distributions of the Covered
228
+ Software under this License. Except to the extent prohibited by statute
229
+ or regulation, such description must be sufficiently detailed for a
230
+ recipient of ordinary skill to be able to understand it.
231
+
232
+ 5. Termination
233
+ --------------
234
+
235
+ 5.1. The rights granted under this License will terminate automatically
236
+ if You fail to comply with any of its terms. However, if You become
237
+ compliant, then the rights granted under this License from a particular
238
+ Contributor are reinstated (a) provisionally, unless and until such
239
+ Contributor explicitly and finally terminates Your grants, and (b) on an
240
+ ongoing basis, if such Contributor fails to notify You of the
241
+ non-compliance by some reasonable means prior to 60 days after You have
242
+ come back into compliance. Moreover, Your grants from a particular
243
+ Contributor are reinstated on an ongoing basis if such Contributor
244
+ notifies You of the non-compliance by some reasonable means, this is the
245
+ first time You have received notice of non-compliance with this License
246
+ from such Contributor, and You become compliant prior to 30 days after
247
+ Your receipt of the notice.
248
+
249
+ 5.2. If You initiate litigation against any entity by asserting a patent
250
+ infringement claim (excluding declaratory judgment actions,
251
+ counter-claims, and cross-claims) alleging that a Contributor Version
252
+ directly or indirectly infringes any patent, then the rights granted to
253
+ You by any and all Contributors for the Covered Software under Section
254
+ 2.1 of this License shall terminate.
255
+
256
+ 5.3. In the event of termination under Sections 5.1 or 5.2 above, all
257
+ end user license agreements (excluding distributors and resellers) which
258
+ have been validly granted by You or Your distributors under this License
259
+ prior to termination shall survive termination.
260
+
261
+ ************************************************************************
262
+ * *
263
+ * 6. Disclaimer of Warranty *
264
+ * ------------------------- *
265
+ * *
266
+ * Covered Software is provided under this License on an "as is" *
267
+ * basis, without warranty of any kind, either expressed, implied, or *
268
+ * statutory, including, without limitation, warranties that the *
269
+ * Covered Software is free of defects, merchantable, fit for a *
270
+ * particular purpose or non-infringing. The entire risk as to the *
271
+ * quality and performance of the Covered Software is with You. *
272
+ * Should any Covered Software prove defective in any respect, You *
273
+ * (not any Contributor) assume the cost of any necessary servicing, *
274
+ * repair, or correction. This disclaimer of warranty constitutes an *
275
+ * essential part of this License. No use of any Covered Software is *
276
+ * authorized under this License except under this disclaimer. *
277
+ * *
278
+ ************************************************************************
279
+
280
+ ************************************************************************
281
+ * *
282
+ * 7. Limitation of Liability *
283
+ * -------------------------- *
284
+ * *
285
+ * Under no circumstances and under no legal theory, whether tort *
286
+ * (including negligence), contract, or otherwise, shall any *
287
+ * Contributor, or anyone who distributes Covered Software as *
288
+ * permitted above, be liable to You for any direct, indirect, *
289
+ * special, incidental, or consequential damages of any character *
290
+ * including, without limitation, damages for lost profits, loss of *
291
+ * goodwill, work stoppage, computer failure or malfunction, or any *
292
+ * and all other commercial damages or losses, even if such party *
293
+ * shall have been informed of the possibility of such damages. This *
294
+ * limitation of liability shall not apply to liability for death or *
295
+ * personal injury resulting from such party's negligence to the *
296
+ * extent applicable law prohibits such limitation. Some *
297
+ * jurisdictions do not allow the exclusion or limitation of *
298
+ * incidental or consequential damages, so this exclusion and *
299
+ * limitation may not apply to You. *
300
+ * *
301
+ ************************************************************************
302
+
303
+ 8. Litigation
304
+ -------------
305
+
306
+ Any litigation relating to this License may be brought only in the
307
+ courts of a jurisdiction where the defendant maintains its principal
308
+ place of business and such litigation shall be governed by laws of that
309
+ jurisdiction, without reference to its conflict-of-law provisions.
310
+ Nothing in this Section shall prevent a party's ability to bring
311
+ cross-claims or counter-claims.
312
+
313
+ 9. Miscellaneous
314
+ ----------------
315
+
316
+ This License represents the complete agreement concerning the subject
317
+ matter hereof. If any provision of this License is held to be
318
+ unenforceable, such provision shall be reformed only to the extent
319
+ necessary to make it enforceable. Any law or regulation which provides
320
+ that the language of a contract shall be construed against the drafter
321
+ shall not be used to construe this License against a Contributor.
322
+
323
+ 10. Versions of the License
324
+ ---------------------------
325
+
326
+ 10.1. New Versions
327
+
328
+ Mozilla Foundation is the license steward. Except as provided in Section
329
+ 10.3, no one other than the license steward has the right to modify or
330
+ publish new versions of this License. Each version will be given a
331
+ distinguishing version number.
332
+
333
+ 10.2. Effect of New Versions
334
+
335
+ You may distribute the Covered Software under the terms of the version
336
+ of the License under which You originally received the Covered Software,
337
+ or under the terms of any subsequent version published by the license
338
+ steward.
339
+
340
+ 10.3. Modified Versions
341
+
342
+ If you create software not governed by this License, and you want to
343
+ create a new license for such software, you may create and use a
344
+ modified version of this License if you rename the license and remove
345
+ any references to the name of the license steward (except to note that
346
+ such modified license differs from this License).
347
+
348
+ 10.4. Distributing Source Code Form that is Incompatible With Secondary
349
+ Licenses
350
+
351
+ If You choose to distribute Source Code Form that is Incompatible With
352
+ Secondary Licenses under the terms of this version of the License, the
353
+ notice described in Exhibit B of this License must be attached.
354
+
355
+ Exhibit A - Source Code Form License Notice
356
+ -------------------------------------------
357
+
358
+ This Source Code Form is subject to the terms of the Mozilla Public
359
+ License, v. 2.0. If a copy of the MPL was not distributed with this
360
+ file, You can obtain one at http://mozilla.org/MPL/2.0/.
361
+
362
+ If it is not possible or desirable to put the notice in a particular
363
+ file, then You may include the notice in a location (such as a LICENSE
364
+ file in a relevant directory) where a recipient would be likely to look
365
+ for such a notice.
366
+
367
+ You may add additional accurate notices of copyright ownership.
368
+
369
+ Exhibit B - "Incompatible With Secondary Licenses" Notice
370
+ ---------------------------------------------------------
371
+
372
+ This Source Code Form is "Incompatible With Secondary Licenses", as
373
+ defined by the Mozilla Public License, v. 2.0.
package/README.md CHANGED
@@ -1,3 +1,211 @@
1
- # Temporary Holding Version
1
+ # @tiqian/precompute
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Native font session and precompute entry points for
4
+ [Tiqian](https://github.com/tiqian-cjk/tiqian), the CJK paragraph layout
5
+ engine. The layout rules live in the Kotlin core; this package runs the font
6
+ session (decoding, shaping, coverage, metrics) in a Rust addon built with
7
+ [Neon](https://neon-rs.dev).
8
+
9
+ Status: the font session API (`createFontSession`) is implemented against the
10
+ same byte-level contract as the Kotlin/JS implementation, which remains the
11
+ parity oracle. The precompute entry points (`createPrecomputer`,
12
+ `createHtmlPreparer`, bundle rendering) land slice by slice; see
13
+ `docs/adr/0050-native-precompute-rust-bindings.md` and `docs/roadmap.md` in
14
+ the repository.
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ npm install @tiqian/precompute
20
+ ```
21
+
22
+ Platform binaries arrive as optional dependencies for `linux-x64-gnu`,
23
+ `linux-arm64-gnu`, `darwin-arm64`, and `win32-x64-msvc`. Loading on any other
24
+ platform reports `UnsupportedPrecomputePlatform:<platform>`.
25
+
26
+ ### NixOS
27
+
28
+ The linux binaries carry no runpath: every `DT_NEEDED` entry resolves through
29
+ the running process (the runtime's loaded SONAMEs, the ldconfig cache, the
30
+ default directories). NixOS has no default library directories, so on a load
31
+ failure the loader diagnoses the addon's `DT_NEEDED` list against the loaded
32
+ images, `ldconfig -p`, the mapped nix store directories, and the profile
33
+ library directories. When every missing library is found, a copy of the
34
+ addon with the repaired runpath is written once to
35
+ `~/.cache/tiqian-precompute/nix-rpath` (requires `patchelf`) and loaded;
36
+ later loads reuse that copy without re-diagnosing. When a library is found
37
+ nowhere, the error names it and the searched directories. Libraries under
38
+ store prefixes the profiles do not cover can be added through
39
+ `TIQIAN_PRECOMPUTE_NIX_LIB_DIRS` (colon-separated directories, searched
40
+ first). Setting `LD_LIBRARY_PATH` from JavaScript does not work: glibc
41
+ parses it once at process startup.
42
+
43
+ ## SSR bundling
44
+
45
+ The native addon resolves relative to this package's own files, so a server
46
+ build that bundles dependencies must keep every entry point external. The
47
+ `vite` entry derives that list from the installed manifest at run time, so it
48
+ carries the installed scope and every exports key without a host-side copy:
49
+
50
+ ```js
51
+ // vite.config.js
52
+ import { tiqianSsrExternals } from "@tiqian/precompute/vite";
53
+
54
+ export default defineConfig(async () => ({
55
+ ssr: { external: await tiqianSsrExternals() },
56
+ }));
57
+ ```
58
+
59
+ ## Font session
60
+
61
+ ```js
62
+ import { createFontSession } from "@tiqian/precompute";
63
+
64
+ const session = await createFontSession(
65
+ [
66
+ {
67
+ family: "Han Sans",
68
+ publicUrl: "/fonts/han-sans.woff2",
69
+ source: await readFile("./han-sans.woff2"),
70
+ },
71
+ ],
72
+ { sessionPrefix: "site" },
73
+ );
74
+
75
+ session.faces;
76
+ session.shape("提椠排版", ["Han Sans"], 20, 400, false, "zh-CN", "body");
77
+ session.metrics(["Han Sans"], 20, 400, false);
78
+ session.renderFamilies(["Han Sans"]);
79
+ session.sourceBoundaries(text, baseStyle, textSpans);
80
+ session.beginCapture();
81
+ session.captureEvidence();
82
+ session.close();
83
+ ```
84
+
85
+ ## Worker threads
86
+
87
+ The batch entries (`prepareParagraphs`, `prepareFontContracts`, `prepareHtml`)
88
+ spread their items over worker threads. `TIQIAN_PRECOMPUTE_THREADS` sets the
89
+ worker count:
90
+
91
+ - unset or malformed: the machine's available parallelism
92
+ - `1`: the plain sequential loop
93
+ - `n > 1`: at most `n` scoped threads; batches smaller than two items always
94
+ run inline
95
+
96
+ Every value produces identical output. Results land in input order, the
97
+ reported error is the one of the lowest failing index, and a worker panic
98
+ leaves the batch instead of vanishing. Paragraph-level evidence capture and
99
+ the metric cache are shared across workers; each paragraph owns its capture
100
+ window.
101
+
102
+ ```js
103
+ import { createPrecomputer } from "@tiqian/precompute/precompute";
104
+
105
+ const precomputer = await createPrecomputer({ typography, fonts });
106
+ const entries = await precomputer.prepareParagraphs(paragraphs);
107
+ const contracts = await precomputer.prepareFontContracts(contractInputs);
108
+ ```
109
+
110
+ `prepareHtml` spreads inside one call: the document walk, the projection, and
111
+ the output reassembly stay sequential in document order, while each element's
112
+ snapshot attempt and contract fallback run over the workers with the same
113
+ guarantees as the explicit batch entries.
114
+
115
+ Singular entries (`prepareParagraph`, `prepareFontContract`) stay sequential;
116
+ font contract retries are rare and their evidence windows belong to one
117
+ paragraph each.
118
+
119
+ ## Host table transport
120
+
121
+ `@tiqian/precompute/transport` owns the delivery side of ADR 0052's snapshot
122
+ tables: serving frozen table bytes under one URL per sha, and the two bundle
123
+ orderings a build must not get wrong.
124
+
125
+ ```js
126
+ import { createSnapshotTableFileTransport } from "@tiqian/precompute/transport";
127
+
128
+ const tables = createSnapshotTableFileTransport({
129
+ directory: ".cache/tiqian/tables", // created on first write
130
+ urlPrefix: "tiqian-tables", // served as /tiqian-tables/<sha>.tiqtbl
131
+ });
132
+
133
+ const url = tables.write(finalized); // "/tiqian-tables/<sha256>.tiqtbl"
134
+ tables.read(sha256); // the bytes, or undefined
135
+ tables.listShas(); // every sha on disk
136
+ tables.sweep(referencedShas); // deletes unreferenced files, returns the count
137
+ ```
138
+
139
+ `createSnapshotTableSession()` drives one build's shared table: `absorb` and
140
+ `renderData` calls interleave article by article, `finish()` freezes the union
141
+ once, and every bundle assembles against the same frozen rows. Absorb and
142
+ data-phase calls share one mutable table; both throw once the table froze.
143
+ `renderStandaloneSnapshotBundle(plan, id)` is the per-item fallback: the item
144
+ absorbs into and freezes its own table beside the session's.
145
+
146
+ ## Cache persistence and contexts
147
+
148
+ `createSqliteCacheStore` (subpath `sqlite-store`) keeps computed snapshots in
149
+ one SQLite file, and `createPersistentCache` (subpath `persistence`) binds a
150
+ precomputer to such a store.
151
+
152
+ A precomputer's cache identity is its **context fingerprint**: a hash the
153
+ engine computes over everything that changes snapshot bytes. That covers the
154
+ engine and shaping revisions, the font files, and the full typography config,
155
+ including `fontSizePx` and `lineHeightPx`. The engine does not read
156
+ stylesheets: the numbers in `typography` are the CSS values snapshots are
157
+ computed under, transcribed by the host. Hosts never read or invent the
158
+ fingerprint; `precomputer.cache.context()` returns it for passing along.
159
+
160
+ The split principle: **one precomputer = one typography config = one
161
+ context**. Instantiate one precomputer per distinct config the site's CSS
162
+ uses (body text, list items, footnotes). Page kinds share a precomputer
163
+ whenever their config is identical, and per-paragraph inputs (text,
164
+ `maxWidthPx`) never split contexts.
165
+
166
+ ```js
167
+ const store = await createSqliteCacheStore(".cache/tiqian/cache.db", {
168
+ contexts: [precomputer.cache.context()], // one entry per precomputer
169
+ });
170
+ ```
171
+
172
+ ## Local development
173
+
174
+ This package is a member of the repository-root npm workspace. `npm install`
175
+ from this directory installs the whole workspace at the root; `@tiqian/*`
176
+ dependencies resolve to workspace symlinks when the declared version matches
177
+ the member's version, and silently fall back to the registry on mismatch, so
178
+ a member version bump must update its dependents in the same change.
179
+
180
+ From this directory:
181
+
182
+ ```sh
183
+ npm install
184
+ npm run debug:native # cargo build + neon dist into platforms/<current>/
185
+ npm run lint # bans `any` and `as unknown`; no inline disable
186
+ npm run build # tsc emit into lib/
187
+ npm run typecheck # src + test against the built lib/, no emit
188
+ npm test # node --test over test/, against the built lib/
189
+ ```
190
+
191
+ `npm run build:native` produces the release build. The sources are TypeScript
192
+ (`src/`); the published package ships the compiled `lib/`, and the tests run
193
+ against that output. The CI lane (`build-neon-precompute.yml`) builds every
194
+ supported platform and uploads the platform packages as artifacts; publishing
195
+ is a separate workflow.
196
+
197
+ Releases go to npmjs.org from annotated `@tiqian/precompute@<version>` tags
198
+ (`publish-precompute.yml`). Snapshot publication is manual-only
199
+ (`snapshot-precompute.yml`): each dispatch stamps its own
200
+ `npm-snapshot-<UTC timestamp>` tag, temporarily swaps the eleven
201
+ manifests (precompute and its platform binaries, the astro and sveltekit
202
+ integrations, and the ffi, core, prose, and react client packages) to the
203
+ running repository owner's scope (GitHub Packages requires the npm scope to
204
+ equal the owner), publishes `<base>-snapshot.<timestamp>` versions with the
205
+ `snapshot` dist-tag to GitHub Packages, and restores the
206
+ manifests. Snapshot publishing belongs to the fork; the stamp job refuses to
207
+ run under the canonical owner, so test packages never land under `@tiqian`
208
+ scopes. The addon loader resolves the platform packages under whatever
209
+ scope its own manifest carries, so the swapped packages load without a source
210
+ patch. Consumers install by exact version with
211
+ `--registry=https://npm.pkg.github.com` and a token carrying `read:packages`.
package/lib/cache.d.ts ADDED
@@ -0,0 +1,58 @@
1
+ import { type CanonicalKind, type CanonicalSubmissionInput } from "./canonical.js";
2
+ /** One cache layer; snapshot paragraphs and font contracts live apart. */
3
+ export type CacheTier = "snapshot" | "fontContract";
4
+ /** The record shape of the drain and prefetch protocol. */
5
+ export interface CacheRecord {
6
+ readonly tier: CacheTier;
7
+ readonly key: Uint8Array;
8
+ readonly contentHash: Uint8Array;
9
+ readonly artifact: Uint8Array;
10
+ readonly artifactSha: Uint8Array;
11
+ }
12
+ /** One content-carrying resend item: the canonical bytes, their hash and the
13
+ * caller's logical key. */
14
+ export interface SubmissionItem {
15
+ readonly hash: Uint8Array;
16
+ readonly logicalKey: string;
17
+ readonly canonical: Uint8Array;
18
+ }
19
+ /** One submission outcome per item. */
20
+ export type SubmissionOutcome = {
21
+ readonly status: "computed";
22
+ readonly artifact: Uint8Array;
23
+ } | {
24
+ readonly status: "hit";
25
+ readonly artifactSha: Uint8Array;
26
+ } | {
27
+ readonly status: "needContent";
28
+ };
29
+ /** Builds one submission item from a wire input; the canonical bytes and
30
+ * their hash are derived here, the caller never touches them. */
31
+ export declare function submissionItem(input: CanonicalSubmissionInput, kind: CanonicalKind): SubmissionItem;
32
+ /** Serializes records for a host store; each blob holds its own header. */
33
+ export declare function packRecords(records: readonly CacheRecord[]): Buffer;
34
+ /** Reads records back from one packed blob. */
35
+ export declare function unpackRecords(buffer: Uint8Array): CacheRecord[];
36
+ /** The bridge of one precomputer handle. The wrapper hangs this off the
37
+ * precomputer object; hosts drive it through the SDK helpers. */
38
+ export interface CacheBridge {
39
+ /** The context fingerprint as hex; namespaces a persistent store. */
40
+ context(): string;
41
+ /** The hash-only lane: hits report the artifact digest, misses report
42
+ * need-content. Content never crosses. */
43
+ submitHashes(hashes: readonly Uint8Array[]): SubmissionOutcome[];
44
+ /** The waiting egress: parks until every item resolved. Hits and fresh
45
+ * computations both return the artifact bytes. */
46
+ submitContents(items: readonly SubmissionItem[]): SubmissionOutcome[];
47
+ /** The background egress: returns once everything queued. Failures surface
48
+ * when the same content arrives through the waiting lane. */
49
+ prefillContents(items: readonly SubmissionItem[]): number;
50
+ /** Warms the memory tier with records read back from a persistent store. */
51
+ prefetch(records: readonly CacheRecord[]): number;
52
+ /** Takes the buffered writes for the host to persist, in write order. */
53
+ drainWrites(): CacheRecord[];
54
+ /** Drops memory-tier records whose store key is not listed. */
55
+ evictExcept(keys: readonly Uint8Array[]): void;
56
+ }
57
+ /** Internal: the bridge bound to one native registry handle. */
58
+ export declare function createCacheBridge(handle: string): CacheBridge;