webslm 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.
Files changed (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +373 -2
  3. package/dist/ai-sdk/index.d.ts +81 -0
  4. package/dist/ai-sdk/index.js +90 -0
  5. package/dist/ai-sdk/language-model.d.ts +77 -0
  6. package/dist/ai-sdk/language-model.js +422 -0
  7. package/dist/ai-sdk/loader.d.ts +54 -0
  8. package/dist/ai-sdk/loader.js +170 -0
  9. package/dist/ai-sdk/output.d.ts +43 -0
  10. package/dist/ai-sdk/output.js +152 -0
  11. package/dist/ai-sdk/prompt.d.ts +21 -0
  12. package/dist/ai-sdk/prompt.js +111 -0
  13. package/dist/async-queue.d.ts +22 -0
  14. package/dist/async-queue.js +70 -0
  15. package/dist/cache/cache-api.d.ts +29 -0
  16. package/dist/cache/cache-api.js +115 -0
  17. package/dist/cache/index.d.ts +21 -0
  18. package/dist/cache/index.js +42 -0
  19. package/dist/cache/memory.d.ts +12 -0
  20. package/dist/cache/memory.js +61 -0
  21. package/dist/cache/models.d.ts +67 -0
  22. package/dist/cache/models.js +107 -0
  23. package/dist/cache/node-fs.d.ts +21 -0
  24. package/dist/cache/node-fs.js +147 -0
  25. package/dist/cache/opfs.d.ts +69 -0
  26. package/dist/cache/opfs.js +181 -0
  27. package/dist/cache/store.d.ts +53 -0
  28. package/dist/cache/store.js +64 -0
  29. package/dist/cache-management.d.ts +23 -0
  30. package/dist/cache-management.js +58 -0
  31. package/dist/capabilities.d.ts +67 -0
  32. package/dist/capabilities.js +55 -0
  33. package/dist/client.d.ts +61 -0
  34. package/dist/client.js +256 -0
  35. package/dist/curated.d.ts +22 -0
  36. package/dist/curated.js +53 -0
  37. package/dist/download.d.ts +51 -0
  38. package/dist/download.js +289 -0
  39. package/dist/engine.d.ts +54 -0
  40. package/dist/engine.js +510 -0
  41. package/dist/errors.d.ts +81 -0
  42. package/dist/errors.js +89 -0
  43. package/dist/hub.d.ts +185 -0
  44. package/dist/hub.js +409 -0
  45. package/dist/index.d.ts +37 -0
  46. package/dist/index.js +41 -0
  47. package/dist/models.d.ts +225 -0
  48. package/dist/models.js +730 -0
  49. package/dist/node-pool-worker.d.ts +6 -0
  50. package/dist/node-pool-worker.js +32 -0
  51. package/dist/node-web-worker.d.ts +23 -0
  52. package/dist/node-web-worker.js +84 -0
  53. package/dist/node-worker.d.ts +2 -0
  54. package/dist/node-worker.js +9 -0
  55. package/dist/pool-worker.d.ts +36 -0
  56. package/dist/pool-worker.js +30 -0
  57. package/dist/pool.d.ts +17 -0
  58. package/dist/pool.js +41 -0
  59. package/dist/protocol.d.ts +246 -0
  60. package/dist/protocol.js +19 -0
  61. package/dist/runtime.d.ts +21 -0
  62. package/dist/runtime.js +53 -0
  63. package/dist/safetensors.d.ts +20 -0
  64. package/dist/safetensors.js +2 -0
  65. package/dist/simple.d.ts +310 -0
  66. package/dist/simple.js +553 -0
  67. package/dist/types.d.ts +412 -0
  68. package/dist/types.js +2 -0
  69. package/dist/wasm-flavour.d.ts +85 -0
  70. package/dist/wasm-flavour.js +169 -0
  71. package/dist/wasm.d.ts +34 -0
  72. package/dist/wasm.js +38 -0
  73. package/dist/worker.d.ts +6 -0
  74. package/dist/worker.js +11 -0
  75. package/package.json +92 -3
  76. package/wasm/relaxed/webslm_wasm.d.ts +325 -0
  77. package/wasm/relaxed/webslm_wasm.js +1899 -0
  78. package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
  79. package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +56 -0
  80. package/wasm/simd/webslm_wasm.d.ts +325 -0
  81. package/wasm/simd/webslm_wasm.js +1899 -0
  82. package/wasm/simd/webslm_wasm_bg.wasm +0 -0
  83. package/wasm/simd/webslm_wasm_bg.wasm.d.ts +56 -0
  84. package/wasm/threads/snippets/wasm-bindgen-rayon-38edf6e439f6d70d/src/workerHelpers.js +108 -0
  85. package/wasm/threads/webslm_wasm.d.ts +357 -0
  86. package/wasm/threads/webslm_wasm.js +2100 -0
  87. package/wasm/threads/webslm_wasm_bg.wasm +0 -0
  88. package/wasm/threads/webslm_wasm_bg.wasm.d.ts +66 -0
@@ -0,0 +1,152 @@
1
+ /**
2
+ * What a call asks the model to write: text, JSON (constrained by the
3
+ * engine's JSON grammar when it can enforce the schema), or the input of a
4
+ * single forced tool, which is JSON following the tool's schema.
5
+ */
6
+ /**
7
+ * JSON Schema keywords the engine's constrained decoding rejects (kept in
8
+ * sync with `UNSUPPORTED` in `crates/webslm-core/src/grammar.rs`).
9
+ */
10
+ const UNSUPPORTED_KEYWORDS = [
11
+ "$ref",
12
+ "$dynamicRef",
13
+ "anyOf",
14
+ "oneOf",
15
+ "allOf",
16
+ "not",
17
+ "if",
18
+ "then",
19
+ "else",
20
+ "pattern",
21
+ "patternProperties",
22
+ "propertyNames",
23
+ "format",
24
+ "minimum",
25
+ "maximum",
26
+ "exclusiveMinimum",
27
+ "exclusiveMaximum",
28
+ "multipleOf",
29
+ "minLength",
30
+ "maxLength",
31
+ "minProperties",
32
+ "maxProperties",
33
+ "dependentRequired",
34
+ "dependentSchemas",
35
+ "uniqueItems",
36
+ "prefixItems",
37
+ "contains",
38
+ "minContains",
39
+ "maxContains",
40
+ "unevaluatedProperties",
41
+ "unevaluatedItems",
42
+ ];
43
+ /** The first keyword of `schema` (or of a schema nested in it) that the engine cannot enforce. */
44
+ export function unsupportedKeyword(schema) {
45
+ if (typeof schema !== "object" || schema === null || Array.isArray(schema))
46
+ return undefined;
47
+ const map = schema;
48
+ const found = UNSUPPORTED_KEYWORDS.find((keyword) => keyword in map);
49
+ if (found !== undefined)
50
+ return found;
51
+ const nested = [map.items, map.additionalProperties];
52
+ if (typeof map.properties === "object" && map.properties !== null) {
53
+ nested.push(...Object.values(map.properties));
54
+ }
55
+ for (const child of nested) {
56
+ const inner = unsupportedKeyword(child);
57
+ if (inner !== undefined)
58
+ return inner;
59
+ }
60
+ return undefined;
61
+ }
62
+ function describe(name, description) {
63
+ return [name, description].filter((s) => s !== undefined && s !== "").join(": ");
64
+ }
65
+ /** The function tool a call forces, when there is exactly one it can be. */
66
+ function forcedTool(options) {
67
+ const tools = (options.tools ?? []).filter((t) => t.type === "function");
68
+ const choice = options.toolChoice;
69
+ if (choice?.type === "tool")
70
+ return tools.find((t) => t.name === choice.toolName);
71
+ if (choice?.type === "required" && tools.length === 1 && options.tools?.length === 1)
72
+ return tools[0];
73
+ return undefined;
74
+ }
75
+ /**
76
+ * Decides what the model writes:
77
+ *
78
+ * - `responseFormat: { type: "json" }`: JSON, with its schema enforced token
79
+ * by token when the engine supports every keyword in it; otherwise any JSON
80
+ * object, the schema given in the system prompt (a `compatibility` warning).
81
+ * - one forced function tool (`toolChoice` naming it, or `"required"` with a
82
+ * single tool): the tool's input, constrained to its schema, returned as a
83
+ * tool call. A schema the engine cannot enforce, several tools or
84
+ * `toolChoice: "auto"` leave tools unsupported (a warning; the model answers
85
+ * with text). `toolChoice: "none"` ignores the tools.
86
+ */
87
+ export function prepareOutput(options) {
88
+ const warnings = [];
89
+ const tools = options.tools ?? [];
90
+ if (tools.length > 0 && options.toolChoice?.type !== "none") {
91
+ const tool = forcedTool(options);
92
+ const keyword = tool === undefined ? undefined : unsupportedKeyword(tool.inputSchema);
93
+ if (tool !== undefined && keyword === undefined && typeof tool.inputSchema === "object") {
94
+ const schema = tool.inputSchema;
95
+ const what = describe(tool.name, tool.description);
96
+ return {
97
+ mode: { kind: "tool", tool, schema },
98
+ instruction: `Call the tool ${what}. Answer with its input only, as a JSON value following this ` +
99
+ `JSON schema: ${JSON.stringify(schema)}`,
100
+ warnings,
101
+ };
102
+ }
103
+ warnings.push({
104
+ type: "unsupported",
105
+ feature: "tools",
106
+ details: keyword !== undefined
107
+ ? `the tool's input schema uses \`${keyword}\`, which constrained decoding cannot enforce: the model answers with text`
108
+ : "webslm calls a tool only when the call forces a single one (toolChoice): the model answers with text",
109
+ });
110
+ }
111
+ const format = options.responseFormat;
112
+ if (format?.type !== "json")
113
+ return { mode: { kind: "text" }, warnings };
114
+ const what = describe(format.name, format.description);
115
+ const schema = format.schema;
116
+ const keyword = schema === undefined ? undefined : unsupportedKeyword(schema);
117
+ const instruction = [
118
+ "Answer with a single JSON value and nothing else: no prose, no code fence.",
119
+ ...(what === "" ? [] : [`It describes ${what}.`]),
120
+ ...(schema === undefined ? [] : [`It must follow this JSON schema: ${JSON.stringify(schema)}`]),
121
+ ].join(" ");
122
+ if (schema === undefined || typeof schema !== "object" || keyword !== undefined) {
123
+ if (keyword !== undefined) {
124
+ warnings.push({
125
+ type: "compatibility",
126
+ feature: "responseFormat",
127
+ details: `the schema uses \`${keyword}\`, which constrained decoding cannot enforce: the output is constrained to a JSON object, the schema is given in the system prompt`,
128
+ });
129
+ }
130
+ return { mode: { kind: "json" }, instruction, warnings };
131
+ }
132
+ return {
133
+ mode: { kind: "json", schema: schema },
134
+ instruction,
135
+ warnings,
136
+ };
137
+ }
138
+ /** Reasoning budgets (tokens) of the AI SDK's effort levels; the higher ones are unbounded. */
139
+ const THINKING_BUDGETS = {
140
+ minimal: 128,
141
+ low: 512,
142
+ medium: 2048,
143
+ };
144
+ /** The thinking budget of a `reasoning` level, when it sets one. */
145
+ export function thinkingBudgetOf(reasoning) {
146
+ return reasoning === undefined ? undefined : THINKING_BUDGETS[reasoning];
147
+ }
148
+ /** A tool call id, unique enough within a conversation. */
149
+ export function toolCallId() {
150
+ const random = globalThis.crypto?.randomUUID?.();
151
+ return `call_${random ?? `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`}`;
152
+ }
@@ -0,0 +1,21 @@
1
+ /** Turns an AI SDK prompt into the chat messages a chat template renders. */
2
+ import type { LanguageModelV4Prompt, SharedV4Warning } from "@ai-sdk/provider";
3
+ import type { ChatMessage } from "../types.js";
4
+ /** The chat messages of a prompt, and what could only be approximated. */
5
+ export interface ConvertedPrompt {
6
+ readonly messages: ChatMessage[];
7
+ readonly warnings: SharedV4Warning[];
8
+ }
9
+ /**
10
+ * Converts the prompt. Consecutive messages of one role are merged (some
11
+ * templates require alternating turns). Reasoning of earlier answers is
12
+ * dropped, as the templates of reasoning models do. Tool calls and results
13
+ * of earlier turns, which a model without tool support cannot read, become
14
+ * plain text, with a compatibility warning.
15
+ */
16
+ export declare function convertPrompt(prompt: LanguageModelV4Prompt): ConvertedPrompt;
17
+ /**
18
+ * A prompt as plain text, for checkpoints without a chat template (base
19
+ * models complete text): the contents one after the other.
20
+ */
21
+ export declare function promptText(messages: readonly ChatMessage[]): string;
@@ -0,0 +1,111 @@
1
+ /** Turns an AI SDK prompt into the chat messages a chat template renders. */
2
+ import { WebslmError } from "../errors.js";
3
+ /** The text of a file part: inline text documents only (the engine reads text). */
4
+ function fileText(part) {
5
+ if (part.data.type === "text")
6
+ return part.data.text;
7
+ throw new WebslmError("INVALID_ARGUMENT", `webslm runs text-only models: file parts (${part.mediaType}) are not supported`);
8
+ }
9
+ function toolOutputText(output) {
10
+ switch (output.type) {
11
+ case "text":
12
+ case "error-text":
13
+ return output.value;
14
+ case "json":
15
+ case "error-json":
16
+ return JSON.stringify(output.value);
17
+ case "execution-denied":
18
+ return output.reason === undefined ? "Execution denied." : `Execution denied: ${output.reason}`;
19
+ case "content":
20
+ return output.value.map((part) => (part.type === "text" ? part.text : "")).join("");
21
+ }
22
+ }
23
+ function toolCallText(name, input) {
24
+ return `Calling ${name}(${JSON.stringify(input)})`;
25
+ }
26
+ function toolResultText(name, output) {
27
+ return `${name} returned: ${toolOutputText(output)}`;
28
+ }
29
+ /**
30
+ * Converts the prompt. Consecutive messages of one role are merged (some
31
+ * templates require alternating turns). Reasoning of earlier answers is
32
+ * dropped, as the templates of reasoning models do. Tool calls and results
33
+ * of earlier turns, which a model without tool support cannot read, become
34
+ * plain text, with a compatibility warning.
35
+ */
36
+ export function convertPrompt(prompt) {
37
+ const messages = [];
38
+ const warnings = [];
39
+ let toolsAsText = false;
40
+ const push = (role, content) => {
41
+ const last = messages.at(-1);
42
+ if (last !== undefined && last.role === role && role !== "system") {
43
+ messages[messages.length - 1] = { role, content: `${last.content}\n\n${content}` };
44
+ }
45
+ else {
46
+ messages.push({ role, content });
47
+ }
48
+ };
49
+ for (const message of prompt) {
50
+ switch (message.role) {
51
+ case "system":
52
+ push("system", message.content);
53
+ break;
54
+ case "user":
55
+ push("user", message.content.map((part) => (part.type === "text" ? part.text : fileText(part))).join(""));
56
+ break;
57
+ case "assistant": {
58
+ let text = "";
59
+ for (const part of message.content) {
60
+ switch (part.type) {
61
+ case "text":
62
+ text += part.text;
63
+ break;
64
+ case "file":
65
+ text += fileText(part);
66
+ break;
67
+ case "tool-call":
68
+ toolsAsText = true;
69
+ text += `${text === "" ? "" : "\n"}${toolCallText(part.toolName, part.input)}`;
70
+ break;
71
+ case "tool-result":
72
+ toolsAsText = true;
73
+ text += `${text === "" ? "" : "\n"}${toolResultText(part.toolName, part.output)}`;
74
+ break;
75
+ // Reasoning, reasoning files and custom parts are not sent back.
76
+ default:
77
+ break;
78
+ }
79
+ }
80
+ push("assistant", text);
81
+ break;
82
+ }
83
+ case "tool": {
84
+ const results = message.content.flatMap((part) => part.type === "tool-result" ? [toolResultText(part.toolName, part.output)] : []);
85
+ if (results.length > 0) {
86
+ toolsAsText = true;
87
+ push("user", results.join("\n"));
88
+ }
89
+ break;
90
+ }
91
+ }
92
+ }
93
+ if (toolsAsText) {
94
+ warnings.push({
95
+ type: "compatibility",
96
+ feature: "tool messages",
97
+ details: "earlier tool calls and results are sent to the model as plain text",
98
+ });
99
+ }
100
+ if (messages.length === 0) {
101
+ throw new WebslmError("INVALID_ARGUMENT", "the prompt has no message");
102
+ }
103
+ return { messages, warnings };
104
+ }
105
+ /**
106
+ * A prompt as plain text, for checkpoints without a chat template (base
107
+ * models complete text): the contents one after the other.
108
+ */
109
+ export function promptText(messages) {
110
+ return messages.map((m) => m.content).join("\n\n");
111
+ }
@@ -0,0 +1,22 @@
1
+ /** A push-based async iterable shared by the streaming APIs. */
2
+ /**
3
+ * Values pushed by a producer, read by one consumer with `for await`. The
4
+ * producer ends the queue, or fails it with an error the consumer rethrows
5
+ * once the values pushed before it are read.
6
+ */
7
+ export declare class AsyncQueue<T> {
8
+ #private;
9
+ /** Whether the producer ended (or failed) the queue. */
10
+ get done(): boolean;
11
+ push(value: T): void;
12
+ /** Ends the queue; later pushes are ignored. */
13
+ end(): void;
14
+ /** Ends the queue with an error. */
15
+ fail(error: unknown): void;
16
+ /**
17
+ * Yields the values until the queue ends. `onExit` runs when iteration
18
+ * stops, including when the consumer leaves early (`break`, `return`, a
19
+ * throw in the loop body).
20
+ */
21
+ iterate(onExit?: () => void): AsyncGenerator<T>;
22
+ }
@@ -0,0 +1,70 @@
1
+ /** A push-based async iterable shared by the streaming APIs. */
2
+ /**
3
+ * Values pushed by a producer, read by one consumer with `for await`. The
4
+ * producer ends the queue, or fails it with an error the consumer rethrows
5
+ * once the values pushed before it are read.
6
+ */
7
+ export class AsyncQueue {
8
+ #items = [];
9
+ #wake;
10
+ #done = false;
11
+ #failed = false;
12
+ #error;
13
+ /** Whether the producer ended (or failed) the queue. */
14
+ get done() {
15
+ return this.#done;
16
+ }
17
+ push(value) {
18
+ if (this.#done)
19
+ return;
20
+ this.#items.push(value);
21
+ this.#notify();
22
+ }
23
+ /** Ends the queue; later pushes are ignored. */
24
+ end() {
25
+ if (this.#done)
26
+ return;
27
+ this.#done = true;
28
+ this.#notify();
29
+ }
30
+ /** Ends the queue with an error. */
31
+ fail(error) {
32
+ if (this.#done)
33
+ return;
34
+ this.#failed = true;
35
+ this.#error = error;
36
+ this.end();
37
+ }
38
+ #notify() {
39
+ const wake = this.#wake;
40
+ this.#wake = undefined;
41
+ wake?.();
42
+ }
43
+ /**
44
+ * Yields the values until the queue ends. `onExit` runs when iteration
45
+ * stops, including when the consumer leaves early (`break`, `return`, a
46
+ * throw in the loop body).
47
+ */
48
+ async *iterate(onExit) {
49
+ try {
50
+ for (;;) {
51
+ const next = this.#items.shift();
52
+ if (next !== undefined) {
53
+ yield next;
54
+ continue;
55
+ }
56
+ if (this.#done) {
57
+ if (this.#failed)
58
+ throw this.#error;
59
+ return;
60
+ }
61
+ await new Promise((resolve) => {
62
+ this.#wake = resolve;
63
+ });
64
+ }
65
+ }
66
+ finally {
67
+ onExit?.();
68
+ }
69
+ }
70
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Cache API store, the fallback when OPFS is unavailable. Files are stored
3
+ * whole as responses of the `webslm` cache, so downloads cannot resume.
4
+ */
5
+ import { type CacheEntry, type CacheStore, type CacheWriter } from "./store.js";
6
+ /** Name of the Cache API cache. */
7
+ export declare const CACHE_NAME = "webslm";
8
+ /** The subset of `Cache` used here. */
9
+ export interface CacheLike {
10
+ match(request: string): Promise<Response | undefined>;
11
+ put(request: string, response: Response): Promise<void>;
12
+ delete(request: string): Promise<boolean>;
13
+ keys(): Promise<readonly {
14
+ readonly url: string;
15
+ }[]>;
16
+ }
17
+ export declare class CacheApiStore implements CacheStore {
18
+ #private;
19
+ readonly kind = "cache-api";
20
+ readonly resumable = false;
21
+ constructor(cache: CacheLike);
22
+ /** Opens the `webslm` cache, or returns `undefined` when the Cache API is unavailable. */
23
+ static open(): Promise<CacheApiStore | undefined>;
24
+ size(path: string): Promise<number | undefined>;
25
+ openWriter(path: string, offset: number): Promise<CacheWriter>;
26
+ read(path: string, start?: number, end?: number): Promise<Uint8Array>;
27
+ list(prefix: string): Promise<CacheEntry[]>;
28
+ remove(path: string): Promise<void>;
29
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Cache API store, the fallback when OPFS is unavailable. Files are stored
3
+ * whole as responses of the `webslm` cache, so downloads cannot resume.
4
+ */
5
+ import { pathSegments, resolveRange, } from "./store.js";
6
+ /** Name of the Cache API cache. */
7
+ export const CACHE_NAME = "webslm";
8
+ /** Origin of the synthetic URLs the files are stored under. */
9
+ const BASE_URL = "https://cache.webslm.invalid/";
10
+ export class CacheApiStore {
11
+ kind = "cache-api";
12
+ resumable = false;
13
+ #cache;
14
+ #blobs = new Map();
15
+ constructor(cache) {
16
+ this.#cache = cache;
17
+ }
18
+ /** Opens the `webslm` cache, or returns `undefined` when the Cache API is unavailable. */
19
+ static async open() {
20
+ const caches = globalThis.caches;
21
+ if (caches === undefined)
22
+ return undefined;
23
+ try {
24
+ return new CacheApiStore(await caches.open(CACHE_NAME));
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
30
+ async #blob(path) {
31
+ const url = toUrl(path);
32
+ const known = this.#blobs.get(url);
33
+ if (known !== undefined)
34
+ return known;
35
+ const response = await this.#cache.match(url);
36
+ if (response === undefined)
37
+ return undefined;
38
+ const blob = await response.blob();
39
+ this.#blobs.set(url, blob);
40
+ return blob;
41
+ }
42
+ async size(path) {
43
+ return (await this.#blob(path))?.size;
44
+ }
45
+ async openWriter(path, offset) {
46
+ const url = toUrl(path);
47
+ const kept = offset === 0 ? undefined : await this.#blob(path);
48
+ if (offset !== 0 && (kept === undefined || kept.size < offset)) {
49
+ throw new RangeError(`cannot write "${path}" from ${offset}: it is shorter`);
50
+ }
51
+ const parts = kept === undefined ? [] : [kept.slice(0, offset)];
52
+ let done = false;
53
+ return {
54
+ write: async (chunk) => {
55
+ parts.push(chunk.slice());
56
+ },
57
+ close: async () => {
58
+ if (done)
59
+ return;
60
+ done = true;
61
+ const blob = new Blob(parts);
62
+ this.#blobs.delete(url);
63
+ await this.#cache.put(url, new Response(blob, { headers: { "content-length": String(blob.size) } }));
64
+ },
65
+ abort: async () => {
66
+ // Incomplete files are not stored: the Cache API cannot append.
67
+ done = true;
68
+ },
69
+ };
70
+ }
71
+ async read(path, start, end) {
72
+ const blob = await this.#blob(path);
73
+ if (blob === undefined) {
74
+ const error = new Error(`"${path}" is not in the cache`);
75
+ error.name = "NotFoundError";
76
+ throw error;
77
+ }
78
+ const [s, e] = resolveRange(path, blob.size, start, end);
79
+ return new Uint8Array(await blob.slice(s, e).arrayBuffer());
80
+ }
81
+ async list(prefix) {
82
+ const p = pathSegments(prefix).join("/");
83
+ const entries = [];
84
+ for (const request of await this.#cache.keys()) {
85
+ const path = fromUrl(request.url);
86
+ if (path === undefined)
87
+ continue;
88
+ if (p === "" || path === p || path.startsWith(`${p}/`)) {
89
+ const size = (await this.size(path)) ?? 0;
90
+ entries.push({ path, size });
91
+ }
92
+ }
93
+ return entries.sort((a, b) => a.path.localeCompare(b.path));
94
+ }
95
+ async remove(path) {
96
+ const p = pathSegments(path).join("/");
97
+ for (const request of await this.#cache.keys()) {
98
+ const stored = fromUrl(request.url);
99
+ if (stored === undefined)
100
+ continue;
101
+ if (p === "" || stored === p || stored.startsWith(`${p}/`)) {
102
+ this.#blobs.delete(request.url);
103
+ await this.#cache.delete(request.url);
104
+ }
105
+ }
106
+ }
107
+ }
108
+ function toUrl(path) {
109
+ return BASE_URL + pathSegments(path).map(encodeURIComponent).join("/");
110
+ }
111
+ function fromUrl(url) {
112
+ if (!url.startsWith(BASE_URL))
113
+ return undefined;
114
+ return url.slice(BASE_URL.length).split("/").map(decodeURIComponent).join("/");
115
+ }
@@ -0,0 +1,21 @@
1
+ /** Picks the cache store of the current environment. */
2
+ import { MemoryStore } from "./memory.js";
3
+ import type { CacheStore } from "./store.js";
4
+ export type { CacheEntry, CacheStore, CacheWriter } from "./store.js";
5
+ /** The shared in-memory store (per JavaScript realm). */
6
+ export declare function memoryStore(): MemoryStore;
7
+ /**
8
+ * The store downloads go to: a directory in Node, else OPFS, else the Cache
9
+ * API, else memory.
10
+ */
11
+ export declare function openStore(options?: {
12
+ cacheDir?: string;
13
+ }): Promise<CacheStore>;
14
+ /**
15
+ * Every persistent store that may hold models in this environment (OPFS and
16
+ * the Cache API in browsers, the cache directory in Node), for listing and
17
+ * deleting.
18
+ */
19
+ export declare function openAllStores(options?: {
20
+ cacheDir?: string;
21
+ }): Promise<CacheStore[]>;
@@ -0,0 +1,42 @@
1
+ /** Picks the cache store of the current environment. */
2
+ import { isNode } from "../runtime.js";
3
+ import { CacheApiStore } from "./cache-api.js";
4
+ import { MemoryStore } from "./memory.js";
5
+ import { NodeFsStore } from "./node-fs.js";
6
+ import { OpfsStore } from "./opfs.js";
7
+ let memory;
8
+ /** The shared in-memory store (per JavaScript realm). */
9
+ export function memoryStore() {
10
+ memory ??= new MemoryStore();
11
+ return memory;
12
+ }
13
+ /**
14
+ * The store downloads go to: a directory in Node, else OPFS, else the Cache
15
+ * API, else memory.
16
+ */
17
+ export async function openStore(options = {}) {
18
+ if (isNode()) {
19
+ return NodeFsStore.open(options.cacheDir);
20
+ }
21
+ return (await OpfsStore.open()) ?? (await CacheApiStore.open()) ?? memoryStore();
22
+ }
23
+ /**
24
+ * Every persistent store that may hold models in this environment (OPFS and
25
+ * the Cache API in browsers, the cache directory in Node), for listing and
26
+ * deleting.
27
+ */
28
+ export async function openAllStores(options = {}) {
29
+ if (isNode()) {
30
+ return [await NodeFsStore.open(options.cacheDir)];
31
+ }
32
+ const stores = [];
33
+ const opfs = await OpfsStore.open();
34
+ if (opfs !== undefined)
35
+ stores.push(opfs);
36
+ const cacheApi = await CacheApiStore.open();
37
+ if (cacheApi !== undefined)
38
+ stores.push(cacheApi);
39
+ if (memory !== undefined)
40
+ stores.push(memory);
41
+ return stores;
42
+ }
@@ -0,0 +1,12 @@
1
+ /** In-memory cache: the last-resort fallback, and the store used by tests. */
2
+ import { type CacheEntry, type CacheStore, type CacheWriter } from "./store.js";
3
+ export declare class MemoryStore implements CacheStore {
4
+ #private;
5
+ readonly kind = "memory";
6
+ readonly resumable = true;
7
+ size(path: string): Promise<number | undefined>;
8
+ openWriter(path: string, offset: number): Promise<CacheWriter>;
9
+ read(path: string, start?: number, end?: number): Promise<Uint8Array>;
10
+ list(prefix: string): Promise<CacheEntry[]>;
11
+ remove(path: string): Promise<void>;
12
+ }
@@ -0,0 +1,61 @@
1
+ /** In-memory cache: the last-resort fallback, and the store used by tests. */
2
+ import { concatChunks, pathSegments, resolveRange, } from "./store.js";
3
+ export class MemoryStore {
4
+ kind = "memory";
5
+ resumable = true;
6
+ #files = new Map();
7
+ async size(path) {
8
+ return this.#files.get(key(path))?.length;
9
+ }
10
+ async openWriter(path, offset) {
11
+ const k = key(path);
12
+ const existing = this.#files.get(k) ?? new Uint8Array(0);
13
+ if (offset > existing.length) {
14
+ throw new RangeError(`cannot write "${path}" from ${offset}: it holds ${existing.length} bytes`);
15
+ }
16
+ const chunks = [existing.subarray(0, offset)];
17
+ // Chunks are joined once, when the writer ends.
18
+ const flush = () => {
19
+ this.#files.set(k, concatChunks(chunks));
20
+ };
21
+ return {
22
+ write: async (chunk) => {
23
+ chunks.push(chunk.slice());
24
+ },
25
+ close: async () => flush(),
26
+ abort: async () => flush(),
27
+ };
28
+ }
29
+ async read(path, start, end) {
30
+ const file = this.#files.get(key(path));
31
+ if (file === undefined)
32
+ throw notFound(path);
33
+ const [s, e] = resolveRange(path, file.length, start, end);
34
+ return file.slice(s, e);
35
+ }
36
+ async list(prefix) {
37
+ const p = key(prefix);
38
+ const entries = [];
39
+ for (const [path, bytes] of this.#files) {
40
+ if (p === "" || path === p || path.startsWith(`${p}/`)) {
41
+ entries.push({ path, size: bytes.length });
42
+ }
43
+ }
44
+ return entries.sort((a, b) => a.path.localeCompare(b.path));
45
+ }
46
+ async remove(path) {
47
+ const p = key(path);
48
+ for (const k of [...this.#files.keys()]) {
49
+ if (p === "" || k === p || k.startsWith(`${p}/`))
50
+ this.#files.delete(k);
51
+ }
52
+ }
53
+ }
54
+ function key(path) {
55
+ return pathSegments(path).join("/");
56
+ }
57
+ function notFound(path) {
58
+ const error = new Error(`"${path}" is not in the cache`);
59
+ error.name = "NotFoundError";
60
+ return error;
61
+ }