@tanstack-ai-browser/onnx 0.0.0-stage → 0.3.3

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.
@@ -0,0 +1,175 @@
1
+ import assert from "node:assert/strict"
2
+ import { readFileSync } from "node:fs"
3
+ import { test } from "node:test"
4
+
5
+ import { onnxImage } from "./adapter.js"
6
+ import { ONNX_IMAGE_MODELS } from "./model-meta.js"
7
+ import { ORT_VERSION } from "./runtime.js"
8
+
9
+ const logger = {
10
+ request: () => undefined,
11
+ errors: () => undefined
12
+ } as never
13
+
14
+ const model = ONNX_IMAGE_MODELS[0]
15
+
16
+ test("the adapter is TanStack AI's image kind, named onnx", () => {
17
+ const adapter = onnxImage(model)
18
+ assert.equal(adapter.kind, "image")
19
+ assert.equal(adapter.name, "onnx")
20
+ assert.equal(adapter.model, model)
21
+ })
22
+
23
+ test("an unknown model is refused", () => {
24
+ assert.throws(
25
+ () => onnxImage("someone/else" as never),
26
+ /doesn't know someone\/else/
27
+ )
28
+ })
29
+
30
+ test("numberOfImages is 1 to 8", async () => {
31
+ const adapter = onnxImage(model)
32
+ for (const numberOfImages of [0, 9, 1.5]) {
33
+ await assert.rejects(
34
+ adapter.generateImages({ model, prompt: "duck", numberOfImages, logger }),
35
+ /numberOfImages must be 1 to 8/
36
+ )
37
+ }
38
+ })
39
+
40
+ test("only the model's own size is taken", async () => {
41
+ await assert.rejects(
42
+ onnxImage(model).generateImages({
43
+ model,
44
+ prompt: "duck",
45
+ size: "1024x1024" as never,
46
+ logger
47
+ }),
48
+ /draws 16x16 images, not 1024x1024/
49
+ )
50
+ })
51
+
52
+ test("image parts in the prompt are refused, and an empty prompt", async () => {
53
+ const adapter = onnxImage(model)
54
+ await assert.rejects(
55
+ adapter.generateImages({
56
+ model,
57
+ prompt: [
58
+ {
59
+ type: "image",
60
+ source: { type: "url", value: "https://example.com/a.png" }
61
+ }
62
+ ],
63
+ logger
64
+ }),
65
+ /only takes text prompts, not image parts/
66
+ )
67
+ await assert.rejects(
68
+ adapter.generateImages({ model, prompt: " ", logger }),
69
+ /The prompt is empty/
70
+ )
71
+ })
72
+
73
+ test("errors go to the logger", async () => {
74
+ const seen: Array<string> = []
75
+ const logging = {
76
+ request: () => undefined,
77
+ errors: (message: string) => seen.push(message)
78
+ } as never
79
+ await assert.rejects(
80
+ onnxImage(model).generateImages({ model, prompt: "", logger: logging })
81
+ )
82
+ assert.equal(seen.length, 1)
83
+ })
84
+
85
+ test("a model with no stored files is downloadable", async () => {
86
+ // Node has no Cache Storage: nothing is stored.
87
+ assert.equal(await onnxImage(model).availability(), "downloadable")
88
+ })
89
+
90
+ test("invalid steps, guidance and seeds are refused before anything loads", async () => {
91
+ const adapter = onnxImage(model)
92
+ for (const steps of [
93
+ 0,
94
+ -1,
95
+ 1.5,
96
+ Number.NaN,
97
+ Number.POSITIVE_INFINITY,
98
+ 1001
99
+ ]) {
100
+ await assert.rejects(
101
+ adapter.generateImages({
102
+ model,
103
+ prompt: "duck",
104
+ modelOptions: { steps },
105
+ logger
106
+ }),
107
+ /steps must be a whole number from 1 to 1000/
108
+ )
109
+ }
110
+ for (const guidanceScale of [Number.NaN, Number.POSITIVE_INFINITY]) {
111
+ await assert.rejects(
112
+ adapter.generateImages({
113
+ model,
114
+ prompt: "duck",
115
+ modelOptions: { guidanceScale },
116
+ logger
117
+ }),
118
+ /guidanceScale must be a finite number/
119
+ )
120
+ }
121
+ await assert.rejects(
122
+ adapter.generateImages({
123
+ model,
124
+ prompt: "duck",
125
+ modelOptions: { seed: Number.NaN },
126
+ logger
127
+ }),
128
+ /seed must be a finite number/
129
+ )
130
+ })
131
+
132
+ test("adapters with other session or WebGPU options don't share sessions", () => {
133
+ const key = (adapter: ReturnType<typeof onnxImage>) =>
134
+ (adapter as unknown as { key: string }).key
135
+ class FakeDevice {}
136
+ const device = new FakeDevice() as GPUDevice
137
+ const quiet = { sessionOptions: { logSeverityLevel: 3 as const } }
138
+ assert.equal(key(onnxImage(model)), key(onnxImage(model, {})))
139
+ assert.equal(
140
+ key(onnxImage(model, quiet)),
141
+ key(onnxImage(model, { sessionOptions: { logSeverityLevel: 3 } }))
142
+ )
143
+ assert.notEqual(key(onnxImage(model)), key(onnxImage(model, quiet)))
144
+ assert.notEqual(
145
+ key(onnxImage(model)),
146
+ key(onnxImage(model, { webgpuOptions: { preferredLayout: "NHWC" } }))
147
+ )
148
+ // Objects JSON can't stand for are told apart by identity.
149
+ assert.equal(
150
+ key(onnxImage(model, { webgpuOptions: { device } })),
151
+ key(onnxImage(model, { webgpuOptions: { device } }))
152
+ )
153
+ assert.notEqual(
154
+ key(onnxImage(model, { webgpuOptions: { device } })),
155
+ key(
156
+ onnxImage(model, {
157
+ webgpuOptions: { device: new FakeDevice() as GPUDevice }
158
+ })
159
+ )
160
+ )
161
+ })
162
+
163
+ test("a load whose caller has already given up doesn't start", async () => {
164
+ await assert.rejects(
165
+ onnxImage(model).create({ signal: AbortSignal.abort() }),
166
+ { name: "AbortError" }
167
+ )
168
+ })
169
+
170
+ test("the WebAssembly files load at the installed onnxruntime-web version", () => {
171
+ const manifest = JSON.parse(
172
+ readFileSync(new URL("../package.json", import.meta.url), "utf8")
173
+ ) as { dependencies: Record<string, string> }
174
+ assert.equal(manifest.dependencies["onnxruntime-web"], ORT_VERSION)
175
+ })
package/src/adapter.ts ADDED
@@ -0,0 +1,450 @@
1
+ /**
2
+ * TanStack AI's image adapter for ONNX models in the browser, on ONNX
3
+ * Runtime Web: WebGPU where the browser has a GPU adapter, else the CPU
4
+ * (WebAssembly). `generateImage({ adapter: onnxImage(model), prompt })`.
5
+ */
6
+ import { Tokenizer } from "@huggingface/tokenizers"
7
+ import type {
8
+ ImageGenerationOptions,
9
+ ImageGenerationResult
10
+ } from "@tanstack/ai"
11
+ import { BaseImageAdapter } from "@tanstack/ai/adapters"
12
+ import type { InferenceSession } from "onnxruntime-web"
13
+
14
+ import { fileUrl, ONNX_MODEL_META } from "./model-meta.js"
15
+ import type {
16
+ OnnxImageModel,
17
+ OnnxImageModelMeta,
18
+ OnnxImageModelSizeByName
19
+ } from "./model-meta.js"
20
+ import { encodePng, toBase64 } from "./png.js"
21
+ import {
22
+ createSessions,
23
+ DEFAULT_WASM_PATHS,
24
+ hasWebGpu,
25
+ loadOrt
26
+ } from "./runtime.js"
27
+ import type { OnnxBackend, Ort } from "./runtime.js"
28
+ import { serial } from "./lifecycle.js"
29
+ import { allStored, fileBytes, removeFiles } from "./storage.js"
30
+ import {
31
+ DEFAULT_SAMPLER,
32
+ drawSprites,
33
+ fixedLengthIds,
34
+ GRID,
35
+ spritePixels
36
+ } from "./tessera.js"
37
+
38
+ /** Download progress, 0 to 1 (1 once the model is loaded). */
39
+ export type DownloadProgressCallback = (progress: number) => void
40
+
41
+ /** Where a model stands on this device. */
42
+ export type Availability =
43
+ "unavailable" | "downloadable" | "downloading" | "available"
44
+
45
+ export type OnnxImageConfig = {
46
+ /** Called with every model download's progress, 0 to 1. */
47
+ onDownloadProgress?: DownloadProgressCallback
48
+ /** Where ONNX Runtime's WebAssembly files load from (default: jsDelivr, at the installed version). */
49
+ wasmPaths?: string
50
+ /** Run on this backend instead of the best one the browser has. */
51
+ backend?: OnnxBackend
52
+ /** ONNX Runtime session options, over the adapter's own (see runtime.ts's `createSessions`). */
53
+ sessionOptions?: InferenceSession.SessionOptions
54
+ /** ONNX Runtime WebGPU backend options (such as `storageBufferCacheMode`), on WebGPU. */
55
+ webgpuOptions?: Record<string, unknown>
56
+ }
57
+
58
+ /** Sampler settings, per call (`modelOptions`). */
59
+ export type OnnxImageProviderOptions = {
60
+ /** The random seed: the same seed, prompt and settings draw the same images. Random if left out. */
61
+ seed?: number
62
+ /** Denoiser passes (default 16). Fewer is faster and rougher. */
63
+ steps?: number
64
+ /** Classifier-free guidance (default 3): how strongly the images follow the prompt. */
65
+ guidanceScale?: number
66
+ }
67
+
68
+ /** Most images one call draws (each is two rows of the denoiser's batch). */
69
+ export const MAX_IMAGES = 8
70
+
71
+ type Loaded = {
72
+ model: string
73
+ backend: OnnxBackend
74
+ ort: Ort
75
+ denoiser: InferenceSession
76
+ textEncoder: InferenceSession
77
+ tokenizer: Tokenizer
78
+ /** CLIP's end-of-text token, which also pads the text encoder's input. */
79
+ endToken: number
80
+ palette: ReadonlyArray<ReadonlyArray<number>>
81
+ }
82
+
83
+ /**
84
+ * The page's loaded model: one at a time, so two never sit in memory
85
+ * together. Only tasks in the lifecycle queue (lifecycle.ts) change it.
86
+ */
87
+ let current: { key: string; ready: Promise<Loaded> } | undefined
88
+
89
+ /** A stable id for a value JSON can't stand for (a GPUDevice in webgpuOptions, say), by identity. */
90
+ const identities = new WeakMap<object, number>()
91
+ let nextIdentity = 0
92
+ const settingsKey = (value: unknown) =>
93
+ JSON.stringify(value ?? null, (_key, v: unknown) => {
94
+ const plain =
95
+ typeof v !== "object" ||
96
+ v === null ||
97
+ Array.isArray(v) ||
98
+ Object.getPrototypeOf(v) === Object.prototype
99
+ if (typeof v === "function" || !plain) {
100
+ const object = v as object
101
+ if (!identities.has(object)) identities.set(object, ++nextIdentity)
102
+ return `#${identities.get(object)}`
103
+ }
104
+ return v
105
+ })
106
+
107
+ async function release(entry: { ready: Promise<Loaded> }) {
108
+ const loaded = await entry.ready.catch(() => undefined)
109
+ if (loaded)
110
+ await Promise.all([loaded.denoiser.release(), loaded.textEncoder.release()])
111
+ }
112
+
113
+ const modelUrls = (meta: OnnxImageModelMeta) =>
114
+ Object.values(meta.files).map((file) => fileUrl(meta, file))
115
+
116
+ /** The prompt's text: a string, or its text parts. Image-conditioned prompts aren't supported. */
117
+ function promptText(prompt: ImageGenerationOptions["prompt"]): string {
118
+ if (typeof prompt === "string") return prompt
119
+ return prompt
120
+ .map((part) => {
121
+ if (part.type !== "text")
122
+ throw new Error(
123
+ `onnxImage only takes text prompts, not ${part.type} parts`
124
+ )
125
+ return part.content
126
+ })
127
+ .join(" ")
128
+ }
129
+
130
+ export class OnnxImageAdapter<
131
+ TModel extends OnnxImageModel
132
+ > extends BaseImageAdapter<
133
+ TModel,
134
+ OnnxImageProviderOptions,
135
+ Record<OnnxImageModel, OnnxImageProviderOptions>,
136
+ OnnxImageModelSizeByName
137
+ > {
138
+ readonly name = "onnx" as const
139
+ private readonly meta: OnnxImageModelMeta
140
+ private readonly settings: OnnxImageConfig
141
+ /** Downloads of this adapter's model going on now. */
142
+ private downloading = 0
143
+
144
+ constructor(model: TModel, config: OnnxImageConfig = {}) {
145
+ super(model, {})
146
+ const meta: OnnxImageModelMeta | undefined = ONNX_MODEL_META[model]
147
+ if (!meta) throw new Error(`onnxImage doesn't know ${model}`)
148
+ this.meta = meta
149
+ this.settings = config
150
+ }
151
+
152
+ /** What the page's sessions are made for: the model and every setting that changes them. */
153
+ private get key() {
154
+ const { backend, wasmPaths, sessionOptions, webgpuOptions } = this.settings
155
+ return JSON.stringify([
156
+ this.model,
157
+ backend ?? null,
158
+ wasmPaths ?? null,
159
+ settingsKey(sessionOptions),
160
+ settingsKey(webgpuOptions)
161
+ ])
162
+ }
163
+
164
+ /** The backend the model runs on, once it's loaded here. */
165
+ async backend(): Promise<OnnxBackend | undefined> {
166
+ if (current?.key !== this.key) return undefined
167
+ return (await current.ready.catch(() => undefined))?.backend
168
+ }
169
+
170
+ /**
171
+ * Where the model stands here: "unavailable" without WebAssembly;
172
+ * "available" once its files are stored (or it's loaded); "downloading"
173
+ * while this adapter downloads it; else "downloadable" (it downloads at
174
+ * `create`, or at the first `generateImage()`).
175
+ */
176
+ async availability(): Promise<Availability> {
177
+ if (typeof WebAssembly === "undefined") return "unavailable"
178
+ if (current?.key === this.key) return "available"
179
+ if (this.downloading > 0) return "downloading"
180
+ return (await allStored(modelUrls(this.meta)))
181
+ ? "available"
182
+ : "downloadable"
183
+ }
184
+
185
+ /**
186
+ * Downloads the model if it isn't stored and loads it, with the download's
187
+ * progress, 0 to 1, then 1 once it's ready. Resolves to this adapter.
188
+ * `generateImage()` doesn't need it: the first call loads the model too.
189
+ * Loading another model first unloads the page's current one.
190
+ */
191
+ create(
192
+ options: {
193
+ onDownloadProgress?: DownloadProgressCallback
194
+ signal?: AbortSignal
195
+ } = {}
196
+ ): Promise<this> {
197
+ const ready = serial(() => this.load(options), options.signal).then(() => {
198
+ options.onDownloadProgress?.(1)
199
+ this.settings.onDownloadProgress?.(1)
200
+ return this
201
+ })
202
+ ready.catch(() => undefined)
203
+ return ready
204
+ }
205
+
206
+ /** Unloads the model, if it's the page's, after the drawings queued before. Its stored files stay. */
207
+ destroy(): Promise<void> {
208
+ return serial(() => this.unloadNow())
209
+ }
210
+
211
+ /** Removes the model's stored files, after unloading it. Returns whether any were stored. */
212
+ remove(): Promise<boolean> {
213
+ return serial(async () => {
214
+ await this.unloadNow()
215
+ return removeFiles(modelUrls(this.meta))
216
+ })
217
+ }
218
+
219
+ /** (In the lifecycle queue.) */
220
+ private async unloadNow() {
221
+ if (current?.key !== this.key) return
222
+ const entry = current
223
+ current = undefined
224
+ await release(entry)
225
+ }
226
+
227
+ /**
228
+ * (In the lifecycle queue.) The page's sessions for this adapter's model
229
+ * and settings: the ones loaded, or new ones after the page's others are
230
+ * released.
231
+ */
232
+ private async load(
233
+ options: {
234
+ onDownloadProgress?: DownloadProgressCallback
235
+ signal?: AbortSignal
236
+ } = {}
237
+ ): Promise<Loaded> {
238
+ if (current?.key === this.key) return current.ready
239
+ if (current) {
240
+ const previous = current
241
+ current = undefined
242
+ await release(previous)
243
+ }
244
+ const ready = this.loadFresh(options)
245
+ const entry = { key: this.key, ready }
246
+ current = entry
247
+ ready.catch(() => {
248
+ if (current === entry) current = undefined
249
+ })
250
+ return ready
251
+ }
252
+
253
+ private async loadFresh(options: {
254
+ onDownloadProgress?: DownloadProgressCallback
255
+ signal?: AbortSignal
256
+ }): Promise<Loaded> {
257
+ const { meta } = this
258
+ const { files } = meta
259
+ const stored = await allStored(modelUrls(meta))
260
+ const total = files.denoiser.bytes + files.textEncoder.bytes
261
+ const seen = { denoiser: 0, textEncoder: 0 }
262
+ const report = () => {
263
+ const progress = Math.min(
264
+ (seen.denoiser + seen.textEncoder) / total,
265
+ 0.999
266
+ )
267
+ options.onDownloadProgress?.(progress)
268
+ this.settings.onDownloadProgress?.(progress)
269
+ }
270
+ const signal = options.signal
271
+ signal?.throwIfAborted()
272
+ if (!stored) this.downloading++
273
+ let bytes: [ArrayBuffer, ArrayBuffer, ArrayBuffer, ArrayBuffer]
274
+ try {
275
+ bytes = await Promise.all([
276
+ fileBytes(fileUrl(meta, files.denoiser), {
277
+ signal,
278
+ onBytes: (n) => ((seen.denoiser = n), report())
279
+ }),
280
+ fileBytes(fileUrl(meta, files.textEncoder), {
281
+ signal,
282
+ onBytes: (n) => ((seen.textEncoder = n), report())
283
+ }),
284
+ fileBytes(fileUrl(meta, files.tokenizer), { signal }),
285
+ fileBytes(fileUrl(meta, files.palette), { signal })
286
+ ])
287
+ } finally {
288
+ if (!stored) this.downloading--
289
+ }
290
+ const [denoiserBytes, textEncoderBytes, tokenizerBytes, paletteBytes] =
291
+ bytes
292
+ const decode = (b: ArrayBuffer) =>
293
+ JSON.parse(new TextDecoder().decode(b)) as unknown
294
+ const tokenizer = new Tokenizer(decode(tokenizerBytes) as object, {})
295
+ const palette = (
296
+ decode(paletteBytes) as { palette_rgba: Array<Array<number>> }
297
+ ).palette_rgba
298
+ const endToken = tokenizer.token_to_id("<|endoftext|>")
299
+ if (endToken === undefined)
300
+ throw new Error(`${this.model}'s tokenizer has no <|endoftext|> token`)
301
+
302
+ const ort = await loadOrt(this.settings.wasmPaths ?? DEFAULT_WASM_PATHS)
303
+ // Cached files come back whatever the signal says: a caller that stopped meanwhile makes no sessions.
304
+ signal?.throwIfAborted()
305
+ const files_ = { denoiser: denoiserBytes, textEncoder: textEncoderBytes }
306
+ let backend: OnnxBackend =
307
+ this.settings.backend ?? ((await hasWebGpu()) ? "webgpu" : "wasm")
308
+ let sessions: Record<"denoiser" | "textEncoder", InferenceSession>
309
+ const extra = this.settings.sessionOptions
310
+ try {
311
+ sessions = await createSessions(
312
+ ort,
313
+ files_,
314
+ backend,
315
+ extra,
316
+ this.settings.webgpuOptions
317
+ )
318
+ } catch (error) {
319
+ // A GPU that can't take the model: the CPU still can (unless asked for WebGPU).
320
+ if (backend !== "webgpu" || this.settings.backend) throw error
321
+ console.warn(
322
+ "onnxImage: WebGPU couldn't load the model, running it on the CPU",
323
+ error
324
+ )
325
+ backend = "wasm"
326
+ sessions = await createSessions(
327
+ ort,
328
+ files_,
329
+ backend,
330
+ extra,
331
+ this.settings.webgpuOptions
332
+ )
333
+ }
334
+ return {
335
+ model: this.model,
336
+ backend,
337
+ ort,
338
+ ...sessions,
339
+ tokenizer,
340
+ endToken,
341
+ palette
342
+ }
343
+ }
344
+
345
+ async generateImages(
346
+ options: ImageGenerationOptions<
347
+ OnnxImageProviderOptions,
348
+ OnnxImageModelSizeByName[TModel]
349
+ >
350
+ ): Promise<ImageGenerationResult> {
351
+ const { logger, abortSignal, modelOptions = {} } = options
352
+ const count = options.numberOfImages ?? 1
353
+ try {
354
+ if (!Number.isInteger(count) || count < 1 || count > MAX_IMAGES) {
355
+ throw new Error(
356
+ `numberOfImages must be 1 to ${MAX_IMAGES}, not ${count}`
357
+ )
358
+ }
359
+ if (options.size !== undefined && options.size !== this.meta.size) {
360
+ throw new Error(
361
+ `${this.model} draws ${this.meta.size} images, not ${options.size}`
362
+ )
363
+ }
364
+ const text = promptText(options.prompt).trim()
365
+ if (!text) throw new Error("The prompt is empty")
366
+ const sampler = samplerSettings(modelOptions)
367
+ logger.request(`onnx.generateImages ${this.model}`, {
368
+ provider: "onnx",
369
+ model: this.model,
370
+ numberOfImages: count
371
+ })
372
+ // Loading (or switching) and drawing in one task: nothing else releases these sessions meanwhile.
373
+ const images = await serial(async () => {
374
+ const loaded = await this.load(
375
+ abortSignal ? { signal: abortSignal } : {}
376
+ )
377
+ const ids = fixedLengthIds(
378
+ loaded.tokenizer.encode(text).ids,
379
+ loaded.endToken
380
+ )
381
+ const sprites = await drawSprites(
382
+ {
383
+ Tensor: loaded.ort.Tensor,
384
+ denoiser: loaded.denoiser,
385
+ textEncoder: loaded.textEncoder
386
+ },
387
+ ids,
388
+ count,
389
+ sampler,
390
+ abortSignal
391
+ )
392
+ return Promise.all(
393
+ sprites.map(async (tokens) =>
394
+ toBase64(
395
+ await encodePng(spritePixels(tokens, loaded.palette), GRID, GRID)
396
+ )
397
+ )
398
+ )
399
+ }, abortSignal)
400
+ return {
401
+ id: this.generateId(),
402
+ model: this.model,
403
+ images: images.map((b64Json) => ({ b64Json }))
404
+ }
405
+ } catch (error) {
406
+ logger.errors(`onnx.generateImages ${this.model} failed`, {
407
+ error,
408
+ source: "onnx.generateImages"
409
+ })
410
+ throw error
411
+ }
412
+ }
413
+ }
414
+
415
+ /** Most denoising steps one call takes. */
416
+ export const MAX_STEPS = 1000
417
+
418
+ /** The sampler's settings for a call: the defaults, with `modelOptions`' own after checking them. */
419
+ function samplerSettings(options: OnnxImageProviderOptions) {
420
+ const { seed, steps, guidanceScale } = options
421
+ if (
422
+ steps !== undefined &&
423
+ (!Number.isInteger(steps) || steps < 1 || steps > MAX_STEPS)
424
+ ) {
425
+ throw new Error(
426
+ `steps must be a whole number from 1 to ${MAX_STEPS}, not ${steps}`
427
+ )
428
+ }
429
+ if (guidanceScale !== undefined && !Number.isFinite(guidanceScale)) {
430
+ throw new Error(
431
+ `guidanceScale must be a finite number, not ${guidanceScale}`
432
+ )
433
+ }
434
+ if (seed !== undefined && !Number.isFinite(seed))
435
+ throw new Error(`seed must be a finite number, not ${seed}`)
436
+ return {
437
+ ...DEFAULT_SAMPLER,
438
+ ...(steps !== undefined && { steps }),
439
+ ...(guidanceScale !== undefined && { guidanceScale }),
440
+ seed: seed ?? Math.floor(Math.random() * 2 ** 32)
441
+ }
442
+ }
443
+
444
+ /** An image adapter for one of the catalog's ONNX models. */
445
+ export function onnxImage<TModel extends OnnxImageModel>(
446
+ model: TModel,
447
+ config: OnnxImageConfig = {}
448
+ ): OnnxImageAdapter<TModel> {
449
+ return new OnnxImageAdapter(model, config)
450
+ }
package/src/index.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * TanStack AI image adapter for ONNX models in the browser, on ONNX Runtime
3
+ * Web (WebGPU, else WebAssembly). The model catalog (model-meta.ts) is
4
+ * exported here too.
5
+ */
6
+ export { MAX_IMAGES, OnnxImageAdapter, onnxImage } from "./adapter.js"
7
+ export type {
8
+ Availability,
9
+ DownloadProgressCallback,
10
+ OnnxImageConfig,
11
+ OnnxImageProviderOptions
12
+ } from "./adapter.js"
13
+ export { ONNX_IMAGE_MODELS, ONNX_MODEL_META } from "./model-meta.js"
14
+ export type { OnnxImageModel, OnnxImageModelMeta, OnnxImageModelSizeByName, OnnxModelFile } from "./model-meta.js"
15
+ export { DEFAULT_WASM_PATHS, ORT_VERSION } from "./runtime.js"
16
+ export type { OnnxBackend } from "./runtime.js"
17
+ export { MODEL_CACHE } from "./storage.js"
@@ -0,0 +1,67 @@
1
+ import assert from "node:assert/strict"
2
+ import { test } from "node:test"
3
+
4
+ import { serial } from "./lifecycle.js"
5
+
6
+ test("tasks run one at a time, in the order they were queued", async () => {
7
+ const seen: Array<string> = []
8
+ const task = (name: string, ms: number) => () =>
9
+ new Promise<string>((resolve) => {
10
+ seen.push(`${name} start`)
11
+ setTimeout(() => {
12
+ seen.push(`${name} end`)
13
+ resolve(name)
14
+ }, ms)
15
+ })
16
+ const results = await Promise.all([
17
+ serial(task("a", 20)),
18
+ serial(task("b", 1)),
19
+ serial(task("c", 5))
20
+ ])
21
+ assert.deepEqual(results, ["a", "b", "c"])
22
+ assert.deepEqual(seen, [
23
+ "a start",
24
+ "a end",
25
+ "b start",
26
+ "b end",
27
+ "c start",
28
+ "c end"
29
+ ])
30
+ })
31
+
32
+ test("a failed task doesn't stop the ones after it", async () => {
33
+ const failed = serial(() => Promise.reject(new Error("no")))
34
+ const next = serial(() => Promise.resolve("yes"))
35
+ await assert.rejects(failed, /no/)
36
+ assert.equal(await next, "yes")
37
+ })
38
+
39
+ test("a caller aborted while it waits rejects at once, and its task never runs", async () => {
40
+ let release!: () => void
41
+ const first = serial(
42
+ () => new Promise<void>((resolve) => (release = resolve))
43
+ )
44
+ const controller = new AbortController()
45
+ let ran = false
46
+ const waiting = serial(async () => {
47
+ ran = true
48
+ }, controller.signal)
49
+ controller.abort()
50
+ await assert.rejects(waiting, { name: "AbortError" })
51
+ release()
52
+ await first
53
+ await serial(() => Promise.resolve())
54
+ assert.equal(ran, false)
55
+ })
56
+
57
+ test("a caller already aborted is refused", async () => {
58
+ let ran = false
59
+ await assert.rejects(
60
+ serial(async () => {
61
+ ran = true
62
+ }, AbortSignal.abort()),
63
+ { name: "AbortError" }
64
+ )
65
+ await serial(() => Promise.resolve())
66
+ assert.equal(ran, false)
67
+ })