@moss-dev/moss-web 1.2.0 → 1.3.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/README.md CHANGED
@@ -18,7 +18,7 @@ Built on WebAssembly for near-native performance in any modern browser.
18
18
  npm install @moss-dev/moss-web
19
19
  ```
20
20
 
21
- Version 1.2.0 resolves `@moss-dev/moss-wasm@0.15.0`. Text `query()` loads its
21
+ Version 1.3.0 resolves `@moss-dev/moss-wasm@0.16.0`. Text `query()` loads its
22
22
  model through the Moss service using the client's credentials, so the service
23
23
  must be reachable the first time a model is loaded; there is no offline
24
24
  fallback. The only published npm versions before this are 1.0.0 and 1.0.1,
@@ -75,22 +75,31 @@ class MyBackendAuthenticator implements IAuthenticator {
75
75
  const res = await fetch("/api/moss-token", { method: "POST" });
76
76
  return res.json(); // { token, expiresIn }
77
77
  }
78
- async getAuthHeader(): Promise<string> {
79
- const { token } = await this.getAuthToken();
80
- return `Bearer ${token}`;
81
- }
82
78
  }
83
79
 
84
80
  const client = new MossClient(projectId, new MyBackendAuthenticator());
85
81
  await client.getAuthToken(); // cached AuthToken
86
82
  ```
87
83
 
88
- Tokens are cached until 60 seconds before expiry and refetched after a 401.
84
+ The client calls `getAuthToken()` only and sends the token as `Authorization: Bearer <token>`. `getAuthHeader()` on an `IAuthenticator` is optional and deprecated, since the client never calls it.
85
+
86
+ A token is cached until 60 seconds before it expires, or for 90% of its life when that is later, and refetched after a 401. A token whose `expiresIn` is not a positive finite number of seconds is not cached, so each request fetches a new one.
89
87
 
90
88
  **Options:**
91
89
 
92
90
  - `model` — `"moss-minilm"` (default, fast, for most use-cases) or `"moss-mediumlm"`
93
91
  - `baseUrl` — Custom API base URL (for self-hosted Moss instances)
92
+ - `onProgress` — Called with `{ modelId, loadedBytes, totalBytes, fromCache }` while the embedding model downloads
93
+
94
+ The first text query waits for the embedding model. The model grant request fails after 30 seconds without an answer. Each model file request aborts after 30 seconds without data and is retried once. The verified model is kept in the browser Cache API and checked against its SHA-256 before each use, so later page loads skip the download. On pages without the Cache API, such as plain HTTP, it downloads on each page load.
95
+
96
+ ```typescript
97
+ const client = new MossClient(projectId, projectKey, {
98
+ onProgress: ({ loadedBytes, totalBytes }) => {
99
+ progressBar.value = loadedBytes / totalBytes;
100
+ },
101
+ });
102
+ ```
94
103
 
95
104
  ### Index Management
96
105
 
@@ -1,8 +1,14 @@
1
1
  export interface AuthToken {
2
2
  token: string;
3
+ /** Seconds until the token expires. A token without a positive finite value is not cached. */
3
4
  expiresIn: number;
4
5
  }
6
+ /**
7
+ * Supplies short-lived tokens to `MossClient`.
8
+ * The client calls `getAuthToken` only and sends `Authorization: Bearer <token>`.
9
+ */
5
10
  export interface IAuthenticator {
6
11
  getAuthToken(): Promise<AuthToken>;
7
- getAuthHeader(): Promise<string>;
12
+ /** @deprecated The client never calls this. It builds the header from `getAuthToken`. */
13
+ getAuthHeader?(): Promise<string>;
8
14
  }
@@ -5,6 +5,7 @@ export declare class CachingAuthenticator implements IAuthenticator {
5
5
  private inflight;
6
6
  constructor(inner: IAuthenticator);
7
7
  getAuthToken(): Promise<AuthToken>;
8
+ /** The header the client sends, built from `getAuthToken`. */
8
9
  getAuthHeader(): Promise<string>;
9
10
  invalidate(): void;
10
11
  private fetchAndCache;
@@ -19,6 +19,7 @@ export class CachingAuthenticator {
19
19
  this.inflight = null;
20
20
  }
21
21
  }
22
+ /** The header the client sends, built from `getAuthToken`. */
22
23
  async getAuthHeader() {
23
24
  const { token } = await this.getAuthToken();
24
25
  return `Bearer ${token}`;
@@ -28,8 +29,21 @@ export class CachingAuthenticator {
28
29
  }
29
30
  async fetchAndCache() {
30
31
  const { token, expiresIn } = await this.inner.getAuthToken();
31
- const expiresAt = Date.now() + (expiresIn - 60) * 1000;
32
- this.cache = { token, expiresIn, expiresAt };
32
+ const lifetime = cacheLifetimeSeconds(expiresIn);
33
+ this.cache = lifetime > 0
34
+ ? { token, expiresIn, expiresAt: Date.now() + lifetime * 1000 }
35
+ : null;
33
36
  return { token, expiresIn };
34
37
  }
35
38
  }
