@moss-dev/moss-web 1.3.0 → 1.5.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 +52 -6
- package/dist/client.d.ts +21 -3
- package/dist/client.js +125 -11
- package/dist/embedder.js +4 -1
- package/dist/model-delivery.d.ts +39 -1
- package/dist/model-delivery.js +114 -31
- package/dist/types.d.ts +38 -2
- package/dist/wasm-runtime-capability.d.ts +25 -1
- package/dist/wasm-runtime-capability.js +77 -0
- package/package.json +9 -3
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ Built on WebAssembly for near-native performance in any modern browser.
|
|
|
10
10
|
- **Semantic & Hybrid Search** — Beyond keyword matching
|
|
11
11
|
- **Multi-Index Support** — Manage multiple isolated search spaces
|
|
12
12
|
- **Full CRUD** — Create, update, and delete indexes and documents from the browser
|
|
13
|
-
- **Privacy-First** — Queries run entirely in the browser
|
|
13
|
+
- **Privacy-First** — Queries run entirely in the browser and never leave the device. Usage telemetry is sent (see [Telemetry](#telemetry))
|
|
14
14
|
|
|
15
15
|
## Installation
|
|
16
16
|
|
|
@@ -18,10 +18,10 @@ 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.
|
|
21
|
+
Version 1.5.0 resolves `@moss-dev/moss-wasm@0.18.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
|
-
fallback.
|
|
24
|
+
fallback. Before 1.2.0 the only published npm versions were 1.0.0 and 1.0.1,
|
|
25
25
|
where `queryWithEmbedding()` remains available for caller-supplied embeddings.
|
|
26
26
|
|
|
27
27
|
## Quick Start
|
|
@@ -169,9 +169,45 @@ await client.unloadIndex(name);
|
|
|
169
169
|
await client.unloadIndexes(names);
|
|
170
170
|
```
|
|
171
171
|
|
|
172
|
-
`
|
|
173
|
-
|
|
174
|
-
|
|
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,16 @@ error.
|
|
|
208
244
|
client.dispose();
|
|
209
245
|
```
|
|
210
246
|
|
|
247
|
+
## Telemetry
|
|
248
|
+
|
|
249
|
+
The browser SDK always sends usage telemetry to the Moss cloud, and there is no
|
|
250
|
+
option to turn it off. It sends your project id, a random id per client, SDK
|
|
251
|
+
versions, query counts and a device id, which is a random UUID stored in
|
|
252
|
+
`localStorage` under `moss-device-id`. Telemetry never includes index names,
|
|
253
|
+
query text, document text, metadata or embeddings.
|
|
254
|
+
|
|
255
|
+
See [Telemetry](https://docs.moss.dev/docs/reference/telemetry) for every field and when it is sent.
|
|
256
|
+
|
|
211
257
|
## License
|
|
212
258
|
|
|
213
259
|
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
|
-
|
|
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
|
|
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;
|
|
@@ -74,7 +98,7 @@ export class MossClient {
|
|
|
74
98
|
this.projectKeyAuthenticator = projectKeyAuth;
|
|
75
99
|
deliveryAuth = {
|
|
76
100
|
getAuthHeader: () => projectKeyAuth.getAuthHeader(),
|
|
77
|
-
invalidate: () => projectKeyAuth.invalidate(),
|
|
101
|
+
invalidate: (rejected) => projectKeyAuth.invalidate(rejected),
|
|
78
102
|
};
|
|
79
103
|
if (this.options.baseUrl) {
|
|
80
104
|
this.indexManager = IndexManager.withBaseUrl(this.projectId, this.projectKey, this.options.baseUrl);
|
|
@@ -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: {
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
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();
|
package/dist/embedder.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
// Outside Node, #ort is onnxruntime-web/wasm, which loads the plain wasm build.
|
|
2
|
+
// The default entry adds WebGPU and a jsep wasm about twice the size, unused here.
|
|
3
|
+
// Under Node, #ort is the default entry, whose node build reads the wasm from disk.
|
|
4
|
+
import * as ort from "#ort";
|
|
2
5
|
import { modelHiddenDim } from "./model-config.js";
|
|
3
6
|
import { loadSealedModel } from "./model-delivery.js";
|
|
4
7
|
export class Embedder {
|
package/dist/model-delivery.d.ts
CHANGED
|
@@ -5,10 +5,46 @@ 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>;
|
|
11
|
-
|
|
46
|
+
/** Called with the header a 401 refused, before the retry asks for a header again. */
|
|
47
|
+
invalidate(rejected: string): Promise<void> | void;
|
|
12
48
|
}
|
|
13
49
|
export interface ModelDeliveryOptions {
|
|
14
50
|
projectId: string;
|
|
@@ -49,6 +85,8 @@ export declare class ModelDeliveryError extends Error {
|
|
|
49
85
|
interface ArtifactOrigin {
|
|
50
86
|
protocol: string;
|
|
51
87
|
host: string;
|
|
88
|
+
hostname: string;
|
|
89
|
+
port: string;
|
|
52
90
|
}
|
|
53
91
|
interface ReleaseFile {
|
|
54
92
|
relativePath: string;
|
package/dist/model-delivery.js
CHANGED
|
@@ -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 {
|
|
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
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
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") {
|
|
@@ -154,10 +166,11 @@ export async function requestModelDeliveryGrant(options, sku, capabilityQuery) {
|
|
|
154
166
|
let response;
|
|
155
167
|
let body;
|
|
156
168
|
try {
|
|
157
|
-
|
|
169
|
+
const header = await options.auth.getAuthHeader();
|
|
170
|
+
response = await send(header);
|
|
158
171
|
if (response.status === 401) {
|
|
159
172
|
response.body?.cancel().catch(() => undefined);
|
|
160
|
-
await options.auth.invalidate();
|
|
173
|
+
await options.auth.invalidate(header);
|
|
161
174
|
response = await send(await options.auth.getAuthHeader());
|
|
162
175
|
}
|
|
163
176
|
body = response.ok
|
|
@@ -205,6 +218,7 @@ export async function fetchGrantedBytes(fetchFn, object, transfer) {
|
|
|
205
218
|
}
|
|
206
219
|
async function fetchGrantedBytesOnce(fetchFn, object, transfer) {
|
|
207
220
|
const timeoutMs = transfer.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
221
|
+
const artifact = artifactLabel(object.url);
|
|
208
222
|
const controller = new AbortController();
|
|
209
223
|
const network = async (step, failure) => {
|
|
210
224
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
@@ -213,7 +227,7 @@ async function fetchGrantedBytesOnce(fetchFn, object, transfer) {
|
|
|
213
227
|
}
|
|
214
228
|
catch (error) {
|
|
215
229
|
throw new ArtifactTransferError(controller.signal.aborted
|
|
216
|
-
? `Fetching
|
|
230
|
+
? `Fetching ${artifact} stalled: nothing arrived for ${timeoutMs} ms`
|
|
217
231
|
: `${failure}: ${String(error)}`);
|
|
218
232
|
}
|
|
219
233
|
finally {
|
|
@@ -225,24 +239,24 @@ async function fetchGrantedBytesOnce(fetchFn, object, transfer) {
|
|
|
225
239
|
headers: { Authorization: `Bearer ${object.capability}` },
|
|
226
240
|
credentials: "omit",
|
|
227
241
|
signal: controller.signal,
|
|
228
|
-
}), `Failed to fetch
|
|
242
|
+
}), `Failed to fetch ${artifact}`);
|
|
229
243
|
if (!response.ok) {
|
|
230
244
|
response.body?.cancel().catch(() => undefined);
|
|
231
|
-
const message = `Failed to fetch
|
|
245
|
+
const message = `Failed to fetch ${artifact}: ${response.status}`;
|
|
232
246
|
const transient = response.status >= 500 || response.status === 408 || response.status === 429;
|
|
233
247
|
throw transient
|
|
234
248
|
? new ArtifactTransferError(message, response.status)
|
|
235
249
|
: new ModelDeliveryError(message, response.status);
|
|
236
250
|
}
|
|
237
|
-
return await readArtifactBody(response,
|
|
251
|
+
return await readArtifactBody(response, artifact, transfer, network);
|
|
238
252
|
}
|
|
239
|
-
async function readArtifactBody(response,
|
|
253
|
+
async function readArtifactBody(response, artifact, transfer, network) {
|
|
240
254
|
const target = transfer.preallocate ? new Uint8Array(transfer.maxBytes) : null;
|
|
241
255
|
const chunks = [];
|
|
242
256
|
let loaded = 0;
|
|
243
257
|
const finish = () => {
|
|
244
258
|
if (target && loaded < transfer.maxBytes) {
|
|
245
|
-
throw new ArtifactTransferError(
|
|
259
|
+
throw new ArtifactTransferError(`${artifact} has an unexpected size: the transfer ended after ${loaded} of ${transfer.maxBytes} bytes`);
|
|
246
260
|
}
|
|
247
261
|
return target ?? joinChunks(chunks, loaded);
|
|
248
262
|
};
|
|
@@ -251,12 +265,12 @@ async function readArtifactBody(response, url, transfer, network) {
|
|
|
251
265
|
const reader = response.body.getReader();
|
|
252
266
|
try {
|
|
253
267
|
for (;;) {
|
|
254
|
-
const next = await network(() => reader.read(), `Transfer of
|
|
268
|
+
const next = await network(() => reader.read(), `Transfer of ${artifact} failed`);
|
|
255
269
|
if (next.done)
|
|
256
270
|
break;
|
|
257
271
|
const chunk = next.value;
|
|
258
272
|
if (loaded + chunk.byteLength > transfer.maxBytes) {
|
|
259
|
-
throw new ModelDeliveryError(
|
|
273
|
+
throw new ModelDeliveryError(`${artifact} exceeds ${transfer.maxBytes} bytes`);
|
|
260
274
|
}
|
|
261
275
|
if (target)
|
|
262
276
|
target.set(chunk, loaded);
|
|
@@ -272,6 +286,17 @@ async function readArtifactBody(response, url, transfer, network) {
|
|
|
272
286
|
}
|
|
273
287
|
return finish();
|
|
274
288
|
}
|
|
289
|
+
/** The file name and host of a granted artifact URL, the only parts of it kept in error text. */
|
|
290
|
+
function artifactLabel(url) {
|
|
291
|
+
try {
|
|
292
|
+
const parsed = new URL(url);
|
|
293
|
+
const file = parsed.pathname.slice(parsed.pathname.lastIndexOf("/") + 1);
|
|
294
|
+
return `'${file}' from ${parsed.host}`;
|
|
295
|
+
}
|
|
296
|
+
catch {
|
|
297
|
+
return "the model artifact";
|
|
298
|
+
}
|
|
299
|
+
}
|
|
275
300
|
function joinChunks(chunks, length) {
|
|
276
301
|
if (chunks.length === 1)
|
|
277
302
|
return chunks[0];
|
|
@@ -463,23 +488,81 @@ export async function loadSealedModel(options, stamped) {
|
|
|
463
488
|
});
|
|
464
489
|
const record = await verifyReleaseManifest(releaseBytes, grant);
|
|
465
490
|
const model = await loadModelFile(options, fetchFn, cache, grant, record);
|
|
466
|
-
const
|
|
467
|
-
|
|
468
|
-
try {
|
|
469
|
-
const graph = sealed.takeGraph();
|
|
470
|
-
const tokenizer = sealed.takeTokenizer();
|
|
471
|
-
bundle = { grant, graph, tokenizer };
|
|
472
|
-
}
|
|
473
|
-
finally {
|
|
474
|
-
sealed.free();
|
|
475
|
-
}
|
|
491
|
+
const opened = await openWithWebCrypto(options.runtime, model.bytes, keys, sku)
|
|
492
|
+
?? openInWasm(options.runtime, model.bytes, keys, sku);
|
|
476
493
|
model.persist?.();
|
|
477
|
-
return
|
|
494
|
+
return { grant, ...opened };
|
|
478
495
|
}
|
|
479
496
|
finally {
|
|
480
497
|
keys.free();
|
|
481
498
|
}
|
|
482
499
|
}
|
|
500
|
+
/** The message the wasm runtime gives when the AES-GCM tag does not match. */
|
|
501
|
+
const DECRYPT_FAILED = "mossml payload decryption failed";
|
|
502
|
+
/**
|
|
503
|
+
* Opens a sealed model with the AES-GCM of Web Crypto, which runs in native code.
|
|
504
|
+
*
|
|
505
|
+
* Returns null, and the wasm runtime opens the model, when the runtime, the keys
|
|
506
|
+
* or the context lack what this path needs, or when Web Crypto cannot import the
|
|
507
|
+
* key or run the decrypt. A tag that does not match fails the load, as in wasm.
|
|
508
|
+
* The graph is a view of the plaintext, and every byte before it is zeroed first.
|
|
509
|
+
*/
|
|
510
|
+
async function openWithWebCrypto(runtime, bytes, keys, sku) {
|
|
511
|
+
const webCrypto = runtime.webCrypto;
|
|
512
|
+
const subtle = globalThis.crypto?.subtle;
|
|
513
|
+
const contentKeys = keys;
|
|
514
|
+
if (!webCrypto || !subtle || typeof contentKeys.importWebCryptoKey !== "function") {
|
|
515
|
+
return null;
|
|
516
|
+
}
|
|
517
|
+
const params = webCrypto.sealedModelDecryptParams(bytes, keys, sku);
|
|
518
|
+
const importing = contentKeys.importWebCryptoKey().catch(() => null);
|
|
519
|
+
const { payloadOffset, payloadLength, tag } = params;
|
|
520
|
+
const sealed = new Uint8Array(payloadLength + tag.byteLength);
|
|
521
|
+
sealed.set(bytes.subarray(payloadOffset, payloadOffset + payloadLength));
|
|
522
|
+
sealed.set(tag, payloadLength);
|
|
523
|
+
const key = await importing;
|
|
524
|
+
if (!key)
|
|
525
|
+
return null;
|
|
526
|
+
let plaintext;
|
|
527
|
+
try {
|
|
528
|
+
plaintext = new Uint8Array(await subtle.decrypt({
|
|
529
|
+
name: "AES-GCM",
|
|
530
|
+
iv: params.iv,
|
|
531
|
+
additionalData: params.additionalData,
|
|
532
|
+
tagLength: 128,
|
|
533
|
+
}, key, sealed));
|
|
534
|
+
}
|
|
535
|
+
catch (error) {
|
|
536
|
+
if (error?.name === "OperationError") {
|
|
537
|
+
throw new ModelDeliveryError(DECRYPT_FAILED);
|
|
538
|
+
}
|
|
539
|
+
return null;
|
|
540
|
+
}
|
|
541
|
+
try {
|
|
542
|
+
const sections = webCrypto.sealedModelSections(plaintext, sku);
|
|
543
|
+
const { tokenizerOffset, tokenizerLength, graphOffset, graphLength } = sections;
|
|
544
|
+
const tokenizer = webCrypto.sealedModelTokenizer(plaintext.subarray(tokenizerOffset, tokenizerOffset + tokenizerLength));
|
|
545
|
+
plaintext.fill(0, 0, graphOffset);
|
|
546
|
+
return { graph: plaintext.subarray(graphOffset, graphOffset + graphLength), tokenizer };
|
|
547
|
+
}
|
|
548
|
+
catch (error) {
|
|
549
|
+
plaintext.fill(0);
|
|
550
|
+
throw error;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
function openInWasm(runtime, bytes, keys, sku) {
|
|
554
|
+
const sealed = runtime.openMatchedSealedModel
|
|
555
|
+
? runtime.openMatchedSealedModel(bytes, keys, sku)
|
|
556
|
+
: runtime.openSealedModel(bytes, keys, sku);
|
|
557
|
+
try {
|
|
558
|
+
const graph = sealed.takeGraph();
|
|
559
|
+
const tokenizer = sealed.takeTokenizer();
|
|
560
|
+
return { graph, tokenizer };
|
|
561
|
+
}
|
|
562
|
+
finally {
|
|
563
|
+
sealed.free();
|
|
564
|
+
}
|
|
565
|
+
}
|
|
483
566
|
async function loadModelFile(options, fetchFn, cache, grant, record) {
|
|
484
567
|
const report = (loadedBytes, fromCache) => {
|
|
485
568
|
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
|
|
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 {
|
|
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
|
+
"version": "1.5.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Moss browser SDK — in-browser semantic search powered by WASM",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -12,6 +12,12 @@
|
|
|
12
12
|
"import": "./dist/index.js"
|
|
13
13
|
}
|
|
14
14
|
},
|
|
15
|
+
"imports": {
|
|
16
|
+
"#ort": {
|
|
17
|
+
"node": "onnxruntime-web",
|
|
18
|
+
"default": "onnxruntime-web/wasm"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
15
21
|
"files": [
|
|
16
22
|
"dist",
|
|
17
23
|
"README.md",
|
|
@@ -25,8 +31,8 @@
|
|
|
25
31
|
"test": "npm run build && node --test"
|
|
26
32
|
},
|
|
27
33
|
"dependencies": {
|
|
28
|
-
"@moss-dev/moss-wasm": "0.
|
|
29
|
-
"onnxruntime-web": "
|
|
34
|
+
"@moss-dev/moss-wasm": "0.18.0",
|
|
35
|
+
"onnxruntime-web": "1.30.0"
|
|
30
36
|
},
|
|
31
37
|
"devDependencies": {
|
|
32
38
|
"typescript": "^6.0.3",
|