@moss-dev/moss-web 1.3.0 → 1.4.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.3.0 resolves `@moss-dev/moss-wasm@0.16.0`. Text `query()` loads its
21
+ Version 1.4.0 resolves `@moss-dev/moss-wasm@0.17.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,
@@ -169,9 +169,45 @@ await client.unloadIndex(name);
169
169
  await client.unloadIndexes(names);
170
170
  ```
171
171
 
172
- `loadIndex` and `loadIndexes` accept `LoadIndexOptions` (`autoRefresh`,
173
- `pollingIntervalInSeconds`) for parity with the Node SDK, but the browser SDK
174
- does not honor them yet; use `refreshIndex` to pull server updates.
172
+ `refreshIndex` downloads the index only when the cloud has a newer version.
173
+ When the loaded version is current it downloads nothing and returns
174
+ `wasUpdated: false`.
175
+
176
+ `loadIndex` and `loadIndexes` accept `autoRefresh` and `pollingIntervalInSeconds`.
177
+ With `autoRefresh: true` the client refreshes that index every
178
+ `pollingIntervalInSeconds` (600 when unset or 0, at least 1) until the index is
179
+ unloaded, loaded again without `autoRefresh`, or the client is disposed. Loading
180
+ the same name again replaces the timer, and a failed refresh logs a warning and
181
+ retries on the next tick.
182
+ A `@moss-dev/moss-wasm` older than the release that skips unchanged snapshots
183
+ would download the whole index on every tick, so with one `autoRefresh` is off:
184
+ the index loads, the client logs one warning, and no timer starts.
185
+
186
+ ```typescript
187
+ await client.loadIndex("docs", { autoRefresh: true, pollingIntervalInSeconds: 300 });
188
+ ```
189
+
190
+ #### Job progress
191
+
192
+ `createIndex`, `createIndexFromFiles`, `addDocs` and `deleteDocs` wait for the
193
+ server job to finish. Pass `onProgress` to see each status the client polls.
194
+ An exception thrown by the callback, or a rejected promise it returns, is ignored.
195
+
196
+ ```typescript
197
+ await client.addDocs("docs", docs, {
198
+ onProgress: (p) => console.log(p.status, p.progress, p.currentPhase),
199
+ });
200
+ ```
201
+
202
+ `onProgress` needs a `@moss-dev/moss-wasm` whose job methods take the callback.
203
+ With an older package these calls throw an upgrade error before the job starts.
204
+
205
+ #### Metadata filters
206
+
207
+ `$gt`, `$gte`, `$lt` and `$lte` compare two plain decimals (`"42"`, `"-3.5"`) as numbers
208
+ and two other values as text. They never match a plain decimal against any other value, such as `"01234"`, `"1e3"` or `"NaN"`.
209
+ `$near` takes `"lat,lng,maxDistanceMeters"` and matches a `"lat,lng"` field value; any other `$near` value is an error.
210
+ A condition never matches a document that lacks the field, `$ne` and `$nin` included.
175
211
 
176
212
  #### Multi-index search
177
213
 
@@ -208,6 +244,70 @@ error.
208
244
  client.dispose();
209
245
  ```
210
246
 
247
+ ## Telemetry
248
+
249
+ The browser SDK always sends usage events, as the native Moss SDKs do. They
250
+ carry the query counts that Moss bills, so there is no option to turn them off.
251
+
252
+ Each client posts them to `<baseUrl>/telemetry`
253
+ (`https://service.usemoss.dev/index/telemetry` by default) with the same
254
+ credentials as its other requests. A query adds one to a count and sends
255
+ nothing. Every 3 seconds while there are new queries, the client gets a token
256
+ and sends the count, and `dispose()` sends what is left. While there are none,
257
+ it gets a token every 30 seconds, so a page that is closing can send without
258
+ waiting for one. It gets these tokens the way other requests do, so a cached
259
+ token costs no request, and with an authenticator whose tokens are not cached,
260
+ each one is a `getAuthToken()` call. Counts wait until the first token request
261
+ succeeds. A failed send is dropped. It never fails a query or raises an
262
+ unhandled promise rejection.
263
+
264
+ Each send is one usage body and the query events in JSON arrays of up to 500,
265
+ the bodies the native SDKs send. One send carries at most 10,000 query events,
266
+ and later queries wait for the next send. A send uses `keepalive`, so a
267
+ navigation does not cancel it, when it fits in about 60 KB that every client on
268
+ the page shares, since browsers allow 64 KiB of keepalive requests in flight per
269
+ page. On `pagehide` and `dispose()` the client starts at once the sends that fit.
270
+ After `pagehide` the rest stay counted for a page restored from the back/forward
271
+ cache, and are lost when the page unloads.
272
+
273
+ ### Device id
274
+
275
+ `deviceId` is the billable device key. A page reads it once, when its first
276
+ client initializes, from `localStorage` under `moss-device-id`. When there is
277
+ none, the SDK creates a random UUID and stores it there, so page reloads and
278
+ every client on the origin reuse it. Later clients on the same page reuse the id
279
+ in memory and do not touch `localStorage`, so after the site's data is cleared,
280
+ the next page load stores a new id. Where `localStorage` is missing or throws,
281
+ each page, worker or process gets a new id that lasts until it ends. That
282
+ happens in some private windows and sandboxed frames, in Web Workers, and under
283
+ Node or server rendering, so each of those counts as a new device. Browsers also
284
+ scope the stored id: a third-party iframe gets one id per top-level site, and
285
+ Safari deletes it after 7 days of use without a visit to the site.
286
+
287
+ ### Fields on every event
288
+
289
+ | Field | Value |
290
+ |---|---|
291
+ | `action` | Always `"telemetry"`. |
292
+ | `eventType` | The event type, from the table below. |
293
+ | `projectId` | Your project id. |
294
+ | `clientId`, `sessionId` | The same random id, one per client. |
295
+ | `sdkVersion`, `sdkPackageVersion` | Version of `@moss-dev/moss-wasm`. |
296
+ | `nativeCoreVersion` | Version of the Rust core. |
297
+ | `deviceId`, `mossDeviceId` | The device id, the same value in both. |
298
+
299
+ ### Event types
300
+
301
+ | Event | Sent when | Extra fields |
302
+ |---|---|---|
303
+ | `index.usage.periodic_flush` | Every 3 seconds while there are new queries | `queryCount`, and `docsEmbedded` and `tokensEstimated`, always 0 |
304
+ | `index.usage.final_flush` | On `dispose()` and `pagehide`, when queries are left | The same as `index.usage.periodic_flush` |
305
+ | `index.query` | Once per single index query, in a batch | None |
306
+ | `index.query_multi` | Once per multi-index query, in a batch | None |
307
+
308
+ Query events carry no index name, latency or model, because a query only adds
309
+ to a count. No document text, query text, metadata or embedding is ever sent.
310
+
211
311
  ## License