39
+ /**
40
+ * Seconds to serve a token from the cache: until 60 seconds
41
+ * before it expires, or for 90% of its life when that is later.
42
+ * Returns 0, meaning uncached, unless `expiresIn` is a positive finite number.
43
+ */
44
+ function cacheLifetimeSeconds(expiresIn) {
45
+ if (!Number.isFinite(expiresIn) || expiresIn <= 0) {
46
+ return 0;
47
+ }
48
+ return Math.max(expiresIn * 0.9, expiresIn - 60);
49
+ }
package/dist/client.d.ts CHANGED
@@ -48,6 +48,12 @@ export declare class MossClient {
48
48
  hasIndex(indexName: string): Promise<boolean>;
49
49
  getIndexInfo(indexName: string): Promise<IndexInfo>;
50
50
  refreshIndex(indexName: string): Promise<RefreshResult>;
51
+ /**
52
+ * Embeds `query` locally and searches one loaded index.
53
+ *
54
+ * A blank `query` (empty or only whitespace) returns no results at every
55
+ * `alpha`, without running the embedding model. `topK` 0 returns no results.
56
+ */
51
57
  query(indexName: string, query: string, options?: QueryOptions): Promise<SearchResult>;
52
58
  queryWithEmbedding(indexName: string, query: string, embedding: Float32Array | number[], options?: QueryOptions): Promise<SearchResult>;
53
59
  /**
@@ -57,7 +63,8 @@ export declare class MossClient {
57
63
  *
58
64
  * `alpha` matches the single-index `query`: `1.0` is embedding-only, `0.0`
59
65
  * is keyword-only, and values between fuse both rankings. `topK` is the
60
- * global cap across the union, not a per-index cap.
66
+ * global cap across the union, not a per-index cap, and 0 returns no results.
67
+ * A blank `query` returns no results without running the embedding model.
61
68
  */
62
69
  queryMultiIndex(indexNames: string[], query: string, options?: QueryOptions): Promise<SearchResult>;
63
70
  /** As `queryMultiIndex`, with a caller-supplied query vector. */
package/dist/client.js CHANGED
@@ -2,7 +2,7 @@ import wasmInit, { IndexManager, ManageClient, ModelKeyExchange, ProjectKeyAuthe
2
2
  import { CachingAuthenticator } from "./auth/caching.authenticator.js";
3
3
  import { Embedder } from "./embedder.js";
4
4
  import { ModelArtifactOwnership } from "./model-artifact-ownership.js";
5
- import { exactModelArtifactIdentity, provenanceAwareIndexManager, queryWithResolvedModelIdentity, requireMultiIndexIndexManager, requireProvenanceAwareIndexManager, } from "./wasm-runtime-capability.js";
5
+ import { exactModelArtifactIdentity, provenanceAwareIndexManager, queryWithResolvedModelIdentity, requireMultiIndexIndexManager, requireProvenanceAwareIndexManager, runtimeQueryTuning, } from "./wasm-runtime-capability.js";
6
6
  const DEFAULT_MODEL = "moss-minilm";
7
7
  function sameModelArtifactIdentity(left, right) {
8
8
  if (left === null || right === null)
@@ -11,6 +11,10 @@ function sameModelArtifactIdentity(left, right) {
11
11
  && left.version === right.version
12
12
  && left.manifestSha256 === right.manifestSha256;
13
13
  }
14
+ /** True for a query with no text to match: empty or only whitespace. */
15
+ function isBlankQuery(query) {
16
+ return query.trim().length === 0;
17
+ }
14
18
  export class MossClient {
15
19
  constructor(projectId, auth, options) {
16
20
  this.initialized = false;
@@ -88,6 +92,7 @@ export class MossClient {
88
92
  runtime: { newKeyExchange: () => new ModelKeyExchange(), openSealedModel },
89
93
  baseUrl: this.options.baseUrl,
90
94
  artifactOrigin: this.options.modelArtifactOrigin,
95
+ onProgress: this.options.onProgress,
91
96
  });
92
97
  await this.embedder.init(this.options.onnxWasmPath);
93
98
  this.initialized = true;
@@ -198,6 +203,12 @@ export class MossClient {
198
203
  ? this.modelIdentityFromRefresh(result)
199
204
  : null);
200
205
  }
206
+ /**
207
+ * Embeds `query` locally and searches one loaded index.
208
+ *
209
+ * A blank `query` (empty or only whitespace) returns no results at every
210
+ * `alpha`, without running the embedding model. `topK` 0 returns no results.
211
+ */
201
212
  async query(indexName, query, options) {
202
213
  await this.ensureInitialized();
203
214
  const manager = requireProvenanceAwareIndexManager(this.indexManager);
@@ -205,8 +216,11 @@ export class MossClient {
205
216
  if (!identity) {
206
217
  throw new Error(`Index '${indexName}' has no foundation model artifact identity; use queryWithEmbedding`);
207
218
  }
219
+ if (isBlankQuery(query)) {
220
+ return { docs: [], query, indexName, timeTakenMs: 0 };
221
+ }
208
222
  const embedding = await this.embedder.embed(query, identity);
209
- return manager.queryWithModelIdentity(indexName, query, embedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter);
223
+ return manager.queryWithModelIdentity(indexName, query, embedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter, runtimeQueryTuning(options));
210
224
  }
211
225
  async queryWithEmbedding(indexName, query, embedding, options) {
212
226
  const im = await this.getIndexManager();
@@ -214,7 +228,7 @@ export class MossClient {
214
228
  const queryEmbedding = embedding instanceof Float32Array
215
229
  ? embedding
216
230
  : new Float32Array(embedding);
217
- return queryWithResolvedModelIdentity(im, identity, indexName, query, queryEmbedding, options?.topK, options?.alpha, options?.filter);
231
+ return queryWithResolvedModelIdentity(im, identity, indexName, query, queryEmbedding, options?.topK, options?.alpha, options?.filter, runtimeQueryTuning(options));
218
232
  }
219
233
  /**
220
234
  * Search several loaded indexes in one call and return the global top-k,
@@ -223,7 +237,8 @@ export class MossClient {
223
237
  *
224
238
  * `alpha` matches the single-index `query`: `1.0` is embedding-only, `0.0`
225
239
  * is keyword-only, and values between fuse both rankings. `topK` is the
226
- * global cap across the union, not a per-index cap.
240
+ * global cap across the union, not a per-index cap, and 0 returns no results.
241
+ * A blank `query` returns no results without running the embedding model.
227
242
  */
228
243
  async queryMultiIndex(indexNames, query, options) {
229
244
  if (indexNames.length === 0) {
@@ -232,8 +247,11 @@ export class MossClient {
232
247
  await this.ensureInitialized();
233
248
  const manager = requireMultiIndexIndexManager(this.indexManager);
234
249
  const identity = await this.sharedModelIdentity(indexNames);
250
+ if (isBlankQuery(query)) {
251
+ return { docs: [], query, timeTakenMs: 0 };
252
+ }
235
253
  const embedding = await this.embedder.embed(query, identity);
236
- return manager.queryMultiIndexWithModelIdentity(indexNames, query, embedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter);
254
+ return manager.queryMultiIndexWithModelIdentity(indexNames, query, embedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter, runtimeQueryTuning(options));
237
255
  }
238
256
  /** As `queryMultiIndex`, with a caller-supplied query vector. */
239
257
  async queryMultiIndexWithEmbedding(indexNames, query, embedding, options) {
@@ -247,9 +265,9 @@ export class MossClient {
247
265
  ? embedding
248
266
  : new Float32Array(embedding);
249
267
  if (identity) {
250
- return manager.queryMultiIndexWithModelIdentity(indexNames, query, queryEmbedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter);
268
+ return manager.queryMultiIndexWithModelIdentity(indexNames, query, queryEmbedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter, runtimeQueryTuning(options));
251
269
  }
252
- return manager.queryMultiIndex(indexNames, query, queryEmbedding, options?.topK, options?.alpha, options?.filter);
270
+ return manager.queryMultiIndex(indexNames, query, queryEmbedding, options?.topK, options?.alpha, options?.filter, runtimeQueryTuning(options));
253
271
  }
254
272
  /**
255
273
  * The one model artifact identity every named index shares, or `null` when
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { MossClient } from "./client.js";
2
2
  export type { IAuthenticator, AuthToken } from "./auth/authenticator.interface.js";
3
3
  export { ModelDeliveryError } from "./model-delivery.js";
4
- export type { MossClientOptions, MossModel, IndexInfo, SearchResult, QueryResultDocumentInfo, QueryOptions, MetadataFilter, FilterCondition, RefreshResult, ModelRef, ModelArtifactIdentity, DocumentInfo, MutationResult, CreateIndexOptions, MutationOptions, ParseFileInput, JobStatus, JobPhase, JobProgress, JobStatusResponse, GetDocumentsOptions, LoadIndexOptions, LoadIndexesResult, ISODate, } from "./types.js";
4
+ export type { MossClientOptions, MossModel, IndexInfo, SearchResult, QueryResultDocumentInfo, QueryOptions, MetadataFilter, FilterCondition, RefreshResult, ModelRef, ModelArtifactIdentity, ModelDownloadProgress, DocumentInfo, MutationResult, CreateIndexOptions, MutationOptions, ParseFileInput, JobStatus, JobPhase, JobProgress, JobStatusResponse, GetDocumentsOptions, LoadIndexOptions, LoadIndexesResult, ISODate, } from "./types.js";
@@ -1,5 +1,5 @@
1
1
  import type { ModelContentKeys, ModelKeyExchange, SealedModel, Tokenizer } from "@moss-dev/moss-wasm";
2
- import type { ModelArtifactIdentity } from "./types.js";
2
+ import type { ModelArtifactIdentity, ModelDownloadProgress } from "./types.js";
3
3
  export declare const DEFAULT_INDEX_BASE_URL = "https://service.usemoss.dev/index";
4
4
  export declare const DEFAULT_MODEL_ARTIFACT_ORIGIN = "https://models.moss.link";
5
5
  export interface SealedModelRuntime {
@@ -17,6 +17,11 @@ export interface ModelDeliveryOptions {
17
17
  baseUrl?: string;
18
18
  artifactOrigin?: string;
19
19
  fetch?: typeof fetch;
20
+ onProgress?: (progress: ModelDownloadProgress) => void;
21
+ /** Cache API storage for the verified model file. `null` turns caching off; unset uses `globalThis.caches`. */
22
+ caches?: CacheStorage | null;
23
+ /** How long the grant request, or an artifact response or its next chunk, may take before it is aborted. */
24
+ requestTimeoutMs?: number;
20
25
  }
21
26
  export interface GrantedObject {
22
27
  url: string;
@@ -54,7 +59,22 @@ export declare function parseArtifactOrigin(value: string): ArtifactOrigin;
54
59
  export declare function parseModelDeliveryGrant(json: string, sku: string, artifactOrigin?: string): ModelDeliveryGrant;
55
60
  export declare function grantAcceptsStamp(grant: ModelDeliveryGrant, stamped: ModelArtifactIdentity): boolean;
56
61
  export declare function requestModelDeliveryGrant(options: ModelDeliveryOptions, sku: string, capabilityQuery: string): Promise<ModelDeliveryGrant>;
57
- export declare function fetchGrantedBytes(fetchFn: typeof fetch, object: GrantedObject, maxBytes?: number): Promise<Uint8Array>;
62
+ export interface ArtifactTransfer {
63
+ /** The transfer aborts as soon as more bytes than this arrive. */
64
+ maxBytes: number;
65
+ /** Writes the body into one buffer of exactly `maxBytes` bytes. A shorter body is retried. */
66
+ preallocate?: boolean;
67
+ /** Receives the running byte count of the current attempt after each chunk. */
68
+ onBytes?: (loadedBytes: number) => void;
69
+ timeoutMs?: number;
70
+ }
71
+ /**
72
+ * Streams one granted artifact into memory.
73
+ *
74
+ * Each attempt aborts when the response or the next chunk takes longer than
75
+ * the deadline. A stall, a network error, a 408, a 429 or a 5xx is retried once.
76
+ */
77
+ export declare function fetchGrantedBytes(fetchFn: typeof fetch, object: GrantedObject, transfer: ArtifactTransfer): Promise<Uint8Array>;
58
78
  export declare function verifyReleaseManifest(releaseBytes: Uint8Array, grant: ModelDeliveryGrant): Promise<ReleaseFile>;
59
79
  export declare function verifyModelBytes(bytes: Uint8Array, record: ReleaseFile): Promise<void>;
60
80
  export declare function loadSealedModel(options: ModelDeliveryOptions, stamped: ModelArtifactIdentity): Promise<SealedModelBundle>;
@@ -7,6 +7,10 @@ const RELEASE_FILE = "release.json";
7
7
  const MODEL_FILE = "model.mossml";
8
8
  const SUPPORTED_RELEASE_SCHEMA_VERSIONS = [1, 2];
9
9
  const MAX_RELEASE_MANIFEST_BYTES = 1024 * 1024;
10
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30000;
11
+ const ARTIFACT_REQUEST_ATTEMPTS = 2;
12
+ const ARTIFACT_CACHE_NAME = "moss-model-artifacts-v1";
13
+ const ARTIFACT_CACHE_PATH = "/.moss-artifact-cache";
10
14
  export class ModelDeliveryError extends Error {
11
15
  constructor(message, status, code) {
12
16
  super(message);
@@ -15,6 +19,9 @@ export class ModelDeliveryError extends Error {
15
19
  this.code = code;
16
20
  }
17
21
  }
22
+ /** A transport failure worth one more attempt: a stall, a dropped connection, a short body, a 408, a 429 or a 5xx. */
23
+ class ArtifactTransferError extends ModelDeliveryError {
24
+ }
18
25
  function isCanonicalSha256(value) {
19
26
  return /^[0-9a-f]{64}$/.test(value);
20
27
  }
@@ -129,40 +136,230 @@ export async function requestModelDeliveryGrant(options, sku, capabilityQuery) {
129
136
  const fetchFn = options.fetch ?? fetch;
130
137
  const baseUrl = (options.baseUrl ?? DEFAULT_INDEX_BASE_URL).replace(/\/+$/, "");
131
138
  const url = `${baseUrl}/model-artifacts/download?${capabilityQuery}`;
132
- const send = async (authHeader) => fetchFn(url, {
133
- method: "GET",
134
- headers: { Authorization: authHeader, "x-project-id": options.projectId },
135
- credentials: "omit",
136
- });
137
- let response = await send(await options.auth.getAuthHeader());
138
- if (response.status === 401) {
139
- await options.auth.invalidate();
139
+ const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
140
+ let deadline;
141
+ let timer;
142
+ const send = (authHeader) => {
143
+ clearTimeout(timer);
144
+ const controller = new AbortController();
145
+ deadline = controller;
146
+ timer = setTimeout(() => controller.abort(), timeoutMs);
147
+ return fetchFn(url, {
148
+ method: "GET",
149
+ headers: { Authorization: authHeader, "x-project-id": options.projectId },
150
+ credentials: "omit",
151
+ signal: controller.signal,
152
+ });
153
+ };
154
+ let response;
155
+ let body;
156
+ try {
140
157
  response = await send(await options.auth.getAuthHeader());
158
+ if (response.status === 401) {
159
+ response.body?.cancel().catch(() => undefined);
160
+ await options.auth.invalidate();
161
+ response = await send(await options.auth.getAuthHeader());
162
+ }
163
+ body = response.ok
164
+ ? await response.text()
165
+ : await response.text().catch((error) => {
166
+ if (deadline?.signal.aborted)
167
+ throw error;
168
+ return "";
169
+ });
170
+ }
171
+ catch (error) {
172
+ if (!deadline?.signal.aborted)
173
+ throw error;
174
+ throw new ModelDeliveryError(`Model grant request for '${sku}' got no answer within ${timeoutMs} ms`);
175
+ }
176
+ finally {
177
+ clearTimeout(timer);
141
178
  }
142
179
  if (!response.ok) {
143
- const body = await response.text().catch(() => "");
144
180
  const code = issuerErrorCode(body);
145
181
  const hint = code === "MODEL_ARTIFACT_UNAVAILABLE" || code === "MODEL_ARTIFACT_ENCRYPTED_UNAVAILABLE"
146
182
  ? "; no sealed model artifact is published for this model yet"
147
183
  : "";
148
184
  throw new ModelDeliveryError(`Issuer refused the sealed model grant for '${sku}' (HTTP ${response.status} ${code})${hint}; no plaintext fallback`, response.status, code);
149
185
  }
150
- return parseModelDeliveryGrant(await response.text(), sku, options.artifactOrigin);
186
+ return parseModelDeliveryGrant(body, sku, options.artifactOrigin);
187
+ }
188
+ /**
189
+ * Streams one granted artifact into memory.
190
+ *
191
+ * Each attempt aborts when the response or the next chunk takes longer than
192
+ * the deadline. A stall, a network error, a 408, a 429 or a 5xx is retried once.
193
+ */
194
+ export async function fetchGrantedBytes(fetchFn, object, transfer) {
195
+ for (let attempt = 1;; attempt += 1) {
196
+ try {
197
+ return await fetchGrantedBytesOnce(fetchFn, object, transfer);
198
+ }
199
+ catch (error) {
200
+ if (!(error instanceof ArtifactTransferError) || attempt >= ARTIFACT_REQUEST_ATTEMPTS) {
201
+ throw error;
202
+ }
203
+ }
204
+ }
151
205
  }
152
- export async function fetchGrantedBytes(fetchFn, object, maxBytes) {
153
- const response = await fetchFn(object.url, {
206
+ async function fetchGrantedBytesOnce(fetchFn, object, transfer) {
207
+ const timeoutMs = transfer.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
208
+ const controller = new AbortController();
209
+ const network = async (step, failure) => {
210
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
211
+ try {
212
+ return await step();
213
+ }
214
+ catch (error) {
215
+ throw new ArtifactTransferError(controller.signal.aborted
216
+ ? `Fetching '${object.url}' stalled: nothing arrived for ${timeoutMs} ms`
217
+ : `${failure}: ${String(error)}`);
218
+ }
219
+ finally {
220
+ clearTimeout(timer);
221
+ }
222
+ };
223
+ const response = await network(() => fetchFn(object.url, {
154
224
  method: "GET",
155
225
  headers: { Authorization: `Bearer ${object.capability}` },
156
226
  credentials: "omit",
157
- });
227
+ signal: controller.signal,
228
+ }), `Failed to fetch '${object.url}'`);
158
229
  if (!response.ok) {
159
- throw new ModelDeliveryError(`Failed to fetch '${object.url}': ${response.status}`, response.status);
230
+ response.body?.cancel().catch(() => undefined);
231
+ const message = `Failed to fetch '${object.url}': ${response.status}`;
232
+ const transient = response.status >= 500 || response.status === 408 || response.status === 429;
233
+ throw transient
234
+ ? new ArtifactTransferError(message, response.status)
235
+ : new ModelDeliveryError(message, response.status);
236
+ }
237
+ return await readArtifactBody(response, object.url, transfer, network);
238
+ }
239
+ async function readArtifactBody(response, url, transfer, network) {
240
+ const target = transfer.preallocate ? new Uint8Array(transfer.maxBytes) : null;
241
+ const chunks = [];
242
+ let loaded = 0;
243
+ const finish = () => {
244
+ if (target && loaded < transfer.maxBytes) {
245
+ throw new ArtifactTransferError(`'${url}' has an unexpected size: the transfer ended after ${loaded} of ${transfer.maxBytes} bytes`);
246
+ }
247
+ return target ?? joinChunks(chunks, loaded);
248
+ };
249
+ if (!response.body)
250
+ return finish();
251
+ const reader = response.body.getReader();
252
+ try {
253
+ for (;;) {
254
+ const next = await network(() => reader.read(), `Transfer of '${url}' failed`);
255
+ if (next.done)
256
+ break;
257
+ const chunk = next.value;
258
+ if (loaded + chunk.byteLength > transfer.maxBytes) {
259
+ throw new ModelDeliveryError(`'${url}' exceeds ${transfer.maxBytes} bytes`);
260
+ }
261
+ if (target)
262
+ target.set(chunk, loaded);
263
+ else
264
+ chunks.push(chunk);
265
+ loaded += chunk.byteLength;
266
+ transfer.onBytes?.(loaded);
267
+ }
268
+ }
269
+ catch (error) {
270
+ reader.cancel().catch(() => undefined);
271
+ throw error;
272
+ }
273
+ return finish();
274
+ }
275
+ function joinChunks(chunks, length) {
276
+ if (chunks.length === 1)
277
+ return chunks[0];
278
+ const joined = new Uint8Array(length);
279
+ let offset = 0;
280
+ for (const chunk of chunks) {
281
+ joined.set(chunk, offset);
282
+ offset += chunk.byteLength;
283
+ }
284
+ return joined;
285
+ }
286
+ /**
287
+ * Verified model files in the Cache API, keyed by the release manifest digest.
288
+ *
289
+ * Every read is verified again by the caller. Caching is best effort: storage that
290
+ * is missing, as in Node or an insecure context, or that fails, turns into a miss.
291
+ */
292
+ class ArtifactCache {
293
+ constructor(storage, origin) {
294
+ this.cache = null;
295
+ this.storage = storage;
296
+ this.prefix = `${origin.protocol}//${origin.host}${ARTIFACT_CACHE_PATH}/`;
297
+ }
298
+ key(sku, manifestSha256) {
299
+ return `${this.prefix}${sku}/${manifestSha256}/${MODEL_FILE}`;
300
+ }
301
+ async read(key) {
302
+ try {
303
+ const response = await (await this.open())?.match(key);
304
+ return response ? new Uint8Array(await response.arrayBuffer()) : null;
305
+ }
306
+ catch {
307
+ return null;
308
+ }
309
+ }
310
+ async write(key, bytes) {
311
+ if (!this.storage)
312
+ return;
313
+ try {
314
+ const response = new Response(bytes, {
315
+ headers: { "content-type": "application/octet-stream" },
316
+ });
317
+ await (await this.open())?.put(key, response);
318
+ }
319
+ catch {
320
+ // A full or unavailable cache only costs a download on the next page load.
321
+ }
322
+ }
323
+ async remove(key) {
324
+ try {
325
+ await (await this.open())?.delete(key);
326
+ }
327
+ catch {
328
+ // A stale entry that cannot be removed fails verification again on the next read.
329
+ }
330
+ }
331
+ /** Drops the artifacts of every other release of this model. */
332
+ async pruneOtherReleases(sku, manifestSha256) {
333
+ try {
334
+ const cache = await this.open();
335
+ if (!cache)
336
+ return;
337
+ const modelPrefix = `${this.prefix}${sku}/`;
338
+ const keep = `${modelPrefix}${manifestSha256}/`;
339
+ for (const request of await cache.keys()) {
340
+ if (request.url.startsWith(modelPrefix) && !request.url.startsWith(keep)) {
341
+ await cache.delete(request);
342
+ }
343
+ }
344
+ }
345
+ catch {
346
+ // Leftover releases are only a storage cost.
347
+ }
160
348
  }
161
- const bytes = new Uint8Array(await response.arrayBuffer());
162
- if (maxBytes !== undefined && bytes.byteLength > maxBytes) {
163
- throw new ModelDeliveryError(`'${object.url}' exceeds ${maxBytes} bytes`);
349
+ open() {
350
+ if (!this.storage)
351
+ return Promise.resolve(null);
352
+ this.cache ?? (this.cache = this.storage.open(ARTIFACT_CACHE_NAME).catch(() => null));
353
+ return this.cache;
354
+ }
355
+ }
356
+ function defaultCacheStorage() {
357
+ try {
358
+ return globalThis.caches ?? undefined;
359
+ }
360
+ catch {
361
+ return undefined;
164
362
  }
165
- return bytes;
166
363
  }
167
364
  function parseReleaseFiles(value) {
168
365
  if (!Array.isArray(value)) {
@@ -259,21 +456,66 @@ export async function loadSealedModel(options, stamped) {
259
456
  exchange.free();
260
457
  }
261
458
  try {
262
- const releaseBytes = await fetchGrantedBytes(fetchFn, grant.release, MAX_RELEASE_MANIFEST_BYTES);
459
+ const cache = new ArtifactCache(options.caches === undefined ? defaultCacheStorage() : options.caches ?? undefined, parseArtifactOrigin(options.artifactOrigin ?? DEFAULT_MODEL_ARTIFACT_ORIGIN));
460
+ const releaseBytes = await fetchGrantedBytes(fetchFn, grant.release, {
461
+ maxBytes: MAX_RELEASE_MANIFEST_BYTES,
462
+ timeoutMs: options.requestTimeoutMs,
463
+ });
263
464
  const record = await verifyReleaseManifest(releaseBytes, grant);
264
- const modelBytes = await fetchGrantedBytes(fetchFn, grant.model);
265
- await verifyModelBytes(modelBytes, record);
266
- const sealed = options.runtime.openSealedModel(modelBytes, keys, sku);
465
+ const model = await loadModelFile(options, fetchFn, cache, grant, record);
466
+ const sealed = options.runtime.openSealedModel(model.bytes, keys, sku);
467
+ let bundle;
267
468
  try {
268
469
  const graph = sealed.takeGraph();
269
470
  const tokenizer = sealed.takeTokenizer();
270
- return { grant, graph, tokenizer };
471
+ bundle = { grant, graph, tokenizer };
271
472
  }
272
473
  finally {
273
474
  sealed.free();
274
475
  }
476
+ model.persist?.();
477
+ return bundle;
275
478
  }
276
479
  finally {
277
480
  keys.free();
278
481
  }
279
482
  }
483
+ async function loadModelFile(options, fetchFn, cache, grant, record) {
484
+ const report = (loadedBytes, fromCache) => {
485
+ try {
486
+ options.onProgress?.({
487
+ modelId: grant.modelId,
488
+ loadedBytes,
489
+ totalBytes: record.sizeBytes,
490
+ fromCache,
491
+ });
492
+ }
493
+ catch {
494
+ // A failing progress callback must not fail the model load.
495
+ }
496
+ };
497
+ const manifestSha256 = grant.identity.manifestSha256;
498
+ const key = cache.key(grant.modelId, manifestSha256);
499
+ const cached = await cache.read(key);
500
+ if (cached) {
501
+ try {
502
+ await verifyModelBytes(cached, record);
503
+ report(cached.byteLength, true);
504
+ return { bytes: cached };
505
+ }
506
+ catch {
507
+ await cache.remove(key);
508
+ }
509
+ }
510
+ const bytes = await fetchGrantedBytes(fetchFn, grant.model, {
511
+ maxBytes: record.sizeBytes,
512
+ preallocate: true,
513
+ timeoutMs: options.requestTimeoutMs,
514
+ onBytes: (loaded) => report(loaded, false),
515
+ });
516
+ await verifyModelBytes(bytes, record);
517
+ const persist = () => {
518
+ void cache.write(key, bytes).then(() => cache.pruneOtherReleases(grant.modelId, manifestSha256));
519
+ };
520
+ return { bytes, persist };
521
+ }
package/dist/types.d.ts CHANGED
@@ -5,6 +5,21 @@ export interface MossClientOptions {
5
5
  wasmUrl?: string;
6
6
  onnxWasmPath?: string;
7
7
  modelArtifactOrigin?: string;
8
+ /**
9
+ * Called while the embedding model that text queries need is loaded, as bytes arrive.
10
+ * An error thrown here is ignored and does not stop the load.
11
+ */
12
+ onProgress?: (progress: ModelDownloadProgress) => void;
13
+ }
14
+ /** Progress of the embedding model file that the first text query waits on. */
15
+ export interface ModelDownloadProgress {
16
+ modelId: MossModel;
17
+ /** Bytes of the model file received so far. Starts again from 0 when a stalled request is retried. */
18
+ loadedBytes: number;
19
+ /** Size of the model file in bytes, as the verified release manifest records it. */
20
+ totalBytes: number;
21
+ /** True when the verified file came from the browser Cache API and no transfer took place. */
22
+ fromCache: boolean;
8
23
  }
9
24
  export interface ModelRef {
10
25
  id: string;
@@ -31,6 +46,13 @@ export interface QueryResultDocumentInfo {
31
46
  id: string;
32
47
  text: string;
33
48
  metadata?: Record<string, string>;
49
+ /**
50
+ * Relevance to the query from 0 to 1. It comes from vector similarity
51
+ * alone, so `alpha` and rank never change it. Results are ordered by hybrid
52
+ * relevance, so a lower result can show a higher score. A keyword-only query
53
+ * (`alpha` 0, or an index without vectors) scores every hit 0. Scores
54
+ * depend on the embedding model.
55
+ */
34
56
  score: number;
35
57
  /** Source index. Set on multi-index results; absent for single-index. */
36
58
  indexName?: string;
@@ -45,6 +67,14 @@ export interface QueryOptions {
45
67
  topK?: number;
46
68
  alpha?: number;
47
69
  filter?: MetadataFilter;
70
+ /**
71
+ * How many hits a hybrid query (`alpha` between 0 and 1) ranks on each
72
+ * signal before fusion. A hit outside both lists is never returned, so a
73
+ * deeper list raises recall and query time. Defaults to `2 * topK`. A set
74
+ * value must be at least 1 and is raised to `topK` when below it.
75
+ * Keyword-only and vector-only queries (`alpha` 0 or 1) ignore it.
76
+ */
77
+ candidateDepth?: number;
48
78
  }
49
79
  export type MetadataFilter = {
50
80
  field: string;
@@ -98,6 +128,10 @@ export interface CreateIndexOptions {
98
128
  onProgress?: (progress: JobProgress) => void;
99
129
  }
100
130
  export interface MutationOptions {
131
+ /**
132
+ * Whether a document replaces a stored one with the same ID.
133
+ * `addDocs` sends it only when set, and the cloud service decides how to apply it.
134
+ */
101
135
  upsert?: boolean;
102
136
  onProgress?: (progress: JobProgress) => void;
103
137
  }
@@ -1,14 +1,20 @@
1
- import type { MetadataFilter, ModelArtifactIdentity, SearchResult } from "./types.js";
1
+ import type { MetadataFilter, ModelArtifactIdentity, QueryOptions, SearchResult } from "./types.js";
2
+ /** Optional settings the runtime query methods take after `filter`. */
3
+ export interface RuntimeQueryTuning {
4
+ candidateDepth?: number;
5
+ }
6
+ /** The runtime tuning fields of `options`, or undefined when none is set. */
7
+ export declare function runtimeQueryTuning(options?: QueryOptions): RuntimeQueryTuning | undefined;
2
8
  export interface ProvenanceAwareIndexManager {
3
- queryWithModelIdentity(indexName: string, query: string, embedding: Float32Array, modelId: string, modelArtifactVersion: string, manifestSha256: string, topK: number | undefined, alpha: number | undefined, filter: MetadataFilter | undefined): Promise<SearchResult>;
9
+ queryWithModelIdentity(indexName: string, query: string, embedding: Float32Array, modelId: string, modelArtifactVersion: string, manifestSha256: string, topK: number | undefined, alpha: number | undefined, filter: MetadataFilter | undefined, tuning?: RuntimeQueryTuning): Promise<SearchResult>;
4
10
  }
5
11
  export declare function provenanceAwareIndexManager(manager: unknown): ProvenanceAwareIndexManager | null;
6
12
  export declare function requireProvenanceAwareIndexManager(manager: unknown): ProvenanceAwareIndexManager;
7
13
  export interface MultiIndexIndexManager {
8
- queryMultiIndex(indexNames: string[], query: string, embedding: Float32Array, topK: number | undefined, alpha: number | undefined, filter: MetadataFilter | undefined): Promise<SearchResult>;
9
- queryMultiIndexWithModelIdentity(indexNames: string[], query: string, embedding: Float32Array, modelId: string, modelArtifactVersion: string, manifestSha256: string, topK: number | undefined, alpha: number | undefined, filter: MetadataFilter | undefined): Promise<SearchResult>;
14
+ queryMultiIndex(indexNames: string[], query: string, embedding: Float32Array, topK: number | undefined, alpha: number | undefined, filter: MetadataFilter | undefined, tuning?: RuntimeQueryTuning): Promise<SearchResult>;
15
+ queryMultiIndexWithModelIdentity(indexNames: string[], query: string, embedding: Float32Array, modelId: string, modelArtifactVersion: string, manifestSha256: string, topK: number | undefined, alpha: number | undefined, filter: MetadataFilter | undefined, tuning?: RuntimeQueryTuning): Promise<SearchResult>;
10
16
  }
11
17
  export declare function multiIndexIndexManager(manager: unknown): MultiIndexIndexManager | null;
12
18
  export declare function requireMultiIndexIndexManager(manager: unknown): MultiIndexIndexManager;
13
19
  export declare function exactModelArtifactIdentity(modelId: string, version?: string, manifestSha256?: string): ModelArtifactIdentity | null;
14
- export declare function queryWithResolvedModelIdentity(manager: unknown, identity: ModelArtifactIdentity | null, indexName: string, query: string, embedding: Float32Array, topK: number | undefined, alpha: number | undefined, filter: MetadataFilter | undefined): Promise<SearchResult>;
20
+ export declare function queryWithResolvedModelIdentity(manager: unknown, identity: ModelArtifactIdentity | null, indexName: string, query: string, embedding: Float32Array, topK: number | undefined, alpha: number | undefined, filter: MetadataFilter | undefined, tuning?: RuntimeQueryTuning): Promise<SearchResult>;
@@ -1,3 +1,10 @@
1
+ /** The runtime tuning fields of `options`, or undefined when none is set. */
2
+ export function runtimeQueryTuning(options) {
3
+ if (options?.candidateDepth === undefined) {
4
+ return undefined;
5
+ }
6
+ return { candidateDepth: options.candidateDepth };
7
+ }
1
8
  export function provenanceAwareIndexManager(manager) {
2
9
  if (typeof manager !== "object"
3
10
  || manager === null
@@ -51,18 +58,18 @@ export function exactModelArtifactIdentity(modelId, version, manifestSha256) {
51
58
  }
52
59
  return { modelId, version, manifestSha256 };
53
60
  }
54
- export function queryWithResolvedModelIdentity(manager, identity, indexName, query, embedding, topK, alpha, filter) {
61
+ export function queryWithResolvedModelIdentity(manager, identity, indexName, query, embedding, topK, alpha, filter, tuning) {
55
62
  if (identity) {
56
63
  const capable = provenanceAwareIndexManager(manager);
57
64
  if (!capable) {
58
65
  throw new Error("The installed @moss-dev/moss-wasm runtime cannot bind this foundation query embedding to its exact model artifact identity");
59
66
  }
60
- return capable.queryWithModelIdentity(indexName, query, embedding, identity.modelId, identity.version, identity.manifestSha256, topK, alpha, filter);
67
+ return capable.queryWithModelIdentity(indexName, query, embedding, identity.modelId, identity.version, identity.manifestSha256, topK, alpha, filter, tuning);
61
68
  }
62
69
  if (typeof manager !== "object"
63
70
  || manager === null
64
71
  || typeof manager.query !== "function") {
65
72
  throw new Error("The installed @moss-dev/moss-wasm runtime cannot query this index");
66
73
  }
67
- return manager.query(indexName, query, embedding, topK, alpha, filter);
74
+ return manager.query(indexName, query, embedding, topK, alpha, filter, tuning);
68
75
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moss-dev/moss-web",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "type": "module",
5
5
  "description": "Moss browser SDK — in-browser semantic search powered by WASM",
6
6
  "main": "dist/index.js",
@@ -25,7 +25,7 @@
25
25
  "test": "npm run build && node --test"
26
26
  },
27
27
  "dependencies": {
28
- "@moss-dev/moss-wasm": "0.15.0",
28
+ "@moss-dev/moss-wasm": "0.16.0",
29
29
  "onnxruntime-web": "^1.27.0"
30
30
  },
31
31
  "devDependencies": {