@typfolio/workers 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,53 @@
1
- # Temporary Holding Version
1
+ # @typfolio/workers
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
+ Framework-independent module-worker execution for `@typfolio/core`. The package provides a lazy bounded pool, FIFO scheduling, a finite queue, per-job `AbortSignal` cancellation, timeouts, worker replacement, incremental batches, and deterministic disposal.
4
+
5
+ ```ts
6
+ import { createWorkerClient } from '@typfolio/workers';
7
+ import wasmUrl from '@typfolio/wasm/compiler.wasm?url';
8
+
9
+ const client = createWorkerClient({
10
+ compiler: { wasm: wasmUrl, fonts: ['/fonts/report.otf'] },
11
+ workerCount: 2,
12
+ queueLimit: 16,
13
+ timeoutMs: 30_000,
14
+ });
15
+
16
+ try {
17
+ const result = await client.compile(request, { signal });
18
+ // result.bytes is transferred from the worker without copying it again.
19
+ } finally {
20
+ await client.dispose();
21
+ }
22
+ ```
23
+
24
+ Stream a large batch in completion order without retaining every PDF:
25
+
26
+ ```ts
27
+ import { compileBatch } from '@typfolio/workers';
28
+
29
+ for await (const outcome of compileBatch(client, jobs, { signal })) {
30
+ if (outcome.status === 'success') {
31
+ await upload(outcome.id, outcome.result.bytes);
32
+ }
33
+ }
34
+ ```
35
+
36
+ Use `collectBatch(client, jobs)` when the caller needs all outcomes in input order.
37
+
38
+ The built-in factory creates a module worker from the packaged runtime. `workerFactory` is available for tests or hosts with custom worker construction. The client owns every worker returned by that factory and terminates it during hard cancellation, transport recovery, or disposal.
39
+
40
+ ## Semantics
41
+
42
+ - Calls are snapshotted synchronously and compiled FIFO, with one active compile per worker.
43
+ - Cancelling a waiting job removes only that job. Cancelling or timing out the active synchronous WASM call terminates its worker; the next queued job receives a fresh worker/compiler.
44
+ - A Typst compilation error rejects that job but keeps the worker healthy. A malformed message or worker crash rejects the active job and replaces the worker lazily.
45
+ - `queueLimit` counts waiting jobs, not the active compile. Timeouts include queue time.
46
+ - `dispose()` is idempotent, rejects all unsettled work with `DISPOSED`, and terminates the owned worker.
47
+ - Errors crossing the realm boundary become `TypfolioWorkerError` with stable `code`, `message`, and `diagnostics` fields.
48
+
49
+ `fonts` takes `Uint8Array | string | URL`, as in `@typfolio/core`, and `createWorkerClient` stays synchronous. Give fonts as URLs and each worker fetches them itself while it initializes, so the font bytes never cross the worker boundary (bytes are structured-cloned into every worker). A `URL` is sent as its `href`; a string is resolved against the page URL on the client thread before it is sent, because inside a worker a relative string would resolve against the worker script. Without a page URL (for example in Node) a string must be absolute, otherwise `createWorkerClient` throws a `TypeError`. A font that cannot be fetched in the worker fails initialization: the job rejects with a `TypfolioWorkerError` whose `code` is `INITIALIZATION` and whose message names the URL.
50
+
51
+ Worker transport accepts a WASM URL string, `ArrayBuffer`, `Uint8Array`, or compiled `WebAssembly.Module`. `Request` and `Response` are intentionally excluded because they are not consistently structured-cloneable across browsers. Asset bytes are copied once, on the client thread, when `compile` snapshots the request, so the caller's buffers stay intact and reusable. That private copy is then transferred to the worker (not cloned again), and the worker mounts it as received without copying it a third time. A `SharedArrayBuffer`-backed asset cannot be transferred and still travels by structured clone. `compileBatch` snapshots each job once and passes that snapshot straight to the client.
52
+
53
+ The package uses Effect internally for interruptible jobs, timeout/abort races, scoped client disposal, and bounded completion-order batch streams. The public contract deliberately remains framework-neutral: consumers use Promises, `AbortSignal`, async iterables, and `TypfolioWorkerError`, without needing Effect in application code. The worker wire protocol and explicit `Worker.terminate()` slot recovery remain Typfolio-owned because hard cancellation must stop synchronous WASM.
@@ -0,0 +1,8 @@
1
+ import { type PdfBatchJob, type PdfBatchOptions, type PdfBatchOutcome, type PdfWorkerClient } from './types.js';
2
+ /**
3
+ * Compiles a batch with at most `client.workerCount` submitted jobs at once.
4
+ * Events are yielded in completion order and results are not retained here.
5
+ */
6
+ export declare function compileBatch<Id>(client: PdfWorkerClient, jobs: readonly PdfBatchJob<Id>[], options?: PdfBatchOptions<Id>): AsyncIterable<PdfBatchOutcome<Id>>;
7
+ /** Collects batch events into input order. Prefer `compileBatch` for large outputs. */
8
+ export declare function collectBatch<Id>(client: PdfWorkerClient, jobs: readonly PdfBatchJob<Id>[], options?: PdfBatchOptions<Id>): Promise<readonly PdfBatchOutcome<Id>[]>;
package/dist/batch.js ADDED
@@ -0,0 +1,94 @@
1
+ import * as Effect from 'effect/Effect';
2
+ import * as Stream from 'effect/Stream';
3
+ import { snapshotRequest } from './snapshot.js';
4
+ import { TypfolioWorkerError, } from './types.js';
5
+ function cancelled(job) {
6
+ return { id: job.id, index: job.index, status: 'cancelled' };
7
+ }
8
+ function normalizeError(error) {
9
+ return error instanceof TypfolioWorkerError
10
+ ? error
11
+ : new TypfolioWorkerError('WORKER', error instanceof Error ? error.message : String(error), [], { cause: error });
12
+ }
13
+ const run = Effect.fnUntraced(function* (client, job, batchSignal) {
14
+ if (batchSignal?.aborted)
15
+ return cancelled(job);
16
+ return yield* Effect.tryPromise({
17
+ try: effectSignal => {
18
+ const controller = new AbortController();
19
+ const abortFromEffect = () => controller.abort(effectSignal.reason);
20
+ const abortFromBatch = () => controller.abort(batchSignal?.reason);
21
+ effectSignal.addEventListener('abort', abortFromEffect, { once: true });
22
+ batchSignal?.addEventListener('abort', abortFromBatch, { once: true });
23
+ if (effectSignal.aborted)
24
+ abortFromEffect();
25
+ if (batchSignal?.aborted)
26
+ abortFromBatch();
27
+ return client.compile(job.request, {
28
+ signal: controller.signal,
29
+ timeoutMs: job.timeoutMs,
30
+ }).finally(() => {
31
+ effectSignal.removeEventListener('abort', abortFromEffect);
32
+ batchSignal?.removeEventListener('abort', abortFromBatch);
33
+ });
34
+ },
35
+ catch: normalizeError,
36
+ }).pipe(Effect.match({
37
+ onFailure: error => error.code === 'ABORTED'
38
+ ? cancelled(job)
39
+ : { id: job.id, index: job.index, status: 'error', error },
40
+ onSuccess: (result) => ({
41
+ id: job.id,
42
+ index: job.index,
43
+ status: 'success',
44
+ result,
45
+ }),
46
+ }));
47
+ });
48
+ function initialProgress(total) {
49
+ return { total, completed: 0, succeeded: 0, failed: 0, cancelled: 0 };
50
+ }
51
+ function advance(progress, outcome) {
52
+ return {
53
+ total: progress.total,
54
+ completed: progress.completed + 1,
55
+ succeeded: progress.succeeded + (outcome.status === 'success' ? 1 : 0),
56
+ failed: progress.failed + (outcome.status === 'error' ? 1 : 0),
57
+ cancelled: progress.cancelled + (outcome.status === 'cancelled' ? 1 : 0),
58
+ latestJobId: outcome.id,
59
+ };
60
+ }
61
+ /**
62
+ * Compiles a batch with at most `client.workerCount` submitted jobs at once.
63
+ * Events are yielded in completion order and results are not retained here.
64
+ */
65
+ export function compileBatch(client, jobs, options = {}) {
66
+ const captured = jobs.map((job, index) => ({
67
+ id: job.id,
68
+ index,
69
+ request: snapshotRequest(job.request),
70
+ timeoutMs: job.timeoutMs,
71
+ }));
72
+ return (async function* stream() {
73
+ let progress = initialProgress(captured.length);
74
+ options.onProgress?.(progress);
75
+ const outcomes = Stream.fromIterable(captured).pipe(Stream.mapEffect(job => run(client, job, options.signal), {
76
+ concurrency: client.workerCount,
77
+ unordered: true,
78
+ }), Stream.tap(outcome => Effect.sync(() => {
79
+ progress = advance(progress, outcome);
80
+ options.onProgress?.(progress);
81
+ options.onItemSettled?.(outcome, progress);
82
+ })));
83
+ for await (const outcome of Stream.toAsyncIterable(outcomes)) {
84
+ yield outcome;
85
+ }
86
+ })();
87
+ }
88
+ /** Collects batch events into input order. Prefer `compileBatch` for large outputs. */
89
+ export async function collectBatch(client, jobs, options = {}) {
90
+ const outcomes = new Array(jobs.length);
91
+ for await (const outcome of compileBatch(client, jobs, options))
92
+ outcomes[outcome.index] = outcome;
93
+ return outcomes;
94
+ }
@@ -0,0 +1,4 @@
1
+ import { type CreateWorkerClientOptions, type PdfWorkerClient } from './types.js';
2
+ export { TypfolioWorkerError, type CreateWorkerClientOptions, type PdfWorkerClient, type WorkerCompileOptions, type WorkerCompilerOptions, type WorkerErrorCode, type WorkerFontSource, type WorkerWasmSource, type PdfBatchJob, type PdfBatchOptions, type PdfBatchOutcome, type PdfBatchProgress, } from './types.js';
3
+ export { collectBatch, compileBatch } from './batch.js';
4
+ export declare function createWorkerClient(options: CreateWorkerClientOptions): PdfWorkerClient;
package/dist/index.js ADDED
@@ -0,0 +1,304 @@
1
+ import * as Effect from 'effect/Effect';
2
+ import * as Layer from 'effect/Layer';
3
+ import * as ManagedRuntime from 'effect/ManagedRuntime';
4
+ import { decodeRuntimeMessage, protocolVersion } from './protocol.js';
5
+ import { isSnapshot, snapshotRequest, transferableBuffers } from './snapshot.js';
6
+ import { TypfolioWorkerError, } from './types.js';
7
+ export { TypfolioWorkerError, } from './types.js';
8
+ export { collectBatch, compileBatch } from './batch.js';
9
+ const maximumTimer = 2_147_483_647;
10
+ function positiveInteger(value, fallback, name) {
11
+ const result = value ?? fallback;
12
+ if (!Number.isInteger(result) || result < 1)
13
+ throw new RangeError(`${name} must be a positive integer`);
14
+ return result;
15
+ }
16
+ function timeout(value, name) {
17
+ if (value === undefined)
18
+ return undefined;
19
+ if (!Number.isInteger(value) || value < 1 || value > maximumTimer) {
20
+ throw new RangeError(`${name} must be an integer from 1 through ${maximumTimer}`);
21
+ }
22
+ return value;
23
+ }
24
+ function snapshotWasm(value) {
25
+ if (typeof value === 'string' || value instanceof WebAssembly.Module)
26
+ return value;
27
+ if (value instanceof ArrayBuffer)
28
+ return value.slice(0);
29
+ if (value instanceof Uint8Array)
30
+ return new Uint8Array(value);
31
+ throw new TypeError('compiler.wasm must be a URL string, ArrayBuffer, Uint8Array, or WebAssembly.Module');
32
+ }
33
+ /** Bytes are copied; a URL becomes its `href`; a string is resolved here, because in a worker it would resolve against the worker script. */
34
+ function snapshotFont(font, index) {
35
+ const at = `compiler.fonts[${index}]`;
36
+ if (font instanceof Uint8Array) {
37
+ if (!font.length)
38
+ throw new TypeError(`${at} must not be empty`);
39
+ return new Uint8Array(font);
40
+ }
41
+ if (font instanceof URL)
42
+ return font.href;
43
+ if (typeof font !== 'string' || !font.trim())
44
+ throw new TypeError(`${at} must be a Uint8Array, a URL, or a non-empty URL string`);
45
+ const base = globalThis.location?.href;
46
+ try {
47
+ return (base === undefined ? new URL(font) : new URL(font, base)).href;
48
+ }
49
+ catch (cause) {
50
+ throw new TypeError(`${at} cannot be resolved to a URL${base === undefined ? ' without a page URL; use an absolute URL' : ''}: ${JSON.stringify(font)}`, { cause });
51
+ }
52
+ }
53
+ function snapshotCompiler(value) {
54
+ if (!value || !Array.isArray(value.fonts) || !value.fonts.length) {
55
+ throw new TypeError('compiler.fonts must contain at least one Uint8Array, URL, or URL string');
56
+ }
57
+ return { wasm: snapshotWasm(value.wasm), fonts: value.fonts.map(snapshotFont) };
58
+ }
59
+ function workerError(message, cause) {
60
+ return new TypfolioWorkerError('WORKER', message, [], cause === undefined ? undefined : { cause });
61
+ }
62
+ function defaultWorkerFactory(name) {
63
+ return index => new Worker(new URL('./runtime.js', import.meta.url), { type: 'module', name: `${name}-${index + 1}` });
64
+ }
65
+ export function createWorkerClient(options) {
66
+ const compiler = snapshotCompiler(options.compiler);
67
+ const workerCount = positiveInteger(options.workerCount, 1, 'workerCount');
68
+ const queueLimit = positiveInteger(options.queueLimit, 32, 'queueLimit');
69
+ const defaultTimeout = timeout(options.timeoutMs, 'timeoutMs');
70
+ const createWorker = options.workerFactory ?? defaultWorkerFactory(options.workerName ?? 'typfolio-pdf');
71
+ const queue = [];
72
+ const slots = new Array(workerCount);
73
+ let nextId = 1;
74
+ let poolDisposed = false;
75
+ let clientDisposed = false;
76
+ let disposal;
77
+ function settle(job, result) {
78
+ if (job.settled)
79
+ return;
80
+ job.settled = true;
81
+ job.resume(result);
82
+ }
83
+ function terminateWorker(current) {
84
+ if (!current)
85
+ return;
86
+ if (slots[current.index] === current)
87
+ slots[current.index] = undefined;
88
+ current.worker.terminate();
89
+ }
90
+ function dispatchSoon() {
91
+ queueMicrotask(dispatch);
92
+ }
93
+ function failActive(error, current) {
94
+ if (slots[current.index] !== current)
95
+ return;
96
+ const job = current.active;
97
+ current.active = undefined;
98
+ terminateWorker(current);
99
+ const failed = job ?? queue.shift();
100
+ if (failed)
101
+ settle(failed, Effect.fail(error));
102
+ dispatchSoon();
103
+ }
104
+ function handleMessage(current, value) {
105
+ if (poolDisposed || slots[current.index] !== current)
106
+ return;
107
+ let message;
108
+ try {
109
+ message = decodeRuntimeMessage(value);
110
+ }
111
+ catch (cause) {
112
+ failActive(workerError('Typfolio worker returned an invalid message', cause), current);
113
+ return;
114
+ }
115
+ if (message.type === 'ready') {
116
+ if (current.ready) {
117
+ failActive(workerError('Typfolio worker initialized more than once'), current);
118
+ return;
119
+ }
120
+ current.ready = true;
121
+ dispatch();
122
+ return;
123
+ }
124
+ if (message.type === 'failure' && message.id === undefined) {
125
+ const error = new TypfolioWorkerError(message.error.code, message.error.message, message.error.diagnostics);
126
+ failActive(error, current);
127
+ return;
128
+ }
129
+ const job = current.active;
130
+ if (!job || message.id !== job.id)
131
+ return;
132
+ current.active = undefined;
133
+ if (message.type === 'result') {
134
+ settle(job, Effect.succeed(message.result));
135
+ }
136
+ else {
137
+ settle(job, Effect.fail(new TypfolioWorkerError(message.error.code, message.error.message, message.error.diagnostics)));
138
+ }
139
+ dispatch();
140
+ }
141
+ function createSlot(index) {
142
+ let worker;
143
+ try {
144
+ worker = createWorker(index);
145
+ }
146
+ catch (cause) {
147
+ const job = queue.shift();
148
+ if (job)
149
+ settle(job, Effect.fail(workerError('Could not create Typfolio worker', cause)));
150
+ dispatchSoon();
151
+ return false;
152
+ }
153
+ const current = { worker, index, ready: false };
154
+ slots[index] = current;
155
+ worker.addEventListener('message', event => handleMessage(current, event.data));
156
+ worker.addEventListener('error', event => {
157
+ failActive(workerError(event.message || 'Typfolio worker failed'), current);
158
+ });
159
+ worker.addEventListener('messageerror', () => {
160
+ failActive(workerError('Typfolio worker returned an unreadable message'), current);
161
+ });
162
+ const message = { protocol: protocolVersion, type: 'initialize', compiler };
163
+ try {
164
+ worker.postMessage(message);
165
+ }
166
+ catch (cause) {
167
+ failActive(workerError('Could not initialize Typfolio worker', cause), current);
168
+ }
169
+ return true;
170
+ }
171
+ function ensureCapacity() {
172
+ if (poolDisposed || !queue.length)
173
+ return;
174
+ const activeCount = slots.reduce((count, current) => count + (current?.active ? 1 : 0), 0);
175
+ const target = Math.min(workerCount, activeCount + queue.length);
176
+ let existing = slots.reduce((count, current) => count + (current ? 1 : 0), 0);
177
+ for (let index = 0; index < slots.length && existing < target; index += 1) {
178
+ if (!slots[index]) {
179
+ if (!createSlot(index))
180
+ break;
181
+ existing += 1;
182
+ }
183
+ }
184
+ }
185
+ function dispatch() {
186
+ if (poolDisposed || !queue.length)
187
+ return;
188
+ ensureCapacity();
189
+ for (const current of slots) {
190
+ if (!current?.ready || current.active)
191
+ continue;
192
+ const job = queue.shift();
193
+ if (!job)
194
+ return;
195
+ current.active = job;
196
+ const message = { protocol: protocolVersion, type: 'compile', id: job.id, request: job.request };
197
+ try {
198
+ // A job is posted once: failed, cancelled, timed-out and crashed jobs are rejected, never re-posted, and a
199
+ // queued job leaves the queue as it is posted. So the snapshot's buffers can be transferred, not cloned.
200
+ current.worker.postMessage(message, transferableBuffers(job.request));
201
+ }
202
+ catch (cause) {
203
+ failActive(workerError('Could not send work to Typfolio worker', cause), current);
204
+ }
205
+ }
206
+ }
207
+ function interruptJob(job) {
208
+ if (job.settled)
209
+ return;
210
+ job.settled = true;
211
+ const current = slots.find(candidate => candidate?.active === job);
212
+ if (current) {
213
+ current.active = undefined;
214
+ terminateWorker(current);
215
+ dispatchSoon();
216
+ return;
217
+ }
218
+ const index = queue.indexOf(job);
219
+ if (index !== -1)
220
+ queue.splice(index, 1);
221
+ }
222
+ const compileJob = Effect.fnUntraced(function* (request) {
223
+ return yield* Effect.callback(resume => {
224
+ if (poolDisposed) {
225
+ resume(Effect.fail(new TypfolioWorkerError('DISPOSED', 'The worker client is disposed')));
226
+ return;
227
+ }
228
+ if (queue.length >= queueLimit) {
229
+ resume(Effect.fail(new TypfolioWorkerError('QUEUE_FULL', `The worker queue limit of ${queueLimit} was reached`)));
230
+ return;
231
+ }
232
+ const job = { id: nextId++, request, resume, settled: false };
233
+ queue.push(job);
234
+ dispatch();
235
+ return Effect.sync(() => interruptJob(job));
236
+ });
237
+ });
238
+ function waitForAbort(signal) {
239
+ return Effect.callback(resume => {
240
+ const abort = () => resume(Effect.fail(new TypfolioWorkerError('ABORTED', 'Compilation was cancelled', [], { cause: signal.reason })));
241
+ if (signal.aborted) {
242
+ abort();
243
+ return;
244
+ }
245
+ signal.addEventListener('abort', abort, { once: true });
246
+ return Effect.sync(() => signal.removeEventListener('abort', abort));
247
+ });
248
+ }
249
+ const disposePool = Effect.sync(() => {
250
+ if (poolDisposed)
251
+ return;
252
+ poolDisposed = true;
253
+ const error = new TypfolioWorkerError('DISPOSED', 'The worker client is disposed');
254
+ for (const current of slots) {
255
+ if (current?.active) {
256
+ const job = current.active;
257
+ current.active = undefined;
258
+ settle(job, Effect.fail(error));
259
+ }
260
+ }
261
+ for (const job of queue.splice(0))
262
+ settle(job, Effect.fail(error));
263
+ for (const current of slots)
264
+ terminateWorker(current);
265
+ });
266
+ const runtime = ManagedRuntime.make(Layer.effectDiscard(Effect.acquireRelease(Effect.void, () => disposePool)));
267
+ return {
268
+ workerCount,
269
+ compile(request, compileOptions = {}) {
270
+ if (clientDisposed)
271
+ return Promise.reject(new TypfolioWorkerError('DISPOSED', 'The worker client is disposed'));
272
+ if (compileOptions.signal?.aborted) {
273
+ return Promise.reject(new TypfolioWorkerError('ABORTED', 'Compilation was cancelled', [], { cause: compileOptions.signal.reason }));
274
+ }
275
+ let captured;
276
+ let duration;
277
+ try {
278
+ // A snapshot (from compileBatch) is already client-owned; copying it again would copy every asset twice.
279
+ captured = isSnapshot(request) ? request : snapshotRequest(request);
280
+ duration = timeout(compileOptions.timeoutMs, 'compile timeoutMs') ?? defaultTimeout;
281
+ }
282
+ catch (error) {
283
+ return Promise.reject(error);
284
+ }
285
+ let program = compileJob(captured);
286
+ if (duration !== undefined) {
287
+ program = Effect.timeoutOrElse(program, {
288
+ duration,
289
+ orElse: () => Effect.fail(new TypfolioWorkerError('TIMEOUT', `Compilation exceeded its ${duration} ms timeout`)),
290
+ });
291
+ }
292
+ if (compileOptions.signal) {
293
+ program = Effect.raceFirst(program, waitForAbort(compileOptions.signal));
294
+ }
295
+ return runtime.runPromise(program);
296
+ },
297
+ dispose() {
298
+ if (disposal)
299
+ return disposal;
300
+ clientDisposed = true;
301
+ return disposal = Effect.runPromise(disposePool).then(() => runtime.dispose());
302
+ },
303
+ };
304
+ }
@@ -0,0 +1,34 @@
1
+ import type { Diagnostic, PdfRequest, PdfResult } from '@typfolio/core';
2
+ import type { SerializedCompilerOptions, WorkerErrorCode } from './types.js';
3
+ export declare const protocolVersion = 1;
4
+ export type HostMessage = {
5
+ readonly protocol: 1;
6
+ readonly type: 'initialize';
7
+ readonly compiler: SerializedCompilerOptions;
8
+ } | {
9
+ readonly protocol: 1;
10
+ readonly type: 'compile';
11
+ readonly id: number;
12
+ readonly request: PdfRequest<unknown>;
13
+ };
14
+ export interface SerializedError {
15
+ readonly code: WorkerErrorCode;
16
+ readonly message: string;
17
+ readonly diagnostics: readonly Diagnostic[];
18
+ }
19
+ export type RuntimeMessage = {
20
+ readonly protocol: 1;
21
+ readonly type: 'ready';
22
+ } | {
23
+ readonly protocol: 1;
24
+ readonly type: 'result';
25
+ readonly id: number;
26
+ readonly result: PdfResult;
27
+ } | {
28
+ readonly protocol: 1;
29
+ readonly type: 'failure';
30
+ readonly id?: number;
31
+ readonly error: SerializedError;
32
+ };
33
+ export declare function decodeHostMessage(value: unknown): HostMessage;
34
+ export declare function decodeRuntimeMessage(value: unknown): RuntimeMessage;
@@ -0,0 +1,101 @@
1
+ export const protocolVersion = 1;
2
+ function record(value, at) {
3
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
4
+ throw new TypeError(`${at} must be an object`);
5
+ }
6
+ return value;
7
+ }
8
+ function wasmSource(value) {
9
+ if (typeof value === 'string' || value instanceof ArrayBuffer || value instanceof Uint8Array || value instanceof WebAssembly.Module) {
10
+ return value;
11
+ }
12
+ throw new TypeError('compiler.wasm cannot cross the worker boundary');
13
+ }
14
+ function compilerOptions(value) {
15
+ const options = record(value, 'compiler');
16
+ if (!Array.isArray(options.fonts) || options.fonts.some(font => !(font instanceof Uint8Array || typeof font === 'string'))) {
17
+ throw new TypeError('compiler.fonts must contain Uint8Array or string values');
18
+ }
19
+ return {
20
+ wasm: wasmSource(options.wasm),
21
+ fonts: options.fonts.map((font) => typeof font === 'string' ? font : new Uint8Array(font)),
22
+ };
23
+ }
24
+ export function decodeHostMessage(value) {
25
+ const message = record(value, 'worker message');
26
+ if (message.protocol !== protocolVersion)
27
+ throw new TypeError('Unsupported Typfolio worker protocol');
28
+ if (message.type === 'initialize') {
29
+ return { protocol: protocolVersion, type: 'initialize', compiler: compilerOptions(message.compiler) };
30
+ }
31
+ if (message.type === 'compile' && Number.isSafeInteger(message.id)) {
32
+ const request = record(message.request, 'request');
33
+ return { protocol: protocolVersion, type: 'compile', id: Number(message.id), request };
34
+ }
35
+ throw new TypeError('Unknown Typfolio worker message');
36
+ }
37
+ function diagnostic(value) {
38
+ const item = record(value, 'diagnostic');
39
+ if (typeof item.severity !== 'string' || typeof item.message !== 'string')
40
+ throw new TypeError('Invalid worker diagnostic');
41
+ return {
42
+ severity: item.severity,
43
+ message: item.message,
44
+ path: typeof item.path === 'string' ? item.path : undefined,
45
+ range: typeof item.range === 'string' ? item.range : undefined,
46
+ package: typeof item.package === 'string' ? item.package : undefined,
47
+ };
48
+ }
49
+ function serializedError(value) {
50
+ const error = record(value, 'worker error');
51
+ if (typeof error.code !== 'string' || typeof error.message !== 'string' || !Array.isArray(error.diagnostics)) {
52
+ throw new TypeError('Invalid worker error');
53
+ }
54
+ const codes = [
55
+ 'INITIALIZATION', 'INVALID_REQUEST', 'UNSUPPORTED_OPTION', 'BUSY', 'DISPOSED',
56
+ 'ABORTED', 'COMPILATION', 'ENGINE', 'WORKER', 'TIMEOUT', 'QUEUE_FULL',
57
+ ];
58
+ const code = codes.find(candidate => candidate === error.code);
59
+ if (!code)
60
+ throw new TypeError('Invalid worker error code');
61
+ return {
62
+ code,
63
+ message: error.message,
64
+ diagnostics: error.diagnostics.map(diagnostic),
65
+ };
66
+ }
67
+ function result(value) {
68
+ const item = record(value, 'worker result');
69
+ const bytes = item.bytes instanceof Uint8Array
70
+ ? item.bytes
71
+ : item.bytes instanceof ArrayBuffer ? new Uint8Array(item.bytes) : undefined;
72
+ if (!bytes || !Array.isArray(item.diagnostics))
73
+ throw new TypeError('Invalid worker PDF result');
74
+ const metadata = record(item.metadata, 'worker result metadata');
75
+ if (metadata.title !== undefined && typeof metadata.title !== 'string')
76
+ throw new TypeError('Invalid worker PDF title');
77
+ return {
78
+ bytes,
79
+ diagnostics: item.diagnostics.map(diagnostic),
80
+ metadata: { title: metadata.title },
81
+ };
82
+ }
83
+ export function decodeRuntimeMessage(value) {
84
+ const message = record(value, 'runtime message');
85
+ if (message.protocol !== protocolVersion)
86
+ throw new TypeError('Unsupported Typfolio worker protocol');
87
+ if (message.type === 'ready')
88
+ return { protocol: protocolVersion, type: 'ready' };
89
+ if (message.type === 'result' && Number.isSafeInteger(message.id)) {
90
+ return { protocol: protocolVersion, type: 'result', id: Number(message.id), result: result(message.result) };
91
+ }
92
+ if (message.type === 'failure' && (message.id === undefined || Number.isSafeInteger(message.id))) {
93
+ return {
94
+ protocol: protocolVersion,
95
+ type: 'failure',
96
+ id: message.id === undefined ? undefined : Number(message.id),
97
+ error: serializedError(message.error),
98
+ };
99
+ }
100
+ throw new TypeError('Unknown Typfolio runtime message');
101
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import { installWorkerRuntime } from './worker-runtime.js';
2
+ installWorkerRuntime(self);
@@ -0,0 +1,10 @@
1
+ import type { PdfRequest } from '@typfolio/core';
2
+ export declare function isSnapshot(request: unknown): boolean;
3
+ export declare function snapshotRequest(request: PdfRequest<unknown>): PdfRequest<unknown>;
4
+ /**
5
+ * The buffers of a snapshot's assets that `postMessage` can transfer, each once. Buffers that cannot be
6
+ * transferred (a `SharedArrayBuffer`, which structured clone shares instead of copying, or one that is already
7
+ * detached) are left out and travel by the ordinary clone. Only call this with a snapshot: transferring detaches
8
+ * the buffers, which would break a caller's request.
9
+ */
10
+ export declare function transferableBuffers(snapshot: PdfRequest<unknown>): ArrayBuffer[];
@@ -0,0 +1,62 @@
1
+ import { TypfolioWorkerError } from './types.js';
2
+ function inspectCloneable(value, ancestors, at) {
3
+ if (typeof value === 'function' || typeof value === 'symbol') {
4
+ throw new TypeError(`${at} cannot cross the worker boundary`);
5
+ }
6
+ if (typeof value !== 'object' || value === null || value instanceof Uint8Array || value instanceof ArrayBuffer)
7
+ return;
8
+ if (ancestors.has(value))
9
+ throw new TypeError(`${at} contains a cycle`);
10
+ if (!Array.isArray(value) && ![Object.prototype, null].includes(Object.getPrototypeOf(value))) {
11
+ throw new TypeError(`${at} must contain only plain objects, arrays, and Uint8Array assets`);
12
+ }
13
+ if (Object.getOwnPropertySymbols(value).length)
14
+ throw new TypeError(`${at} contains symbol keys`);
15
+ ancestors.add(value);
16
+ try {
17
+ for (const key of Object.keys(value)) {
18
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
19
+ if (!descriptor || !('value' in descriptor))
20
+ throw new TypeError(`${at}.${key} contains an accessor`);
21
+ inspectCloneable(descriptor.value, ancestors, `${at}.${key}`);
22
+ }
23
+ }
24
+ finally {
25
+ ancestors.delete(value);
26
+ }
27
+ }
28
+ // Every request returned by snapshotRequest. The client owns these (nothing else holds their buffers), so it
29
+ // neither snapshots them again nor hesitates to transfer them.
30
+ const snapshots = new WeakSet();
31
+ export function isSnapshot(request) {
32
+ return typeof request === 'object' && request !== null && snapshots.has(request);
33
+ }
34
+ export function snapshotRequest(request) {
35
+ try {
36
+ inspectCloneable(request, new Set(), 'request');
37
+ const snapshot = structuredClone(request);
38
+ snapshots.add(snapshot);
39
+ return snapshot;
40
+ }
41
+ catch (cause) {
42
+ throw new TypfolioWorkerError('INVALID_REQUEST', 'The PDF request cannot cross the worker boundary', [], { cause });
43
+ }
44
+ }
45
+ /**
46
+ * The buffers of a snapshot's assets that `postMessage` can transfer, each once. Buffers that cannot be
47
+ * transferred (a `SharedArrayBuffer`, which structured clone shares instead of copying, or one that is already
48
+ * detached) are left out and travel by the ordinary clone. Only call this with a snapshot: transferring detaches
49
+ * the buffers, which would break a caller's request.
50
+ */
51
+ export function transferableBuffers(snapshot) {
52
+ const buffers = new Set();
53
+ for (const bytes of Object.values(snapshot.assets ?? {})) {
54
+ if (!ArrayBuffer.isView(bytes))
55
+ continue; // Not an asset; the worker's validation rejects it.
56
+ const buffer = bytes.buffer;
57
+ if (Object.prototype.toString.call(buffer) === '[object ArrayBuffer]' && !buffer.detached) {
58
+ buffers.add(buffer);
59
+ }
60
+ }
61
+ return [...buffers];
62
+ }
@@ -0,0 +1,81 @@
1
+ import type { Diagnostic, ErrorCode, PdfClient, PdfRequest, PdfResult } from '@typfolio/core';
2
+ /** WASM sources that the structured-clone worker protocol can carry reliably. */
3
+ export type WorkerWasmSource = string | ArrayBuffer | Uint8Array | WebAssembly.Module;
4
+ /**
5
+ * Font bytes, or a URL that each worker fetches itself, so the bytes never cross the worker boundary.
6
+ * A string is resolved against the page URL on the client thread before it is sent.
7
+ */
8
+ export type WorkerFontSource = Uint8Array | string | URL;
9
+ export interface WorkerCompilerOptions {
10
+ readonly wasm: WorkerWasmSource;
11
+ readonly fonts: readonly WorkerFontSource[];
12
+ }
13
+ /** What crosses the worker boundary: a `URL` has become its absolute `href`. */
14
+ export interface SerializedCompilerOptions {
15
+ readonly wasm: WorkerWasmSource;
16
+ readonly fonts: readonly (Uint8Array | string)[];
17
+ }
18
+ export interface WorkerCompileOptions {
19
+ readonly signal?: AbortSignal;
20
+ /** Includes time spent waiting in the queue. */
21
+ readonly timeoutMs?: number;
22
+ }
23
+ export interface PdfWorkerClient extends PdfClient {
24
+ readonly workerCount: number;
25
+ compile(request: PdfRequest<unknown>, options?: WorkerCompileOptions): Promise<PdfResult>;
26
+ /** Rejects queued/active jobs and terminates all owned workers. Idempotent. */
27
+ dispose(): Promise<void>;
28
+ }
29
+ export interface CreateWorkerClientOptions {
30
+ readonly compiler: WorkerCompilerOptions;
31
+ /** Maximum parallel compilations. Workers are created lazily. Defaults to one. */
32
+ readonly workerCount?: number;
33
+ /** Maximum number of waiting jobs, excluding the active compilation. */
34
+ readonly queueLimit?: number;
35
+ /** Default per-job timeout, including queue time. Omit for no timeout. */
36
+ readonly timeoutMs?: number;
37
+ /** Used by the built-in module-worker factory. */
38
+ readonly workerName?: string;
39
+ /** Test/custom-host escape hatch. The client owns and terminates each worker. */
40
+ readonly workerFactory?: (index: number) => Worker;
41
+ }
42
+ export interface PdfBatchJob<Id> {
43
+ readonly id: Id;
44
+ readonly request: PdfRequest<unknown>;
45
+ readonly timeoutMs?: number;
46
+ }
47
+ export type PdfBatchOutcome<Id> = {
48
+ readonly id: Id;
49
+ readonly index: number;
50
+ readonly status: 'success';
51
+ readonly result: PdfResult;
52
+ } | {
53
+ readonly id: Id;
54
+ readonly index: number;
55
+ readonly status: 'error';
56
+ readonly error: TypfolioWorkerError;
57
+ } | {
58
+ readonly id: Id;
59
+ readonly index: number;
60
+ readonly status: 'cancelled';
61
+ };
62
+ export interface PdfBatchProgress<Id> {
63
+ readonly total: number;
64
+ readonly completed: number;
65
+ readonly succeeded: number;
66
+ readonly failed: number;
67
+ readonly cancelled: number;
68
+ readonly latestJobId?: Id;
69
+ }
70
+ export interface PdfBatchOptions<Id> {
71
+ readonly signal?: AbortSignal;
72
+ readonly onItemSettled?: (outcome: PdfBatchOutcome<Id>, progress: PdfBatchProgress<Id>) => void;
73
+ readonly onProgress?: (progress: PdfBatchProgress<Id>) => void;
74
+ }
75
+ export type WorkerErrorCode = ErrorCode | 'WORKER' | 'TIMEOUT' | 'QUEUE_FULL';
76
+ export declare class TypfolioWorkerError extends Error {
77
+ readonly code: WorkerErrorCode;
78
+ readonly diagnostics: readonly Diagnostic[];
79
+ readonly name = "TypfolioWorkerError";
80
+ constructor(code: WorkerErrorCode, message: string, diagnostics?: readonly Diagnostic[], options?: ErrorOptions);
81
+ }
package/dist/types.js ADDED
@@ -0,0 +1,10 @@
1
+ export class TypfolioWorkerError extends Error {
2
+ code;
3
+ diagnostics;
4
+ name = 'TypfolioWorkerError';
5
+ constructor(code, message, diagnostics = [], options) {
6
+ super(message, options);
7
+ this.code = code;
8
+ this.diagnostics = diagnostics;
9
+ }
10
+ }
@@ -0,0 +1,6 @@
1
+ import { type RuntimeMessage } from './protocol.js';
2
+ export interface WorkerRuntimeScope {
3
+ addEventListener(type: 'message', listener: (event: MessageEvent<unknown>) => void): void;
4
+ postMessage(message: RuntimeMessage, transfer?: readonly Transferable[]): void;
5
+ }
6
+ export declare function installWorkerRuntime(scope: WorkerRuntimeScope): void;
@@ -0,0 +1,65 @@
1
+ import { createCompiler, TypstPdfError } from '@typfolio/core';
2
+ import { decodeHostMessage, protocolVersion } from './protocol.js';
3
+ function errorMessage(error) {
4
+ if (error instanceof Error)
5
+ return error.message;
6
+ return String(error);
7
+ }
8
+ function serializeError(error) {
9
+ if (error instanceof TypstPdfError) {
10
+ return { code: error.code, message: error.message, diagnostics: error.diagnostics };
11
+ }
12
+ return { code: 'WORKER', message: errorMessage(error), diagnostics: [] };
13
+ }
14
+ function transferable(bytes) {
15
+ return bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength ? bytes : bytes.slice();
16
+ }
17
+ export function installWorkerRuntime(scope) {
18
+ let compiler;
19
+ let initializing;
20
+ scope.addEventListener('message', event => {
21
+ let requestId;
22
+ try {
23
+ const message = decodeHostMessage(event.data);
24
+ if (message.type === 'initialize') {
25
+ if (initializing || compiler)
26
+ throw new Error('Typfolio worker is already initialized');
27
+ // The request is owned by this worker (a transferred snapshot), so core need not copy its assets again.
28
+ initializing = createCompiler({ ...message.compiler, copyAssets: false }).then(value => {
29
+ compiler = value;
30
+ scope.postMessage({ protocol: protocolVersion, type: 'ready' });
31
+ }).catch(error => {
32
+ scope.postMessage({ protocol: protocolVersion, type: 'failure', error: serializeError(error) });
33
+ });
34
+ return;
35
+ }
36
+ requestId = message.id;
37
+ if (!compiler)
38
+ throw new Error('Typfolio worker is not ready');
39
+ void compiler.compile(message.request).then(result => {
40
+ const bytes = transferable(result.bytes);
41
+ scope.postMessage({
42
+ protocol: protocolVersion,
43
+ type: 'result',
44
+ id: message.id,
45
+ result: { ...result, bytes },
46
+ }, [bytes.buffer]);
47
+ }).catch(error => {
48
+ scope.postMessage({
49
+ protocol: protocolVersion,
50
+ type: 'failure',
51
+ id: message.id,
52
+ error: serializeError(error),
53
+ });
54
+ });
55
+ }
56
+ catch (error) {
57
+ scope.postMessage({
58
+ protocol: protocolVersion,
59
+ type: 'failure',
60
+ id: requestId,
61
+ error: serializeError(error),
62
+ });
63
+ }
64
+ });
65
+ }
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@typfolio/workers",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Framework-independent Web Worker execution for Typfolio PDF compilation",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "keywords": ["typst", "pdf", "wasm", "webassembly", "web-worker", "browser", "concurrency"],
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/HelioCampus/typfolio.git",
11
+ "directory": "packages/workers"
12
+ },
13
+ "homepage": "https://github.com/HelioCampus/typfolio#readme",
14
+ "bugs": { "url": "https://github.com/HelioCampus/typfolio/issues" },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
+ },
24
+ "./runtime": "./dist/runtime.js"
25
+ },
26
+ "dependencies": {
27
+ "@typfolio/core": "^0.1.0",
28
+ "effect": "4.0.0-rc.118"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "engines": { "node": ">=22" },
34
+ "sideEffects": [
35
+ "./dist/runtime.js"
36
+ ]
37
+ }