212
312
 
213
313
  See [LICENSE](./LICENSE.txt).
package/dist/client.d.ts CHANGED
@@ -12,6 +12,8 @@ export declare class MossClient {
12
12
  private projectKeyAuthenticator;
13
13
  private initPromise;
14
14
  private readonly modelArtifacts;
15
+ private readonly autoRefreshLoops;
16
+ private autoRefreshUnsupportedWarned;
15
17
  constructor(projectId: string, projectKey: string, options?: MossClientOptions);
16
18
  constructor(projectId: string, authenticator: IAuthenticator, options?: MossClientOptions);
17
19
  getAuthToken(): Promise<AuthToken>;
@@ -35,18 +37,31 @@ export declare class MossClient {
35
37
  deleteIndex(indexName: string): Promise<boolean>;
36
38
  getDocs(indexName: string, options?: GetDocumentsOptions): Promise<DocumentInfo[]>;
37
39
  getJobStatus(jobId: string): Promise<JobStatusResponse>;
38
- loadIndex(indexName: string, _options?: LoadIndexOptions): Promise<string>;
40
+ /**
41
+ * Load an index into browser memory.
42
+ *
43
+ * With `autoRefresh`, the index is refreshed from the cloud
44
+ * every `pollingIntervalInSeconds` (600 when unset or 0, minimum 1)
45
+ * until it is unloaded, loaded again without `autoRefresh`, or the client is disposed.
46
+ * A failed load keeps the running loop, and a failed refresh keeps the model of the loaded index.
47
+ * A `@moss-dev/moss-wasm` that would download the whole index on every tick gets a warning and no loop.
48
+ */
49
+ loadIndex(indexName: string, options?: LoadIndexOptions): Promise<string>;
39
50
  unloadIndex(indexName: string): Promise<void>;
40
51
  /**
41
52
  * Best-effort bulk load. Loads one index at a time so each keeps its own
42
- * model artifact identity; failures are reported in `failed` and never roll
43
- * back the indexes that did load.
53
+ * model artifact identity; failures are reported in `failed`, with their
54
+ * codes in `failedCodes`, and never roll back the indexes that did load.
44
55
  */
45
56
  loadIndexes(indexNames: string[], options?: LoadIndexOptions): Promise<LoadIndexesResult>;
46
57
  /** Best-effort bulk unload; names that are not loaded are ignored. */
47
58
  unloadIndexes(indexNames: string[]): Promise<void>;
48
59
  hasIndex(indexName: string): Promise<boolean>;
49
60
  getIndexInfo(indexName: string): Promise<IndexInfo>;
61
+ /**
62
+ * Install the cloud's snapshot of a loaded index when it is newer. A snapshot no newer
63
+ * than the loaded one, with the same model, downloads nothing and returns `wasUpdated` false.
64
+ */
50
65
  refreshIndex(indexName: string): Promise<RefreshResult>;
51
66
  /**
52
67
  * Embeds `query` locally and searches one loaded index.
@@ -82,5 +97,8 @@ export declare class MossClient {
82
97
  private modelIdentityFromInfo;
83
98
  private modelIdentityFromRefresh;
84
99
  private exactModelIdentity;
100
+ /** Refreshes `indexName` on `im` until the loop is replaced or stopped, or `im` is disposed. */
101
+ private startAutoRefresh;
102
+ private stopAutoRefresh;
85
103
  dispose(): void;
86
104
  }
package/dist/client.js CHANGED
@@ -1,9 +1,31 @@
1
1
  import wasmInit, { IndexManager, ManageClient, ModelKeyExchange, ProjectKeyAuthenticator, openSealedModel, poolAndNormalize, } from "@moss-dev/moss-wasm";
2
+ import * as mossWasm from "@moss-dev/moss-wasm";
2
3
  import { CachingAuthenticator } from "./auth/caching.authenticator.js";
3
4
  import { Embedder } from "./embedder.js";
4
5
  import { ModelArtifactOwnership } from "./model-artifact-ownership.js";
5
- import { exactModelArtifactIdentity, provenanceAwareIndexManager, queryWithResolvedModelIdentity, requireMultiIndexIndexManager, requireProvenanceAwareIndexManager, runtimeQueryTuning, } from "./wasm-runtime-capability.js";
6
+ import { callWithProgress, exactModelArtifactIdentity, matchedSealedModelOpener, provenanceAwareIndexManager, queryWithResolvedModelIdentity, refreshSkipsUnchanged, requireMultiIndexIndexManager, requireProvenanceAwareIndexManager, runtimeQueryTuning, webCryptoSealedModelRuntime, } from "./wasm-runtime-capability.js";
6
7
  const DEFAULT_MODEL = "moss-minilm";
8
+ /** Auto refresh interval when `pollingIntervalInSeconds` is unset or 0, as in the native SDKs. */
9
+ const DEFAULT_POLLING_INTERVAL_SECONDS = 600;
10
+ /** Shortest auto refresh interval. Smaller values use it. */
11
+ const MIN_POLLING_INTERVAL_SECONDS = 1;
12
+ /** Longest interval `setTimeout` honors. It fires at once for anything longer. */
13
+ const MAX_POLLING_INTERVAL_SECONDS = Math.floor(2147483647 / 1000);
14
+ /**
15
+ * The auto refresh delay in milliseconds for `options`, or `null` when auto
16
+ * refresh is off. Throws on an interval that is not a finite number of zero or more.
17
+ */
18
+ function autoRefreshDelayMs(options) {
19
+ if (!options?.autoRefresh)
20
+ return null;
21
+ const requested = options.pollingIntervalInSeconds ?? DEFAULT_POLLING_INTERVAL_SECONDS;
22
+ if (typeof requested !== "number" || !Number.isFinite(requested) || requested < 0) {
23
+ throw new RangeError(`pollingIntervalInSeconds must be a finite number of zero or more, got ${String(requested)}`);
24
+ }
25
+ const seconds = requested === 0 ? DEFAULT_POLLING_INTERVAL_SECONDS : requested;
26
+ const clamped = Math.min(Math.max(seconds, MIN_POLLING_INTERVAL_SECONDS), MAX_POLLING_INTERVAL_SECONDS);
27
+ return Math.round(clamped * 1000);
28
+ }
7
29
  function sameModelArtifactIdentity(left, right) {
8
30
  if (left === null || right === null)
9
31
  return left === right;
@@ -26,6 +48,8 @@ export class MossClient {
26
48
  this.modelArtifacts = new ModelArtifactOwnership((identities) => {
27
49
  this.embedder?.retainModelArtifacts(identities);
28
50
  });
51
+ this.autoRefreshLoops = new Map();
52
+ this.autoRefreshUnsupportedWarned = false;
29
53
  this.projectId = projectId;
30
54
  if (typeof auth === "string") {
31
55
  this.projectKey = auth;
@@ -89,7 +113,12 @@ export class MossClient {
89
113
  this.embedder = new Embedder(model, poolAndNormalize, {
90
114
  projectId: this.projectId,
91
115
  auth: deliveryAuth,
92
- runtime: { newKeyExchange: () => new ModelKeyExchange(), openSealedModel },
116
+ runtime: {
117
+ newKeyExchange: () => new ModelKeyExchange(),
118
+ openSealedModel,
119
+ openMatchedSealedModel: matchedSealedModelOpener(mossWasm),
120
+ webCrypto: webCryptoSealedModelRuntime(mossWasm),
121
+ },
93
122
  baseUrl: this.options.baseUrl,
94
123
  artifactOrigin: this.options.modelArtifactOrigin,
95
124
  onProgress: this.options.onProgress,
@@ -111,20 +140,20 @@ export class MossClient {
111
140
  const hasEmbeddings = docs.some((d) => Array.isArray(d.embedding) && d.embedding.length > 0);
112
141
  const modelId = options?.modelId
113
142
  ?? (hasEmbeddings ? "custom" : (this.options.model ?? DEFAULT_MODEL));
114
- return manage.createIndex(indexName, docs, modelId);
143
+ return callWithProgress(manage, "createIndex", [indexName, docs, modelId], options?.onProgress);
115
144
  }
116
145
  async createIndexFromFiles(indexName, files, options) {
117
146
  const manage = await this.getManageClient();
118
147
  const modelId = options?.modelId ?? (this.options.model ?? DEFAULT_MODEL);
119
- return manage.createIndexFromFiles(indexName, files, modelId);
148
+ return callWithProgress(manage, "createIndexFromFiles", [indexName, files, modelId], options?.onProgress);
120
149
  }
121
150
  async addDocs(indexName, docs, options) {
122
151
  const manage = await this.getManageClient();
123
- return manage.addDocs(indexName, docs, options?.upsert);
152
+ return callWithProgress(manage, "addDocs", [indexName, docs, options?.upsert], options?.onProgress);
124
153
  }
125
154
  async deleteDocs(indexName, docIds, options) {
126
155
  const manage = await this.getManageClient();
127
- return manage.deleteDocs(indexName, docIds);
156
+ return callWithProgress(manage, "deleteDocs", [indexName, docIds], options?.onProgress);
128
157
  }
129
158
  async getIndex(indexName) {
130
159
  const manage = await this.getManageClient();
@@ -147,26 +176,52 @@ export class MossClient {
147
176
  return manage.getJobStatus(jobId);
148
177
  }
149
178
  // ── Local index operations ─────────────────────────────────
150
- async loadIndex(indexName, _options) {
179
+ /**
180
+ * Load an index into browser memory.
181
+ *
182
+ * With `autoRefresh`, the index is refreshed from the cloud
183
+ * every `pollingIntervalInSeconds` (600 when unset or 0, minimum 1)
184
+ * until it is unloaded, loaded again without `autoRefresh`, or the client is disposed.
185
+ * A failed load keeps the running loop, and a failed refresh keeps the model of the loaded index.
186
+ * A `@moss-dev/moss-wasm` that would download the whole index on every tick gets a warning and no loop.
187
+ */
188
+ async loadIndex(indexName, options) {
189
+ let refreshDelayMs = autoRefreshDelayMs(options);
151
190
  const im = await this.getIndexManager();
191
+ if (refreshDelayMs !== null && !refreshSkipsUnchanged(im)) {
192
+ refreshDelayMs = null;
193
+ if (!this.autoRefreshUnsupportedWarned) {
194
+ this.autoRefreshUnsupportedWarned = true;
195
+ console.warn("The installed @moss-dev/moss-wasm downloads the whole index on every refresh, so autoRefresh is off. Upgrade @moss-dev/moss-wasm to enable it.");
196
+ }
197
+ }
152
198
  await this.modelArtifacts.replaceAfter(indexName, () => im.loadIndex(indexName), (info) => provenanceAwareIndexManager(im)
153
199
  ? this.modelIdentityFromInfo(info)
154
200
  : null, async () => {
155
201
  await im.unloadIndex(indexName);
156
202
  });
203
+ // dispose() ran while the load was pending, so the index belongs to a freed manager.
204
+ if (this.indexManager !== im)
205
+ return indexName;
206
+ this.stopAutoRefresh(indexName);
207
+ if (refreshDelayMs !== null) {
208
+ this.startAutoRefresh(indexName, refreshDelayMs, im);
209
+ }
157
210
  return indexName;
158
211
  }
159
212
  async unloadIndex(indexName) {
213
+ this.stopAutoRefresh(indexName);
160
214
  const im = await this.getIndexManager();
161
215
  await this.modelArtifacts.removeAfter(indexName, () => im.unloadIndex(indexName));
162
216
  }
163
217
  /**
164
218
  * Best-effort bulk load. Loads one index at a time so each keeps its own
165
- * model artifact identity; failures are reported in `failed` and never roll
166
- * back the indexes that did load.
219
+ * model artifact identity; failures are reported in `failed`, with their
220
+ * codes in `failedCodes`, and never roll back the indexes that did load.
167
221
  */
168
222
  async loadIndexes(indexNames, options) {
169
- const result = { loaded: [], failed: {} };
223
+ const failedCodes = {};
224
+ const result = { loaded: [], failed: {}, failedCodes };
170
225
  for (const name of indexNames) {
171
226
  try {
172
227
  await this.loadIndex(name, options);
@@ -174,6 +229,9 @@ export class MossClient {
174
229
  }
175
230
  catch (error) {
176
231
  result.failed[name] = error instanceof Error ? error.message : String(error);
232
+ const code = error?.code;
233
+ if (typeof code === "string")
234
+ failedCodes[name] = code;
177
235
  }
178
236
  }
179
237
  return result;
@@ -197,6 +255,10 @@ export class MossClient {
197
255
  ? this.modelIdentityFromInfo(info)
198
256
  : null);
199
257
  }
258
+ /**
259
+ * Install the cloud's snapshot of a loaded index when it is newer. A snapshot no newer
260
+ * than the loaded one, with the same model, downloads nothing and returns `wasUpdated` false.
261
+ */
200
262
  async refreshIndex(indexName) {
201
263
  const im = await this.getIndexManager();
202
264
  return this.modelArtifacts.replaceAfter(indexName, () => im.refreshIndex(indexName), (result) => provenanceAwareIndexManager(im)
@@ -318,7 +380,59 @@ export class MossClient {
318
380
  exactModelIdentity(modelId, version, manifestSha256) {
319
381
  return exactModelArtifactIdentity(modelId, version, manifestSha256);
320
382
  }
383
+ /** Refreshes `indexName` on `im` until the loop is replaced or stopped, or `im` is disposed. */
384
+ startAutoRefresh(indexName, delayMs, im) {
385
+ const loop = { timer: undefined };
386
+ const current = () => this.autoRefreshLoops.get(indexName) === loop && this.indexManager === im;
387
+ const schedule = () => {
388
+ loop.timer = setTimeout(tick, delayMs);
389
+ // Under Node, an idle refresh timer must not keep the process alive.
390
+ loop.timer.unref?.();
391
+ };
392
+ // Unlike `refreshIndex`, a failed tick keeps the index's model identity:
393
+ // the loaded index is unchanged, and dropping it would release the model.
394
+ const tick = async () => {
395
+ if (!current())
396
+ return;
397
+ try {
398
+ const result = await im.refreshIndex(indexName);
399
+ if (current()) {
400
+ this.modelArtifacts.synchronize(indexName, provenanceAwareIndexManager(im) ? this.modelIdentityFromRefresh(result) : null);
401
+ }
402
+ }
403
+ catch (error) {
404
+ if (!current())
405
+ return;
406
+ const loaded = await im.hasIndex(indexName).catch(() => true);
407
+ if (!current())
408
+ return;
409
+ if (!loaded) {
410
+ this.stopAutoRefresh(indexName);
411
+ try {
412
+ this.modelArtifacts.clear(indexName);
413
+ }
414
+ catch { }
415
+ return;
416
+ }
417
+ console.warn(`Moss auto refresh of '${indexName}' failed: ${error instanceof Error ? error.message : String(error)}`);
418
+ }
419
+ if (current())
420
+ schedule();
421
+ };
422
+ this.autoRefreshLoops.set(indexName, loop);
423
+ schedule();
424
+ }
425
+ stopAutoRefresh(indexName) {
426
+ const loop = this.autoRefreshLoops.get(indexName);
427
+ if (!loop)
428
+ return;
429
+ clearTimeout(loop.timer);
430
+ this.autoRefreshLoops.delete(indexName);
431
+ }
321
432
  dispose() {
433
+ for (const indexName of Array.from(this.autoRefreshLoops.keys())) {
434
+ this.stopAutoRefresh(indexName);
435
+ }
322
436
  this.modelArtifacts.clearAll();
323
437
  this.embedder?.dispose();
324
438
  this.indexManager?.free();
@@ -5,6 +5,41 @@ export declare const DEFAULT_MODEL_ARTIFACT_ORIGIN = "https://models.moss.link";
5
5
  export interface SealedModelRuntime {
6
6
  newKeyExchange(): ModelKeyExchange;
7
7
  openSealedModel(bytes: Uint8Array, keys: ModelContentKeys, sku: string): SealedModel;
8
+ /**
9
+ * Opens bytes whose raw SHA-256 already matched the release entry, without
10
+ * hashing them again. Absent on @moss-dev/moss-wasm releases that predate it.
11
+ */
12
+ openMatchedSealedModel?(bytes: Uint8Array, keys: ModelContentKeys, sku: string): SealedModel;
13
+ /**
14
+ * Lets Web Crypto decrypt the model instead of wasm. Absent on
15
+ * @moss-dev/moss-wasm releases that predate the exports it needs.
16
+ */
17
+ webCrypto?: WebCryptoSealedModelRuntime;
18
+ }
19
+ /** What Web Crypto needs to decrypt the payload of a sealed model. */
20
+ export interface SealedModelDecryptParams {
21
+ iv: Uint8Array;
22
+ tag: Uint8Array;
23
+ additionalData: Uint8Array;
24
+ payloadOffset: number;
25
+ payloadLength: number;
26
+ }
27
+ /** Where the tokenizer and graph lie in a decrypted sealed model payload. */
28
+ export interface SealedModelSections {
29
+ tokenizerOffset: number;
30
+ tokenizerLength: number;
31
+ graphOffset: number;
32
+ graphLength: number;
33
+ }
34
+ /**
35
+ * The runtime exports that check a sealed model on each side of a Web Crypto
36
+ * decrypt. The content keys import themselves through `importWebCryptoKey`,
37
+ * so the raw key crosses only into `importKey`, from a buffer zeroed right after.
38
+ */
39
+ export interface WebCryptoSealedModelRuntime {
40
+ sealedModelDecryptParams(bytes: Uint8Array, keys: ModelContentKeys, sku: string): SealedModelDecryptParams;
41
+ sealedModelSections(plaintext: Uint8Array, sku: string): SealedModelSections;
42
+ sealedModelTokenizer(tokenizerJson: Uint8Array): Tokenizer;
8
43
  }
9
44
  export interface ModelDeliveryAuth {
10
45
  getAuthHeader(): Promise<string>;
@@ -49,6 +84,8 @@ export declare class ModelDeliveryError extends Error {
49
84
  interface ArtifactOrigin {
50
85
  protocol: string;
51
86
  host: string;
87
+ hostname: string;
88
+ port: string;
52
89
  }
53
90
  interface ReleaseFile {
54
91
  relativePath: string;
@@ -46,7 +46,12 @@ export function parseArtifactOrigin(value) {
46
46
  if (url.pathname !== "/" || url.search || url.hash || url.username || url.password) {
47
47
  throw new ModelDeliveryError("Model artifact origin must be scheme://host[:port] only");
48
48
  }
49
- return { protocol: url.protocol, host: url.host.toLowerCase() };
49
+ return {
50
+ protocol: url.protocol,
51
+ host: url.host.toLowerCase(),
52
+ hostname: url.hostname.toLowerCase(),
53
+ port: url.port,
54
+ };
50
55
  }
51
56
  function validateGrantedUrl(url, origin, sku, version, object) {
52
57
  let parsed;
@@ -57,15 +62,22 @@ function validateGrantedUrl(url, origin, sku, version, object) {
57
62
  throw new ModelDeliveryError(`${object} url is not valid: ${String(error)}`);
58
63
  }
59
64
  const expectedPath = `${ARTIFACTS_PREFIX}/${sku}/${version}/${object}`;
60
- if (parsed.protocol !== origin.protocol
61
- || parsed.host.toLowerCase() !== origin.host
62
- || parsed.pathname !== expectedPath
63
- || parsed.search
64
- || parsed.hash
65
- || parsed.username
66
- || parsed.password) {
67
- throw new ModelDeliveryError(`${object} url on ${parsed.host} is outside ${origin.protocol}//${origin.host}${expectedPath}`);
68
- }
65
+ let mismatch;
66
+ if (parsed.protocol !== origin.protocol)
67
+ mismatch = "scheme";
68
+ else if (parsed.hostname.toLowerCase() !== origin.hostname)
69
+ mismatch = "host";
70
+ else if (parsed.port !== origin.port)
71
+ mismatch = "port";
72
+ else if (parsed.pathname !== expectedPath)
73
+ mismatch = "path";
74
+ else if (parsed.search || parsed.hash)
75
+ mismatch = "query or fragment";
76
+ else if (parsed.username || parsed.password)
77
+ mismatch = "userinfo";
78
+ else
79
+ return;
80
+ throw new ModelDeliveryError(`${object} url ${mismatch} does not match the artifact location on ${origin.hostname}`);
69
81
  }
70
82
  function grantedObject(value, name) {
71
83
  if (!value || typeof value !== "object") {
@@ -205,6 +217,7 @@ export async function fetchGrantedBytes(fetchFn, object, transfer) {
205
217
  }
206
218
  async function fetchGrantedBytesOnce(fetchFn, object, transfer) {
207
219
  const timeoutMs = transfer.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
220
+ const artifact = artifactLabel(object.url);
208
221
  const controller = new AbortController();
209
222
  const network = async (step, failure) => {
210
223
  const timer = setTimeout(() => controller.abort(), timeoutMs);
@@ -213,7 +226,7 @@ async function fetchGrantedBytesOnce(fetchFn, object, transfer) {
213
226
  }
214
227
  catch (error) {
215
228
  throw new ArtifactTransferError(controller.signal.aborted
216
- ? `Fetching '${object.url}' stalled: nothing arrived for ${timeoutMs} ms`
229
+ ? `Fetching ${artifact} stalled: nothing arrived for ${timeoutMs} ms`
217
230
  : `${failure}: ${String(error)}`);
218
231
  }
219
232
  finally {
@@ -225,24 +238,24 @@ async function fetchGrantedBytesOnce(fetchFn, object, transfer) {
225
238
  headers: { Authorization: `Bearer ${object.capability}` },
226
239
  credentials: "omit",
227
240
  signal: controller.signal,
228
- }), `Failed to fetch '${object.url}'`);
241
+ }), `Failed to fetch ${artifact}`);
229
242
  if (!response.ok) {
230
243
  response.body?.cancel().catch(() => undefined);
231
- const message = `Failed to fetch '${object.url}': ${response.status}`;
244
+ const message = `Failed to fetch ${artifact}: ${response.status}`;
232
245
  const transient = response.status >= 500 || response.status === 408 || response.status === 429;
233
246
  throw transient
234
247
  ? new ArtifactTransferError(message, response.status)
235
248
  : new ModelDeliveryError(message, response.status);
236
249
  }
237
- return await readArtifactBody(response, object.url, transfer, network);
250
+ return await readArtifactBody(response, artifact, transfer, network);
238
251
  }
239
- async function readArtifactBody(response, url, transfer, network) {
252
+ async function readArtifactBody(response, artifact, transfer, network) {
240
253
  const target = transfer.preallocate ? new Uint8Array(transfer.maxBytes) : null;
241
254
  const chunks = [];
242
255
  let loaded = 0;
243
256
  const finish = () => {
244
257
  if (target && loaded < transfer.maxBytes) {
245
- throw new ArtifactTransferError(`'${url}' has an unexpected size: the transfer ended after ${loaded} of ${transfer.maxBytes} bytes`);
258
+ throw new ArtifactTransferError(`${artifact} has an unexpected size: the transfer ended after ${loaded} of ${transfer.maxBytes} bytes`);
246
259
  }
247
260
  return target ?? joinChunks(chunks, loaded);
248
261
  };
@@ -251,12 +264,12 @@ async function readArtifactBody(response, url, transfer, network) {
251
264
  const reader = response.body.getReader();
252
265
  try {
253
266
  for (;;) {
254
- const next = await network(() => reader.read(), `Transfer of '${url}' failed`);
267
+ const next = await network(() => reader.read(), `Transfer of ${artifact} failed`);
255
268
  if (next.done)
256
269
  break;
257
270
  const chunk = next.value;
258
271
  if (loaded + chunk.byteLength > transfer.maxBytes) {
259
- throw new ModelDeliveryError(`'${url}' exceeds ${transfer.maxBytes} bytes`);
272
+ throw new ModelDeliveryError(`${artifact} exceeds ${transfer.maxBytes} bytes`);
260
273
  }
261
274
  if (target)
262
275
  target.set(chunk, loaded);
@@ -272,6 +285,17 @@ async function readArtifactBody(response, url, transfer, network) {
272
285
  }
273
286
  return finish();
274
287
  }
288
+ /** The file name and host of a granted artifact URL, the only parts of it kept in error text. */
289
+ function artifactLabel(url) {
290
+ try {
291
+ const parsed = new URL(url);
292
+ const file = parsed.pathname.slice(parsed.pathname.lastIndexOf("/") + 1);
293
+ return `'${file}' from ${parsed.host}`;
294
+ }
295
+ catch {
296
+ return "the model artifact";
297
+ }
298
+ }
275
299
  function joinChunks(chunks, length) {
276
300
  if (chunks.length === 1)
277
301
  return chunks[0];
@@ -463,23 +487,81 @@ export async function loadSealedModel(options, stamped) {
463
487
  });
464
488
  const record = await verifyReleaseManifest(releaseBytes, grant);
465
489
  const model = await loadModelFile(options, fetchFn, cache, grant, record);
466
- const sealed = options.runtime.openSealedModel(model.bytes, keys, sku);
467
- let bundle;
468
- try {
469
- const graph = sealed.takeGraph();
470
- const tokenizer = sealed.takeTokenizer();
471
- bundle = { grant, graph, tokenizer };
472
- }
473
- finally {
474
- sealed.free();
475
- }
490
+ const opened = await openWithWebCrypto(options.runtime, model.bytes, keys, sku)
491
+ ?? openInWasm(options.runtime, model.bytes, keys, sku);
476
492
  model.persist?.();
477
- return bundle;
493
+ return { grant, ...opened };
478
494
  }
479
495
  finally {
480
496
  keys.free();
481
497
  }
482
498
  }
499
+ /** The message the wasm runtime gives when the AES-GCM tag does not match. */
500
+ const DECRYPT_FAILED = "mossml payload decryption failed";
501
+ /**
502
+ * Opens a sealed model with the AES-GCM of Web Crypto, which runs in native code.
503
+ *
504
+ * Returns null, and the wasm runtime opens the model, when the runtime, the keys
505
+ * or the context lack what this path needs, or when Web Crypto cannot import the
506
+ * key or run the decrypt. A tag that does not match fails the load, as in wasm.
507
+ * The graph is a view of the plaintext, and every byte before it is zeroed first.
508
+ */
509
+ async function openWithWebCrypto(runtime, bytes, keys, sku) {
510
+ const webCrypto = runtime.webCrypto;
511
+ const subtle = globalThis.crypto?.subtle;
512
+ const contentKeys = keys;
513
+ if (!webCrypto || !subtle || typeof contentKeys.importWebCryptoKey !== "function") {
514
+ return null;
515
+ }
516
+ const params = webCrypto.sealedModelDecryptParams(bytes, keys, sku);
517
+ const importing = contentKeys.importWebCryptoKey().catch(() => null);
518
+ const { payloadOffset, payloadLength, tag } = params;
519
+ const sealed = new Uint8Array(payloadLength + tag.byteLength);
520
+ sealed.set(bytes.subarray(payloadOffset, payloadOffset + payloadLength));
521
+ sealed.set(tag, payloadLength);
522
+ const key = await importing;
523
+ if (!key)
524
+ return null;
525
+ let plaintext;
526
+ try {
527
+ plaintext = new Uint8Array(await subtle.decrypt({
528
+ name: "AES-GCM",
529
+ iv: params.iv,
530
+ additionalData: params.additionalData,
531
+ tagLength: 128,
532
+ }, key, sealed));
533
+ }
534
+ catch (error) {
535
+ if (error?.name === "OperationError") {
536
+ throw new ModelDeliveryError(DECRYPT_FAILED);
537
+ }
538
+ return null;
539
+ }
540
+ try {
541
+ const sections = webCrypto.sealedModelSections(plaintext, sku);
542
+ const { tokenizerOffset, tokenizerLength, graphOffset, graphLength } = sections;
543
+ const tokenizer = webCrypto.sealedModelTokenizer(plaintext.subarray(tokenizerOffset, tokenizerOffset + tokenizerLength));
544
+ plaintext.fill(0, 0, graphOffset);
545
+ return { graph: plaintext.subarray(graphOffset, graphOffset + graphLength), tokenizer };
546
+ }
547
+ catch (error) {
548
+ plaintext.fill(0);
549
+ throw error;
550
+ }
551
+ }
552
+ function openInWasm(runtime, bytes, keys, sku) {
553
+ const sealed = runtime.openMatchedSealedModel
554
+ ? runtime.openMatchedSealedModel(bytes, keys, sku)
555
+ : runtime.openSealedModel(bytes, keys, sku);
556
+ try {
557
+ const graph = sealed.takeGraph();
558
+ const tokenizer = sealed.takeTokenizer();
559
+ return { graph, tokenizer };
560
+ }
561
+ finally {
562
+ sealed.free();
563
+ }
564
+ }
483
565
  async function loadModelFile(options, fetchFn, cache, grant, record) {
484
566
  const report = (loadedBytes, fromCache) => {
485
567
  try {
package/dist/types.d.ts CHANGED
@@ -76,6 +76,13 @@ export interface QueryOptions {
76
76
  */
77
77
  candidateDepth?: number;
78
78
  }
79
+ /**
80
+ * A metadata filter: one field condition, or an `$and` / `$or` of filters.
81
+ *
82
+ * A field condition never matches a document that lacks the field, whatever
83
+ * its operator, `$ne` and `$nin` included. A misspelled field name therefore
84
+ * matches nothing rather than raising an error.
85
+ */
79
86
  export type MetadataFilter = {
80
87
  field: string;
81
88
  condition: FilterCondition;
@@ -84,6 +91,15 @@ export type MetadataFilter = {
84
91
  } | {
85
92
  $or: MetadataFilter[];
86
93
  };
94
+ /**
95
+ * A condition on one metadata field. Metadata values are strings.
96
+ *
97
+ * `$gt`, `$gte`, `$lt` and `$lte` compare two plain decimals (`"42"`, `"-3.5"`)
98
+ * as numbers and two other values character by character as text. They never
99
+ * match a plain decimal against any other value, such as `"007"`, `"1e3"` or `"NaN"`.
100
+ * `$near` takes `"lat,lng,maxDistanceMeters"`, such as `"40.7580,-73.9855,5000"`, and
101
+ * matches a `"lat,lng"` field value. Any other `$near` value makes the query fail.
102
+ */
87
103
  export type FilterCondition = {
88
104
  $eq: string | number;
89
105
  } | {
@@ -101,12 +117,13 @@ export type FilterCondition = {
101
117
  } | {
102
118
  $nin: (string | number)[];
103
119
  } | {
104
- $near: string | number;
120
+ $near: string;
105
121
  };
106
122
  export interface RefreshResult {
107
123
  indexName: string;
108
124
  previousUpdatedAt: string;
109
125
  newUpdatedAt: string;
126
+ /** False when the cloud snapshot was no newer than the loaded one and nothing was downloaded. */
110
127
  wasUpdated: boolean;
111
128
  modelId?: string;
112
129
  modelArtifactVersion?: string;
@@ -125,14 +142,22 @@ export interface MutationResult {
125
142
  }
126
143
  export interface CreateIndexOptions {
127
144
  modelId?: MossModel | "custom";
145
+ /**
146
+ * Called with each job status the client polls until the build finishes.
147
+ * An exception it throws, or a rejection of a promise it returns, is ignored.
148
+ */
128
149
  onProgress?: (progress: JobProgress) => void;
129
150
  }
130
151
  export interface MutationOptions {
131
152
  /**
132
153
  * 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.
154
+ * `addDocs` sends it only when set, `deleteDocs` ignores it, and the cloud service decides how to apply it.
134
155
  */
135
156
  upsert?: boolean;
157
+ /**
158
+ * Called with each job status the client polls until the job finishes.
159
+ * An exception it throws, or a rejection of a promise it returns, is ignored.
160
+ */
136
161
  onProgress?: (progress: JobProgress) => void;
137
162
  }
138
163
  export interface ParseFileInput {
@@ -162,12 +187,23 @@ export interface GetDocumentsOptions {
162
187
  docIds?: string[];
163
188
  }
164
189
  export interface LoadIndexOptions {
190
+ /**
191
+ * Refresh the index from the cloud on a timer until it is unloaded.
192
+ * Off, with one warning, on a `@moss-dev/moss-wasm` that downloads the whole index on every refresh.
193
+ */
165
194
  autoRefresh?: boolean;
195
+ /**
196
+ * Seconds between auto refreshes, 600 when unset or 0.
197
+ * A negative or non-finite value is rejected. Other values below 1 use 1,
198
+ * and values above 2147483 (the longest browser timer, about 24 days) use 2147483.
199
+ */
166
200
  pollingIntervalInSeconds?: number;
167
201
  }
168
202
  /** Outcome of a bulk load. Indexes that succeed are kept even if others fail. */
169
203
  export interface LoadIndexesResult {
170
204
  loaded: string[];
171
205
  failed: Record<string, string>;
206
+ /** Stable error code per failed index, such as `NOT_FOUND` or `NETWORK`, when the failure carries one. */
207
+ failedCodes?: Record<string, string>;
172
208
  }
173
209
  export type ISODate = string;
@@ -1,4 +1,5 @@
1
- import type { MetadataFilter, ModelArtifactIdentity, QueryOptions, SearchResult } from "./types.js";
1
+ import type { SealedModelRuntime, WebCryptoSealedModelRuntime } from "./model-delivery.js";
2
+ import type { JobProgress, MetadataFilter, ModelArtifactIdentity, QueryOptions, SearchResult } from "./types.js";
2
3
  /** Optional settings the runtime query methods take after `filter`. */
3
4
  export interface RuntimeQueryTuning {
4
5
  candidateDepth?: number;
@@ -18,3 +19,26 @@ export declare function multiIndexIndexManager(manager: unknown): MultiIndexInde
18
19
  export declare function requireMultiIndexIndexManager(manager: unknown): MultiIndexIndexManager;
19
20
  export declare function exactModelArtifactIdentity(modelId: string, version?: string, manifestSha256?: string): ModelArtifactIdentity | null;
20
21
  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>;
22
+ /**
23
+ * The runtime's `openMatchedSealedModel`, or undefined when the installed
24
+ * @moss-dev/moss-wasm predates it and every open recomputes the envelope digest.
25
+ */
26
+ export declare function matchedSealedModelOpener(runtime: unknown): SealedModelRuntime["openMatchedSealedModel"];
27
+ /**
28
+ * The runtime exports that let Web Crypto decrypt a sealed model, or undefined
29
+ * when the installed @moss-dev/moss-wasm predates any of them and wasm decrypts it.
30
+ */
31
+ export declare function webCryptoSealedModelRuntime(runtime: unknown): WebCryptoSealedModelRuntime | undefined;
32
+ /**
33
+ * Whether `manager.refreshIndex` skips a snapshot no newer than the loaded one.
34
+ * A runtime without this marker downloads and rebuilds the whole index on every refresh.
35
+ */
36
+ export declare function refreshSkipsUnchanged(manager: unknown): boolean;
37
+ /** `ManageClient` job methods that take an `onProgress` callback after their other arguments. */
38
+ export type ProgressReportingMethod = "createIndex" | "createIndexFromFiles" | "addDocs" | "deleteDocs";
39
+ /**
40
+ * Calls a WASM `ManageClient` job method, passing `onProgress` after `args`.
41
+ * A null or undefined `onProgress` passes no callback. An older runtime whose method
42
+ * has no progress parameter would drop the callback silently, so the call throws before the job starts.
43
+ */
44
+ export declare function callWithProgress(manageClient: unknown, method: ProgressReportingMethod, args: unknown[], onProgress: ((progress: JobProgress) => void) | null | undefined): Promise<unknown>;
@@ -73,3 +73,80 @@ export function queryWithResolvedModelIdentity(manager, identity, indexName, que
73
73
  }
74
74
  return manager.query(indexName, query, embedding, topK, alpha, filter, tuning);
75
75
  }
76
+ /**
77
+ * The runtime's `openMatchedSealedModel`, or undefined when the installed
78
+ * @moss-dev/moss-wasm predates it and every open recomputes the envelope digest.
79
+ */
80
+ export function matchedSealedModelOpener(runtime) {
81
+ const open = runtime?.openMatchedSealedModel;
82
+ return typeof open === "function"
83
+ ? open
84
+ : undefined;
85
+ }
86
+ const WEB_CRYPTO_SEALED_MODEL_EXPORTS = [
87
+ "sealedModelDecryptParams",
88
+ "sealedModelSections",
89
+ "sealedModelTokenizer",
90
+ ];
91
+ /**
92
+ * The runtime exports that let Web Crypto decrypt a sealed model, or undefined
93
+ * when the installed @moss-dev/moss-wasm predates any of them and wasm decrypts it.
94
+ */
95
+ export function webCryptoSealedModelRuntime(runtime) {
96
+ if (typeof runtime !== "object" || runtime === null)
97
+ return undefined;
98
+ const candidate = runtime;
99
+ for (const name of WEB_CRYPTO_SEALED_MODEL_EXPORTS) {
100
+ if (typeof candidate[name] !== "function")
101
+ return undefined;
102
+ }
103
+ const exports = runtime;
104
+ return {
105
+ sealedModelDecryptParams: exports.sealedModelDecryptParams,
106
+ sealedModelSections: exports.sealedModelSections,
107
+ sealedModelTokenizer: exports.sealedModelTokenizer,
108
+ };
109
+ }
110
+ /**
111
+ * Whether `manager.refreshIndex` skips a snapshot no newer than the loaded one.
112
+ * A runtime without this marker downloads and rebuilds the whole index on every refresh.
113
+ */
114
+ export function refreshSkipsUnchanged(manager) {
115
+ const marker = typeof manager === "object" && manager !== null
116
+ ? manager.refreshSkipsUnchanged
117
+ : undefined;
118
+ return typeof marker === "function" && marker.call(manager) === true;
119
+ }
120
+ /**
121
+ * Calls a WASM `ManageClient` job method, passing `onProgress` after `args`.
122
+ * A null or undefined `onProgress` passes no callback. An older runtime whose method
123
+ * has no progress parameter would drop the callback silently, so the call throws before the job starts.
124
+ */
125
+ export function callWithProgress(manageClient, method, args, onProgress) {
126
+ const fn = typeof manageClient === "object" && manageClient !== null
127
+ ? manageClient[method]
128
+ : undefined;
129
+ if (typeof fn !== "function") {
130
+ throw new Error(`The installed @moss-dev/moss-wasm runtime has no ManageClient.${method}`);
131
+ }
132
+ if (onProgress == null) {
133
+ return fn.apply(manageClient, args);
134
+ }
135
+ if (typeof onProgress !== "function") {
136
+ throw new TypeError("onProgress must be a function");
137
+ }
138
+ if (fn.length <= args.length) {
139
+ throw new Error("The installed @moss-dev/moss-wasm cannot report job progress (onProgress). Upgrade @moss-dev/moss-wasm or omit onProgress.");
140
+ }
141
+ return fn.apply(manageClient, [...args, ignoreRejection(onProgress)]);
142
+ }
143
+ /** Wraps a progress callback so a promise it returns cannot reject unhandled. */
144
+ function ignoreRejection(onProgress) {
145
+ return (progress) => {
146
+ const returned = onProgress(progress);
147
+ if (typeof returned === "object" && returned !== null
148
+ && typeof returned.then === "function") {
149
+ returned.then(undefined, () => { });
150
+ }
151
+ };
152
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moss-dev/moss-web",
3
- "version": "1.3.0",
3
+ "version": "1.4.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.16.0",
28
+ "@moss-dev/moss-wasm": "0.17.0",
29
29
  "onnxruntime-web": "^1.27.0"
30
30
  },
31
31
  "devDependencies": {