tempest-react-sdk 0.32.0 → 0.33.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/dist/tabular.d.ts CHANGED
@@ -21,469 +21,648 @@ export declare function cacheModelBytes(url: string, bytes: Uint8Array, cacheNam
21
21
  export declare function clearModelCache(url?: string, cacheName?: string): Promise<boolean>;
22
22
 
23
23
  /**
24
- * Point ONNX Runtime Web at locally served WebAssembly binaries.
24
+ * The bytes are not a compact model, or use a newer layout.
25
25
  *
26
- * Call once, before creating any predictor.
27
- *
28
- * @example
29
- * ```ts
30
- * configureOrtAssets("/ort/");
31
- * const predictor = await TabularPredictor.create("/models/classifier.onnx");
32
- * ```
33
- *
34
- * @param basePath Directory the binaries are served from, with a trailing
35
- * slash. Copy them there at build time — for Vite, from
36
- * `node_modules/onnxruntime-web/dist/`.
37
- */
38
- export declare function configureOrtAssets(basePath: string): void;
39
-
40
- /** Cache Storage bucket used when the caller does not name one. */
41
- export declare const DEFAULT_MODEL_CACHE = "tempest-tabular-models";
42
-
43
- /**
44
- * Execution providers used when the caller does not choose.
45
- *
46
- * WebAssembly only, and deliberately: scikit-learn graphs are `ai.onnx.ml`
47
- * operators, which the WebGPU backend does not implement. There is no
48
- * speed left on the table here — a 10-tree forest predicts a row in about
49
- * 0.05 ms in Chromium.
26
+ * Separate from {@link ModelLoadError} because the fix is different: a
27
+ * `.onnx` file handed to the compact reader is a wiring mistake, not a
28
+ * broken model.
50
29
  */
51
- export declare const DEFAULT_TABULAR_PROVIDERS: readonly string[];
52
-
53
- /** The package manifest, as written by `edge_pipeline`. */
54
- export declare interface EdgeManifest {
55
- readonly schema_version: number;
56
- readonly name: string;
57
- readonly version: string;
58
- readonly created_at: string;
59
- readonly sdk_version: string;
60
- readonly estimator: string;
61
- readonly model: ManifestModelFile;
62
- readonly input: ManifestInput;
63
- readonly output: ManifestOutput;
64
- readonly verified: boolean | null;
65
- readonly baseline_file: string | null;
66
- readonly baseline_samples: number;
67
- }
68
-
69
- /** One row of feature values, in the column order the model was trained on. */
70
- export declare type FeatureRow = readonly number[];
71
-
72
- /** The rows do not match what the model expects. */
73
- export declare class FeatureShapeError extends TabularError {
30
+ export declare class CompactFormatError extends TabularError {
74
31
  constructor(message: string, options?: ErrorOptions);
75
32
  }
76
33
 
34
+ /** What the file holds. */
35
+ export declare type CompactKind = "linear" | "tree_ensemble";
36
+
77
37
  /**
78
- * Read a package's manifest.
79
- *
80
- * Cheap: it is a few hundred bytes, so an app can check for a new version
81
- * without downloading a model it may already have.
38
+ * A compact model, loaded and ready to answer.
82
39
  *
83
40
  * @example
84
41
  * ```ts
85
- * const manifest = await fetchEdgeManifest("/models/risk/");
86
- * if (manifest.version !== localStorage.getItem("risk-version")) {
87
- * // a new model was published
88
- * }
42
+ * const predictor = await CompactPredictor.create("/models/risk.tmc");
43
+ * const { labels, probabilities } = await predictor.predict([[5.1, 3.5, 1.4, 0.2]]);
89
44
  * ```
90
- *
91
- * @param directoryUrl URL of the package directory, with or without a
92
- * trailing slash. A full URL to the manifest file also works.
93
- * @param requestInit `fetch` options.
94
- * @returns The parsed manifest.
95
- * @throws {@link ModelFetchError} when the manifest cannot be read, or when
96
- * its `schema_version` is newer than this reader understands — loading it
97
- * anyway would risk misreading the field that defines column order.
98
- */
99
- export declare function fetchEdgeManifest(directoryUrl: string, requestInit?: RequestInit): Promise<EdgeManifest>;
100
-
101
- /**
102
- * Fetch the model bytes, preferring the on-device copy.
103
- *
104
- * @example
105
- * ```ts
106
- * const bytes = await fetchModelBytes("/models/classifier-v3.onnx");
107
- * const predictor = await TabularPredictor.create(bytes);
108
- * ```
109
- *
110
- * @param url Where the model lives.
111
- * @param options Cache bucket, revalidation and `fetch` options.
112
- * @returns The model bytes.
113
- * @throws {@link ModelFetchError} when the model is neither cached nor
114
- * reachable — which is the "offline and never warmed" case, and the
115
- * message says so.
116
- */
117
- export declare function fetchModelBytes(url: string, options?: ModelCacheOptions): Promise<Uint8Array>;
118
-
119
- /** The session ran but its outputs could not be read. */
120
- export declare class InferenceError extends TabularError {
121
- constructor(message: string, options?: ErrorOptions);
122
- }
123
-
124
- /**
125
- * Whether a model is already on the device.
126
- *
127
- * Useful for showing "available offline" in the UI, and for deciding
128
- * whether to prefetch on a metered connection.
129
- *
130
- * @param url The model URL.
131
- * @param cacheName Cache Storage bucket name.
132
- * @returns `true` when the bytes are cached.
133
- */
134
- export declare function isModelCached(url: string, cacheName?: string): Promise<boolean>;
135
-
136
- /** A package loaded and ready to answer. */
137
- export declare interface LoadedEdgePackage {
138
- /** What was published. */
139
- readonly manifest: EdgeManifest;
140
- /** The running model. */
141
- readonly predictor: TabularPredictor;
142
- /** Column order the rows must follow. */
143
- readonly featureNames: readonly string[];
144
- /** Class names behind each probability column. */
145
- readonly classes: readonly string[];
146
- /**
147
- * Map a prediction's scores onto class names.
148
- *
149
- * @param probabilities One row of scores.
150
- * @returns Name/score pairs, highest first.
151
- */
152
- readonly explain: (probabilities: readonly number[]) => {
153
- name: string;
154
- score: number;
155
- }[];
156
- }
157
-
158
- /**
159
- * Load a whole edge package: manifest, model, and the names to read it by.
160
- *
161
- * @example
162
- * ```ts
163
- * const pkg = await loadEdgePackage("/models/risk/");
164
- *
165
- * console.log(pkg.featureNames); // ["age", "income", "tenure", "score", "visits"]
166
- *
167
- * const { probabilities } = await pkg.predictor.predict([[41, 5200, 3, 0.82, 12]]);
168
- * console.log(pkg.explain(probabilities[0]!)); // [{ name: "approved", score: 0.91 }, ...]
169
- * ```
170
- *
171
- * @param directoryUrl URL of the package directory.
172
- * @param options Predictor options plus caching.
173
- * @returns The loaded package.
174
- * @throws {@link ModelFetchError} when the manifest or model cannot be read.
175
- */
176
- export declare function loadEdgePackage(directoryUrl: string, options?: LoadEdgePackageOptions): Promise<LoadedEdgePackage>;
177
-
178
- /** Options for {@link loadEdgePackage}. */
179
- export declare interface LoadEdgePackageOptions extends TabularPredictorOptions {
180
- /** Cache the model bytes for offline use. `true` by default. */
181
- readonly cache?: boolean | ModelCacheOptions;
182
- }
183
-
184
- /** Fixed filename inside a package directory. */
185
- export declare const MANIFEST_FILENAME = "manifest.json";
186
-
187
- /** What the graph expects per row. */
188
- export declare interface ManifestInput {
189
- readonly name: string;
190
- readonly features: number;
191
- /** Column order used at training time. */
192
- readonly feature_names: readonly string[];
193
- }
194
-
195
- /** The graph file and how to check you got it whole. */
196
- export declare interface ManifestModelFile {
197
- readonly file: string;
198
- readonly sha256: string;
199
- readonly bytes: number;
200
- readonly gzip_file: string | null;
201
- readonly gzip_bytes: number | null;
202
- readonly opset: number;
203
- readonly dtype: string;
204
- }
205
-
206
- /** What the graph answers. */
207
- export declare interface ManifestOutput {
208
- readonly is_classifier: boolean;
209
- readonly label_output: string;
210
- readonly probability_output: string | null;
211
- /** Class labels in score-column order. */
212
- readonly classes: readonly string[];
213
- }
214
-
215
- /** Options for {@link fetchModelBytes}. */
216
- export declare interface ModelCacheOptions {
217
- /** Cache Storage bucket name. */
218
- readonly cacheName?: string;
219
- /**
220
- * Go to the network first and fall back to the cache.
221
- *
222
- * For a URL that serves "whatever is current" rather than a pinned
223
- * version. Costs a round trip on every load when online.
224
- */
225
- readonly revalidate?: boolean;
226
- /** `fetch` options, e.g. credentials for a private model endpoint. */
227
- readonly requestInit?: RequestInit;
228
- }
229
-
230
- /**
231
- * The model bytes could not be fetched or read from the cache.
232
- *
233
- * Distinct from {@link ModelLoadError}: this one means the app is offline
234
- * and nothing was cached, which is a deployment problem, not a model
235
- * problem.
236
- */
237
- export declare class ModelFetchError extends TabularError {
238
- constructor(message: string, options?: ErrorOptions);
239
- }
240
-
241
- /** The model bytes could not be loaded into a session. */
242
- export declare class ModelLoadError extends TabularError {
243
- constructor(message: string, options?: ErrorOptions);
244
- }
245
-
246
- /**
247
- * The WebAssembly binaries ONNX Runtime Web may request.
248
- *
249
- * Which one is fetched depends on the browser's threading and SIMD support,
250
- * so an app that must work everywhere ships all of them. Chromium with the
251
- * default entry point fetched the `jsep` build.
252
- */
253
- export declare const ORT_WASM_ASSETS: readonly string[];
254
-
255
- /**
256
- * The URLs a service worker should precache for offline inference.
257
- *
258
- * The model file is not included: it is cached by
259
- * {@link fetchModelBytes} on first use, under its own bucket.
260
- *
261
- * @example
262
- * ```ts
263
- * installPrecache([...ortAssetUrls("/ort/"), "/index.html"]);
264
- * ```
265
- *
266
- * @param basePath Directory the binaries are served from.
267
- * @returns Absolute-from-root URLs for every runtime asset.
268
- */
269
- export declare function ortAssetUrls(basePath: string): string[];
270
-
271
- /**
272
- * A predicted class label.
273
- *
274
- * scikit-learn classifiers export an int64 label tensor, which ONNX Runtime
275
- * Web surfaces as `bigint`. Those are converted to `number` — a class index
276
- * never approaches `Number.MAX_SAFE_INTEGER`, and leaving `bigint` in the
277
- * result would break `JSON.stringify` and every `=== 1` comparison a caller
278
- * writes. A model trained on string labels keeps them as strings.
279
- */
280
- export declare type PredictedLabel = number | string;
281
-
282
- /** Manifest schema version this reader was written against. */
283
- export declare const SUPPORTED_MANIFEST_SCHEMA = 1;
284
-
285
- /**
286
- * Errors thrown by the tabular inference module.
287
- *
288
- * Each one exists because the underlying failure is unreadable on its own:
289
- * ONNX Runtime reports a missing operator registration, and the actual cause
290
- * is an import path chosen three files away.
291
- *
292
- * Every subclass sets `name` to a **literal** string rather than to
293
- * `new.target.name`. Measured in a real build: the minifier renames the
294
- * class, so the derived form ships as `error.name === "t"` — useless in a
295
- * log and in any consumer that branches on the name.
296
- */
297
- /** Base class for every error this module throws. */
298
- export declare class TabularError extends Error {
299
- constructor(message: string, options?: ErrorOptions);
300
- }
301
-
302
- /**
303
- * Types for browser inference over tabular models exported from scikit-learn.
304
- */
305
- /** Anything `InferenceSession.create` accepts as a model. */
306
- export declare type TabularModelSource = string | ArrayBufferLike | Uint8Array;
307
-
308
- /** One batch of predictions. */
309
- export declare interface TabularPrediction {
310
- /** Predicted class or regressed value per row. */
311
- readonly labels: readonly PredictedLabel[];
312
- /** Class scores per row; empty for a regressor. */
313
- readonly probabilities: readonly (readonly number[])[];
314
- /** Rows predicted. */
315
- readonly numRows: number;
316
- /** Wall-clock inference duration in milliseconds. */
317
- readonly ms: number;
318
- }
319
-
320
- /**
321
- * A loaded tabular model, ready to answer.
322
- *
323
- * @example
324
- * ```ts
325
- * const predictor = await TabularPredictor.create("/models/classifier.onnx");
326
- * const { labels, probabilities } = await predictor.predict([[5.1, 3.5, 1.4, 0.2]]);
327
- * ```
328
- */
329
- export declare class TabularPredictor {
330
- private readonly session;
331
- /** What is loaded and how it is configured. */
332
- readonly info: TabularPredictorInfo;
333
- private constructor();
334
- /**
335
- * Load a model and describe its graph.
336
- *
337
- * @param source A URL string, or the model bytes (which is what an
338
- * offline app passes, having read them from the cache).
339
- * @param options Providers, warm-up and pass-through session options.
340
- * @throws {@link UnsupportedGraphError} when the runtime build lacks the
341
- * `ai.onnx.ml` operators — the WebGPU entry point does.
342
- * @throws {@link ModelLoadError} for any other load failure.
45
+ */
46
+ export declare class CompactPredictor {
47
+ private readonly header;
48
+ private readonly arrays;
49
+ /** What is loaded. */
50
+ readonly info: CompactPredictorInfo;
51
+ private constructor();
52
+ /**
53
+ * Load a `.tmc` file.
54
+ *
55
+ * @param source A URL, or the bytes when the app already has them.
56
+ * @param requestInit `fetch` options, when `source` is a URL.
57
+ * @returns The loaded predictor.
58
+ * @throws {@link ModelFetchError} when a URL cannot be read.
59
+ * @throws {@link CompactFormatError} when the bytes are not a compact
60
+ * model, or use a layout newer than this reader.
61
+ */
62
+ static create(source: string | ArrayBuffer | Uint8Array, requestInit?: RequestInit): Promise<CompactPredictor>;
63
+ /**
64
+ * Predict for a batch of rows.
65
+ *
66
+ * @param rows One array of feature values per row, in training column
67
+ * order. A single row is still wrapped: `[[...]]`.
68
+ * @returns Labels, class scores when the model is a classifier, and the
69
+ * call's duration.
70
+ * @throws {@link FeatureShapeError} when the batch is empty, ragged, or
71
+ * the wrong width.
72
+ */
73
+ predict(rows: readonly FeatureRow[]): Promise<TabularPrediction>;
74
+ /** Releasing nothing, so callers can swap predictors without branching. */
75
+ dispose(): Promise<void>;
76
+ /**
77
+ * Apply the folded scaler, when the export had one.
78
+ *
79
+ * @param row The raw feature values.
80
+ * @param width How many there are.
81
+ * @returns The values the model was trained on.
82
+ */
83
+ private preprocess;
84
+ /**
85
+ * Score one row against the coefficient matrix.
86
+ *
87
+ * @param row The prepared feature values.
88
+ * @returns One raw score per output.
89
+ */
90
+ private linearScores;
91
+ /**
92
+ * Walk every tree and average what the leaves hold.
93
+ *
94
+ * A leaf is marked by a negative `feature` entry, which also carries
95
+ * its slot in the value array — so the walk needs no second lookup and
96
+ * the file stores values only for leaves.
97
+ *
98
+ * @param row The prepared feature values.
99
+ * @returns One averaged score per output.
100
+ */
101
+ private treeScores;
102
+ /**
103
+ * Turn raw scores into labels and probabilities.
104
+ *
105
+ * @param scores One score array per row.
106
+ * @returns Labels and probabilities in the shape the ONNX route uses,
107
+ * so an app can swap runtimes without touching its own code. That
108
+ * includes the label's **type**: an integer class comes back as a
109
+ * number here exactly as ONNX returns it, because two routes over one
110
+ * model that disagree on `0` versus `"0"` break the day someone
111
+ * switches.
112
+ */
113
+ private finish;
114
+ }
115
+
116
+ /** What a loaded compact model is. */
117
+ export declare interface CompactPredictorInfo {
118
+ /** Which reader path the file uses. */
119
+ readonly kind: CompactKind;
120
+ /** Class labels in score-column order; empty for a regressor. */
121
+ readonly classes: readonly string[];
122
+ /** Values expected per row. */
123
+ readonly numFeatures: number;
124
+ /** Column order recorded at training time, when the export had one. */
125
+ readonly featureNames: readonly string[];
126
+ /** Trees in the ensemble; `0` for a linear model. */
127
+ readonly numTrees: number;
128
+ /** Whether the model produces class scores. */
129
+ readonly isClassifier: boolean;
130
+ /** Class name of the exported estimator. */
131
+ readonly estimator: string;
132
+ }
133
+
134
+ /**
135
+ * Point ONNX Runtime Web at locally served WebAssembly binaries.
136
+ *
137
+ * Call once, before creating any predictor.
138
+ *
139
+ * @example
140
+ * ```ts
141
+ * configureOrtAssets("/ort/");
142
+ * const predictor = await TabularPredictor.create("/models/classifier.onnx");
143
+ * ```
144
+ *
145
+ * @param basePath Directory the binaries are served from, with a trailing
146
+ * slash. Copy them there at build time — for Vite, from
147
+ * `node_modules/onnxruntime-web/dist/`.
148
+ */
149
+ export declare function configureOrtAssets(basePath: string): void;
150
+
151
+ /** Cache Storage bucket used when the caller does not name one. */
152
+ export declare const DEFAULT_MODEL_CACHE = "tempest-tabular-models";
153
+
154
+ /**
155
+ * Execution providers used when the caller does not choose.
156
+ *
157
+ * WebAssembly only, and deliberately: scikit-learn graphs are `ai.onnx.ml`
158
+ * operators, which the WebGPU backend does not implement. There is no
159
+ * speed left on the table here — a 10-tree forest predicts a row in about
160
+ * 0.05 ms in Chromium.
161
+ */
162
+ export declare const DEFAULT_TABULAR_PROVIDERS: readonly string[];
163
+
164
+ /** The package manifest, as written by `edge_pipeline`. */
165
+ export declare interface EdgeManifest {
166
+ readonly schema_version: number;
167
+ readonly name: string;
168
+ readonly version: string;
169
+ readonly created_at: string;
170
+ readonly sdk_version: string;
171
+ readonly estimator: string;
172
+ readonly model: ManifestModelFile;
173
+ readonly input: ManifestInput;
174
+ readonly output: ManifestOutput;
175
+ readonly verified: boolean | null;
176
+ /** Every file a runtime can load. Absent on packages written before v0.194. */
177
+ readonly runtimes?: readonly ManifestRuntime[];
178
+ /** Absent on packages built straight from a fitted estimator. */
179
+ readonly source?: ManifestSource;
180
+ readonly baseline_file: string | null;
181
+ readonly baseline_samples: number;
182
+ }
183
+
184
+ /** One row of feature values, in the column order the model was trained on. */
185
+ export declare type FeatureRow = readonly number[];
186
+
187
+ /** The rows do not match what the model expects. */
188
+ export declare class FeatureShapeError extends TabularError {
189
+ constructor(message: string, options?: ErrorOptions);
190
+ }
191
+
192
+ /**
193
+ * Read a package's manifest.
194
+ *
195
+ * Cheap: it is a few hundred bytes, so an app can check for a new version
196
+ * without downloading a model it may already have.
197
+ *
198
+ * @example
199
+ * ```ts
200
+ * const manifest = await fetchEdgeManifest("/models/risk/");
201
+ * if (manifest.version !== localStorage.getItem("risk-version")) {
202
+ * // a new model was published
203
+ * }
204
+ * ```
205
+ *
206
+ * @param directoryUrl URL of the package directory, with or without a
207
+ * trailing slash. A full URL to the manifest file also works.
208
+ * @param requestInit `fetch` options.
209
+ * @returns The parsed manifest.
210
+ * @throws {@link ModelFetchError} when the manifest cannot be read, or when
211
+ * its `schema_version` is newer than this reader understands loading it
212
+ * anyway would risk misreading the field that defines column order.
213
+ */
214
+ export declare function fetchEdgeManifest(directoryUrl: string, requestInit?: RequestInit): Promise<EdgeManifest>;
215
+
216
+ /**
217
+ * Fetch the model bytes, preferring the on-device copy.
218
+ *
219
+ * @example
220
+ * ```ts
221
+ * const bytes = await fetchModelBytes("/models/classifier-v3.onnx");
222
+ * const predictor = await TabularPredictor.create(bytes);
223
+ * ```
224
+ *
225
+ * @param url Where the model lives.
226
+ * @param options Cache bucket, revalidation and `fetch` options.
227
+ * @returns The model bytes.
228
+ * @throws {@link ModelFetchError} when the model is neither cached nor
229
+ * reachable which is the "offline and never warmed" case, and the
230
+ * message says so.
231
+ */
232
+ export declare function fetchModelBytes(url: string, options?: ModelCacheOptions): Promise<Uint8Array>;
233
+
234
+ /** The session ran but its outputs could not be read. */
235
+ export declare class InferenceError extends TabularError {
236
+ constructor(message: string, options?: ErrorOptions);
237
+ }
238
+
239
+ /**
240
+ * Whether a model is already on the device.
241
+ *
242
+ * Useful for showing "available offline" in the UI, and for deciding
243
+ * whether to prefetch on a metered connection.
244
+ *
245
+ * @param url The model URL.
246
+ * @param cacheName Cache Storage bucket name.
247
+ * @returns `true` when the bytes are cached.
248
+ */
249
+ export declare function isModelCached(url: string, cacheName?: string): Promise<boolean>;
250
+
251
+ /** A package loaded and ready to answer. */
252
+ export declare interface LoadedEdgePackage {
253
+ /** What was published. */
254
+ readonly manifest: EdgeManifest;
255
+ /** The running model, whichever runtime read it. */
256
+ readonly predictor: PredictorLike;
257
+ /** Which reader was used. */
258
+ readonly runtime: TabularRuntime;
259
+ /** Column order the rows must follow. */
260
+ readonly featureNames: readonly string[];
261
+ /** Class names behind each probability column. */
262
+ readonly classes: readonly string[];
263
+ /**
264
+ * Map a prediction's scores onto class names.
265
+ *
266
+ * @param probabilities One row of scores.
267
+ * @returns Name/score pairs, highest first.
343
268
  */
344
- static create(source: TabularModelSource, options?: TabularPredictorOptions): Promise<TabularPredictor>;
269
+ readonly explain: (probabilities: readonly number[]) => {
270
+ name: string;
271
+ score: number;
272
+ }[];
273
+ }
274
+
275
+ /**
276
+ * Load a whole edge package: manifest, model, and the names to read it by.
277
+ *
278
+ * @example
279
+ * ```ts
280
+ * const pkg = await loadEdgePackage("/models/risk/");
281
+ *
282
+ * console.log(pkg.featureNames); // ["age", "income", "tenure", "score", "visits"]
283
+ *
284
+ * const { probabilities } = await pkg.predictor.predict([[41, 5200, 3, 0.82, 12]]);
285
+ * console.log(pkg.explain(probabilities[0]!)); // [{ name: "approved", score: 0.91 }, ...]
286
+ * ```
287
+ *
288
+ * @param directoryUrl URL of the package directory.
289
+ * @param options Predictor options plus caching.
290
+ * @returns The loaded package.
291
+ * @throws {@link ModelFetchError} when the manifest or model cannot be read.
292
+ */
293
+ export declare function loadEdgePackage(directoryUrl: string, options?: LoadEdgePackageOptions): Promise<LoadedEdgePackage>;
294
+
295
+ /** Options for {@link loadEdgePackage}. */
296
+ export declare interface LoadEdgePackageOptions extends TabularPredictorOptions {
297
+ /** Cache the model bytes for offline use. `true` by default. */
298
+ readonly cache?: boolean | ModelCacheOptions;
299
+ /**
300
+ * Which reader to use.
301
+ *
302
+ * `"auto"` (the default) takes the compact form when the package has
303
+ * one, because it answers without downloading a WebAssembly runtime.
304
+ * Force `"onnx"` when the app already ships ONNX for something else —
305
+ * then the runtime is already paid for and ONNX covers more estimators.
306
+ */
307
+ readonly runtime?: TabularRuntime | "auto";
308
+ }
309
+
310
+ /** Fixed filename inside a package directory. */
311
+ export declare const MANIFEST_FILENAME = "manifest.json";
312
+
313
+ /** What the graph expects per row. */
314
+ export declare interface ManifestInput {
315
+ readonly name: string;
316
+ readonly features: number;
317
+ /** Column order used at training time. */
318
+ readonly feature_names: readonly string[];
319
+ }
320
+
321
+ /** The graph file and how to check you got it whole. */
322
+ export declare interface ManifestModelFile {
323
+ readonly file: string;
324
+ readonly sha256: string;
325
+ readonly bytes: number;
326
+ readonly gzip_file: string | null;
327
+ readonly gzip_bytes: number | null;
328
+ readonly opset: number;
329
+ readonly dtype: string;
330
+ }
331
+
332
+ /** What the graph answers. */
333
+ export declare interface ManifestOutput {
334
+ readonly is_classifier: boolean;
335
+ readonly label_output: string;
336
+ readonly probability_output: string | null;
337
+ /** Class labels in score-column order. */
338
+ readonly classes: readonly string[];
339
+ }
340
+
345
341
  /**
346
- * Run one throwaway inference so the first real call is not the slow one.
342
+ * One file in the package a runtime can load.
347
343
  *
348
- * Skipped when the graph does not declare a feature count, since there
349
- * is no shape to synthesise. Failures are swallowed: a warm-up that
350
- * cannot run is not a reason to refuse to serve.
344
+ * A package may carry the same model twice as ONNX, which any runtime
345
+ * reads at the cost of a 25.6 MB WebAssembly download, and as the compact
346
+ * format, which needs no runtime. The list is what lets the browser pick
347
+ * by what it already ships.
351
348
  */
352
- warmUp(): Promise<void>;
349
+ export declare interface ManifestRuntime {
350
+ readonly kind: "onnx" | "compact" | string;
351
+ readonly file: string;
352
+ readonly bytes: number;
353
+ readonly gzip_file: string | null;
354
+ readonly gzip_bytes: number | null;
355
+ readonly sha256: string;
356
+ }
357
+
353
358
  /**
354
- * Predict for a batch of rows.
359
+ * Where the packaged model came from, when it came from an existing
360
+ * artifact.
355
361
  *
356
- * @param rows One array of feature values per row, in training column
357
- * order. A single row is still wrapped: `[[...]]`.
358
- * @returns Labels, class scores when the model produces them, and the
359
- * call's duration.
360
- * @throws {@link FeatureShapeError} when the batch is empty, ragged, or
361
- * the wrong width checked here so the failure names the mismatch
362
- * instead of surfacing as an opaque runtime error.
363
- * @throws {@link InferenceError} when the session runs but its outputs
364
- * cannot be read.
365
- */
366
- predict(rows: readonly FeatureRow[]): Promise<TabularPrediction>;
367
- /**
368
- * Release the session's memory.
369
- *
370
- * Worth calling on a route that swaps models: the WebAssembly heap does
371
- * not shrink on garbage collection alone.
372
- */
373
- dispose(): Promise<void>;
374
- }
375
-
376
- /** What a loaded predictor is, and how it is configured. */
377
- export declare interface TabularPredictorInfo {
378
- /** Graph input name. Not a constant: exporters choose it. */
379
- readonly inputName: string;
380
- /** Features per row, or `null` when the graph does not declare it. */
381
- readonly numFeatures: number | null;
382
- /** Every graph output, in order. */
383
- readonly outputNames: readonly string[];
384
- /** The output holding predicted classes or regressed values. */
385
- readonly labelOutput: string;
386
- /** The output holding class scores, when the graph produces them. */
387
- readonly probabilityOutput: string | null;
388
- /** Whether a score output was found. */
389
- readonly isClassifier: boolean;
390
- /** Execution providers actually in use. */
391
- readonly providers: readonly string[];
392
- }
393
-
394
- /** Options for {@link TabularPredictor.create}. */
395
- export declare interface TabularPredictorOptions {
396
- /**
397
- * Execution providers in preference order.
398
- *
399
- * Defaults to `["wasm"]`, and that is not a placeholder: scikit-learn
400
- * graphs are built from `ai.onnx.ml` operators (`TreeEnsembleClassifier`,
401
- * `LinearClassifier`, `Scaler`), which only the WebAssembly backend
402
- * implements.
403
- */
404
- readonly providers?: readonly string[];
405
- /**
406
- * Run one throwaway inference at creation, so the first real prediction
407
- * does not pay for allocation and kernel selection.
408
- */
409
- readonly warmup?: boolean;
410
- /** Session options forwarded verbatim to ONNX Runtime Web. */
411
- readonly sessionOptions?: Record<string, unknown>;
412
- }
413
-
414
- /** Lifecycle of the model behind the hook. */
415
- export declare type TabularPredictorStatus = "idle" | "loading" | "ready" | "error";
416
-
417
- /**
418
- * The runtime has no kernels for this graph's operators.
419
- *
420
- * Measured, and the reason this class exists: importing
421
- * `onnxruntime-web/webgpu` loads a WebAssembly build without the
422
- * `ai.onnx.ml` domain, so creating a session over any scikit-learn export
423
- * fails with `No Op registered for TreeEnsembleClassifier`. The message
424
- * names the fix, because the raw error points at the model instead of at
425
- * the import.
426
- */
427
- export declare class UnsupportedGraphError extends TabularError {
428
- constructor(message: string, options?: ErrorOptions);
429
- }
430
-
431
- /**
432
- * Load a tabular model and keep it for the component's lifetime.
433
- *
434
- * @example
435
- * ```tsx
436
- * function RiskWidget() {
437
- * const { predict, isReady } = useTabularPredictor("/models/risk-v3.onnx");
438
- * const [score, setScore] = useState<number | null>(null);
439
- *
440
- * async function onSubmit(features: number[]) {
441
- * const { probabilities } = await predict([features]);
442
- * setScore(probabilities[0]?.[1] ?? null);
443
- * }
444
- *
445
- * return <button disabled={!isReady} onClick={() => onSubmit([1, 2, 3, 4])}>Score</button>;
446
- * }
447
- * ```
448
- *
449
- * @param source Model URL, or the bytes when the app already has them.
450
- * Pass `null` to hold off loading (a gate, a lazy tab).
451
- * @param options Predictor options plus caching.
452
- * @returns The predictor, its status, and a `predict` bound to it.
453
- */
454
- export declare function useTabularPredictor(source: TabularModelSource | null, options?: UseTabularPredictorOptions): UseTabularPredictorResult;
455
-
456
- /** Options for {@link useTabularPredictor}. */
457
- export declare interface UseTabularPredictorOptions extends TabularPredictorOptions {
458
- /**
459
- * Cache the model bytes on the device, so later loads work offline.
460
- *
461
- * On by default when the source is a URL: an app that runs inference in
462
- * the browser almost always wants it to keep working without a network,
463
- * and the failure mode of not caching only shows up in a tunnel.
464
- */
465
- readonly cache?: boolean | ModelCacheOptions;
466
- }
467
-
468
- /** What {@link useTabularPredictor} returns. */
469
- export declare interface UseTabularPredictorResult {
470
- /** The loaded predictor, or `null` while loading or on error. */
471
- readonly predictor: TabularPredictor | null;
472
- /** Where the load is. */
473
- readonly status: TabularPredictorStatus;
474
- /** Why the load failed. */
475
- readonly error: Error | null;
476
- /** Whether the model is loaded and can answer. */
477
- readonly isReady: boolean;
478
- /**
479
- * Predict for a batch of rows.
480
- *
481
- * @throws When called before the model is ready — awaiting `isReady`
482
- * is the caller's job, and a silent empty result would hide the bug.
483
- */
484
- readonly predict: (rows: readonly FeatureRow[]) => Promise<TabularPrediction>;
485
- /** Load the model again, e.g. after a failure or a new version. */
486
- readonly reload: () => void;
487
- }
488
-
489
- export { }
362
+ * Present when the package was built with `edge_pipeline_from_pickle`: the
363
+ * `.pkl` never reaches the browser (a pickle is a Python program, not
364
+ * data), but its name and digest travel in the manifest, so a model
365
+ * answering in a tab can be traced back to the file that produced it.
366
+ */
367
+ export declare interface ManifestSource {
368
+ readonly file: string;
369
+ readonly kind: string;
370
+ readonly sha256: string;
371
+ readonly bytes: number;
372
+ readonly sklearn_version: string;
373
+ readonly warnings: readonly string[];
374
+ }
375
+
376
+ /** Options for {@link fetchModelBytes}. */
377
+ export declare interface ModelCacheOptions {
378
+ /** Cache Storage bucket name. */
379
+ readonly cacheName?: string;
380
+ /**
381
+ * Go to the network first and fall back to the cache.
382
+ *
383
+ * For a URL that serves "whatever is current" rather than a pinned
384
+ * version. Costs a round trip on every load when online.
385
+ */
386
+ readonly revalidate?: boolean;
387
+ /** `fetch` options, e.g. credentials for a private model endpoint. */
388
+ readonly requestInit?: RequestInit;
389
+ }
390
+
391
+ /**
392
+ * The model bytes could not be fetched or read from the cache.
393
+ *
394
+ * Distinct from {@link ModelLoadError}: this one means the app is offline
395
+ * and nothing was cached, which is a deployment problem, not a model
396
+ * problem.
397
+ */
398
+ export declare class ModelFetchError extends TabularError {
399
+ constructor(message: string, options?: ErrorOptions);
400
+ }
401
+
402
+ /** The model bytes could not be loaded into a session. */
403
+ export declare class ModelLoadError extends TabularError {
404
+ constructor(message: string, options?: ErrorOptions);
405
+ }
406
+
407
+ /**
408
+ * The WebAssembly binaries ONNX Runtime Web may request.
409
+ *
410
+ * Which one is fetched depends on the browser's threading and SIMD support,
411
+ * so an app that must work everywhere ships all of them. Chromium with the
412
+ * default entry point fetched the `jsep` build.
413
+ */
414
+ export declare const ORT_WASM_ASSETS: readonly string[];
415
+
416
+ /**
417
+ * The URLs a service worker should precache for offline inference.
418
+ *
419
+ * The model file is not included: it is cached by
420
+ * {@link fetchModelBytes} on first use, under its own bucket.
421
+ *
422
+ * @example
423
+ * ```ts
424
+ * installPrecache([...ortAssetUrls("/ort/"), "/index.html"]);
425
+ * ```
426
+ *
427
+ * @param basePath Directory the binaries are served from.
428
+ * @returns Absolute-from-root URLs for every runtime asset.
429
+ */
430
+ export declare function ortAssetUrls(basePath: string): string[];
431
+
432
+ /**
433
+ * A predicted class label.
434
+ *
435
+ * scikit-learn classifiers export an int64 label tensor, which ONNX Runtime
436
+ * Web surfaces as `bigint`. Those are converted to `number` — a class index
437
+ * never approaches `Number.MAX_SAFE_INTEGER`, and leaving `bigint` in the
438
+ * result would break `JSON.stringify` and every `=== 1` comparison a caller
439
+ * writes. A model trained on string labels keeps them as strings.
440
+ */
441
+ export declare type PredictedLabel = number | string;
442
+
443
+ /**
444
+ * The shape both readers share.
445
+ *
446
+ * `TabularPredictor` (ONNX) and `CompactPredictor` (runtime-free) answer
447
+ * with the same object, so an app can switch routes without touching a
448
+ * line of its own code.
449
+ */
450
+ export declare interface PredictorLike {
451
+ predict(rows: readonly FeatureRow[]): Promise<TabularPrediction>;
452
+ dispose(): Promise<void>;
453
+ }
454
+
455
+ /** Layout version this reader understands. */
456
+ export declare const SUPPORTED_COMPACT_SCHEMA = 1;
457
+
458
+ /** Manifest schema version this reader was written against. */
459
+ export declare const SUPPORTED_MANIFEST_SCHEMA = 1;
460
+
461
+ /**
462
+ * Errors thrown by the tabular inference module.
463
+ *
464
+ * Each one exists because the underlying failure is unreadable on its own:
465
+ * ONNX Runtime reports a missing operator registration, and the actual cause
466
+ * is an import path chosen three files away.
467
+ *
468
+ * Every subclass sets `name` to a **literal** string rather than to
469
+ * `new.target.name`. Measured in a real build: the minifier renames the
470
+ * class, so the derived form ships as `error.name === "t"` — useless in a
471
+ * log and in any consumer that branches on the name.
472
+ */
473
+ /** Base class for every error this module throws. */
474
+ export declare class TabularError extends Error {
475
+ constructor(message: string, options?: ErrorOptions);
476
+ }
477
+
478
+ /**
479
+ * Types for browser inference over tabular models exported from scikit-learn.
480
+ */
481
+ /** Anything `InferenceSession.create` accepts as a model. */
482
+ export declare type TabularModelSource = string | ArrayBufferLike | Uint8Array;
483
+
484
+ /** One batch of predictions. */
485
+ export declare interface TabularPrediction {
486
+ /** Predicted class or regressed value per row. */
487
+ readonly labels: readonly PredictedLabel[];
488
+ /** Class scores per row; empty for a regressor. */
489
+ readonly probabilities: readonly (readonly number[])[];
490
+ /** Rows predicted. */
491
+ readonly numRows: number;
492
+ /** Wall-clock inference duration in milliseconds. */
493
+ readonly ms: number;
494
+ }
495
+
496
+ /**
497
+ * A loaded tabular model, ready to answer.
498
+ *
499
+ * @example
500
+ * ```ts
501
+ * const predictor = await TabularPredictor.create("/models/classifier.onnx");
502
+ * const { labels, probabilities } = await predictor.predict([[5.1, 3.5, 1.4, 0.2]]);
503
+ * ```
504
+ */
505
+ export declare class TabularPredictor {
506
+ private readonly session;
507
+ /** What is loaded and how it is configured. */
508
+ readonly info: TabularPredictorInfo;
509
+ private constructor();
510
+ /**
511
+ * Load a model and describe its graph.
512
+ *
513
+ * @param source A URL string, or the model bytes (which is what an
514
+ * offline app passes, having read them from the cache).
515
+ * @param options Providers, warm-up and pass-through session options.
516
+ * @throws {@link UnsupportedGraphError} when the runtime build lacks the
517
+ * `ai.onnx.ml` operators — the WebGPU entry point does.
518
+ * @throws {@link ModelLoadError} for any other load failure.
519
+ */
520
+ static create(source: TabularModelSource, options?: TabularPredictorOptions): Promise<TabularPredictor>;
521
+ /**
522
+ * Run one throwaway inference so the first real call is not the slow one.
523
+ *
524
+ * Skipped when the graph does not declare a feature count, since there
525
+ * is no shape to synthesise. Failures are swallowed: a warm-up that
526
+ * cannot run is not a reason to refuse to serve.
527
+ */
528
+ warmUp(): Promise<void>;
529
+ /**
530
+ * Predict for a batch of rows.
531
+ *
532
+ * @param rows One array of feature values per row, in training column
533
+ * order. A single row is still wrapped: `[[...]]`.
534
+ * @returns Labels, class scores when the model produces them, and the
535
+ * call's duration.
536
+ * @throws {@link FeatureShapeError} when the batch is empty, ragged, or
537
+ * the wrong width — checked here so the failure names the mismatch
538
+ * instead of surfacing as an opaque runtime error.
539
+ * @throws {@link InferenceError} when the session runs but its outputs
540
+ * cannot be read.
541
+ */
542
+ predict(rows: readonly FeatureRow[]): Promise<TabularPrediction>;
543
+ /**
544
+ * Release the session's memory.
545
+ *
546
+ * Worth calling on a route that swaps models: the WebAssembly heap does
547
+ * not shrink on garbage collection alone.
548
+ */
549
+ dispose(): Promise<void>;
550
+ }
551
+
552
+ /** What a loaded predictor is, and how it is configured. */
553
+ export declare interface TabularPredictorInfo {
554
+ /** Graph input name. Not a constant: exporters choose it. */
555
+ readonly inputName: string;
556
+ /** Features per row, or `null` when the graph does not declare it. */
557
+ readonly numFeatures: number | null;
558
+ /** Every graph output, in order. */
559
+ readonly outputNames: readonly string[];
560
+ /** The output holding predicted classes or regressed values. */
561
+ readonly labelOutput: string;
562
+ /** The output holding class scores, when the graph produces them. */
563
+ readonly probabilityOutput: string | null;
564
+ /** Whether a score output was found. */
565
+ readonly isClassifier: boolean;
566
+ /** Execution providers actually in use. */
567
+ readonly providers: readonly string[];
568
+ }
569
+
570
+ /** Options for {@link TabularPredictor.create}. */
571
+ export declare interface TabularPredictorOptions {
572
+ /**
573
+ * Execution providers in preference order.
574
+ *
575
+ * Defaults to `["wasm"]`, and that is not a placeholder: scikit-learn
576
+ * graphs are built from `ai.onnx.ml` operators (`TreeEnsembleClassifier`,
577
+ * `LinearClassifier`, `Scaler`), which only the WebAssembly backend
578
+ * implements.
579
+ */
580
+ readonly providers?: readonly string[];
581
+ /**
582
+ * Run one throwaway inference at creation, so the first real prediction
583
+ * does not pay for allocation and kernel selection.
584
+ */
585
+ readonly warmup?: boolean;
586
+ /** Session options forwarded verbatim to ONNX Runtime Web. */
587
+ readonly sessionOptions?: Record<string, unknown>;
588
+ }
589
+
590
+ /** Lifecycle of the model behind the hook. */
591
+ export declare type TabularPredictorStatus = "idle" | "loading" | "ready" | "error";
592
+
593
+ /** Which reader served the package. */
594
+ export declare type TabularRuntime = "onnx" | "compact";
595
+
596
+ /**
597
+ * The runtime has no kernels for this graph's operators.
598
+ *
599
+ * Measured, and the reason this class exists: importing
600
+ * `onnxruntime-web/webgpu` loads a WebAssembly build without the
601
+ * `ai.onnx.ml` domain, so creating a session over any scikit-learn export
602
+ * fails with `No Op registered for TreeEnsembleClassifier`. The message
603
+ * names the fix, because the raw error points at the model instead of at
604
+ * the import.
605
+ */
606
+ export declare class UnsupportedGraphError extends TabularError {
607
+ constructor(message: string, options?: ErrorOptions);
608
+ }
609
+
610
+ /**
611
+ * Load a tabular model and keep it for the component's lifetime.
612
+ *
613
+ * @example
614
+ * ```tsx
615
+ * function RiskWidget() {
616
+ * const { predict, isReady } = useTabularPredictor("/models/risk-v3.onnx");
617
+ * const [score, setScore] = useState<number | null>(null);
618
+ *
619
+ * async function onSubmit(features: number[]) {
620
+ * const { probabilities } = await predict([features]);
621
+ * setScore(probabilities[0]?.[1] ?? null);
622
+ * }
623
+ *
624
+ * return <button disabled={!isReady} onClick={() => onSubmit([1, 2, 3, 4])}>Score</button>;
625
+ * }
626
+ * ```
627
+ *
628
+ * @param source Model URL, or the bytes when the app already has them.
629
+ * Pass `null` to hold off loading (a gate, a lazy tab).
630
+ * @param options Predictor options plus caching.
631
+ * @returns The predictor, its status, and a `predict` bound to it.
632
+ */
633
+ export declare function useTabularPredictor(source: TabularModelSource | null, options?: UseTabularPredictorOptions): UseTabularPredictorResult;
634
+
635
+ /** Options for {@link useTabularPredictor}. */
636
+ export declare interface UseTabularPredictorOptions extends TabularPredictorOptions {
637
+ /**
638
+ * Cache the model bytes on the device, so later loads work offline.
639
+ *
640
+ * On by default when the source is a URL: an app that runs inference in
641
+ * the browser almost always wants it to keep working without a network,
642
+ * and the failure mode of not caching only shows up in a tunnel.
643
+ */
644
+ readonly cache?: boolean | ModelCacheOptions;
645
+ }
646
+
647
+ /** What {@link useTabularPredictor} returns. */
648
+ export declare interface UseTabularPredictorResult {
649
+ /** The loaded predictor, or `null` while loading or on error. */
650
+ readonly predictor: TabularPredictor | null;
651
+ /** Where the load is. */
652
+ readonly status: TabularPredictorStatus;
653
+ /** Why the load failed. */
654
+ readonly error: Error | null;
655
+ /** Whether the model is loaded and can answer. */
656
+ readonly isReady: boolean;
657
+ /**
658
+ * Predict for a batch of rows.
659
+ *
660
+ * @throws When called before the model is ready — awaiting `isReady`
661
+ * is the caller's job, and a silent empty result would hide the bug.
662
+ */
663
+ readonly predict: (rows: readonly FeatureRow[]) => Promise<TabularPrediction>;
664
+ /** Load the model again, e.g. after a failure or a new version. */
665
+ readonly reload: () => void;
666
+ }
667
+
668
+ export { }