@tradalab/tskit 0.0.0-stage → 0.1.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 +72 -2
- package/dist/assets.d.ts +83 -0
- package/dist/assets.js +285 -0
- package/dist/assets.js.map +1 -0
- package/dist/cache.d.ts +27 -0
- package/dist/cache.js +13 -0
- package/dist/cache.js.map +1 -0
- package/dist/chunk-CPL35ABZ.js +109 -0
- package/dist/chunk-CPL35ABZ.js.map +1 -0
- package/dist/chunk-JRWPS4OS.js +159 -0
- package/dist/chunk-JRWPS4OS.js.map +1 -0
- package/dist/chunk-UUTOMKU7.js +93 -0
- package/dist/chunk-UUTOMKU7.js.map +1 -0
- package/dist/chunk-ZPGZZXHR.js +153 -0
- package/dist/chunk-ZPGZZXHR.js.map +1 -0
- package/dist/fetch.d.ts +31 -0
- package/dist/fetch.js +17 -0
- package/dist/fetch.js.map +1 -0
- package/dist/progress.d.ts +45 -0
- package/dist/progress.js +9 -0
- package/dist/progress.js.map +1 -0
- package/dist/retain.d.ts +30 -0
- package/dist/retain.js +7 -0
- package/dist/retain.js.map +1 -0
- package/package.json +47 -3
package/README.md
CHANGED
|
@@ -1,3 +1,73 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tradalab/tskit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Framework-free TypeScript shared across tradalab. No runtime dependency; every subpath imports in
|
|
4
|
+
a page, a worker, an AudioWorklet and Node.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
pnpm add @tradalab/tskit
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
| Subpath | What it gives you |
|
|
11
|
+
|---|---|
|
|
12
|
+
| `@tradalab/tskit/progress` | `ProgressTracker`: progress over many items, bytes and phases |
|
|
13
|
+
| `@tradalab/tskit/retain` | `Retainer`: shared, reference-counted values with a keep time |
|
|
14
|
+
| `@tradalab/tskit/fetch` | `fetchBytes`: streamed download with stall timeout, retry and integrity check |
|
|
15
|
+
| `@tradalab/tskit/cache` | `openByteStore`: bytes in Cache Storage per name and version, memory fallback |
|
|
16
|
+
| `@tradalab/tskit/assets` | `createAssets`: the four above as one manager for a manifest of files |
|
|
17
|
+
|
|
18
|
+
## Assets
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { createAssets } from "@tradalab/tskit/assets"
|
|
22
|
+
|
|
23
|
+
const assets = createAssets({
|
|
24
|
+
name: "mediakit",
|
|
25
|
+
version: "3.0.0",
|
|
26
|
+
fetch: (url, init) => fetch(url, init),
|
|
27
|
+
manifest: [
|
|
28
|
+
{ id: "face", url: "/mediakit/face_landmarker.task" },
|
|
29
|
+
{ id: "background", url: "/backgrounds/office.jpg", cacheable: false },
|
|
30
|
+
],
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
await assets.purgeOld()
|
|
34
|
+
await assets.preload(["face"], (p) => show(p.ratio, p.loaded, p.total))
|
|
35
|
+
|
|
36
|
+
const face = await assets.acquire("face", {
|
|
37
|
+
build: (bytes) => FaceLandmarker.createFromOptions(fileset, { baseOptions: { modelAssetBuffer: bytes } }),
|
|
38
|
+
dispose: (landmarker) => landmarker.close(),
|
|
39
|
+
})
|
|
40
|
+
face.release()
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
- `fetch` is required. The kit never calls the global `fetch`: the app decides how requests go out.
|
|
44
|
+
- Bytes live in Cache Storage under `<name>-v<version>`; `purgeOld()` deletes the other versions of
|
|
45
|
+
the same name. Where Cache Storage is missing or refuses to open (not a secure context, an
|
|
46
|
+
AudioWorklet, some private modes) they stay in memory for the page; `usage().store` says which.
|
|
47
|
+
- `acquire` builds once for every holder. After the last `release` the value is kept for `keepMs`
|
|
48
|
+
(default 30 s, 0 when `navigator.deviceMemory` is 4 or less) and then disposed. A wasm runtime
|
|
49
|
+
does not reliably return its memory on `dispose`; terminate the worker that holds it there.
|
|
50
|
+
- `acquire` of an id already being built or held joins it: the runtime passed first is the one
|
|
51
|
+
used. Every caller after the first gets its own copy from `bytes`, so transferring one copy to a
|
|
52
|
+
worker does not empty another.
|
|
53
|
+
- `state(id).phase` is `idle`, `fetching`, `building`, `ready`, `kept` or `failed`, with `error`
|
|
54
|
+
for the last; an abort goes back to `idle`, not `failed`. `state(id)` and `snapshot()` return the
|
|
55
|
+
same frozen object until something changes, so either can be the `getSnapshot` of
|
|
56
|
+
`useSyncExternalStore` with `subscribe`.
|
|
57
|
+
- A download shared by several callers stops only when every one of them has aborted.
|
|
58
|
+
|
|
59
|
+
## Progress
|
|
60
|
+
|
|
61
|
+
`total` is 0 until every item has a size, and stays 0 when one has none (no `Content-Length`, or a
|
|
62
|
+
compressed response); show `done`/`items` then. `loaded` never passes a known `total`, and drops
|
|
63
|
+
when a download breaks off. A failed item counts as done and adds no bytes. Listeners are called
|
|
64
|
+
at most every 100 ms for bytes and at once for phase changes; one that throws is removed.
|
|
65
|
+
`ratio` counts a building item as 0.9.
|
|
66
|
+
|
|
67
|
+
## Fetch
|
|
68
|
+
|
|
69
|
+
`fetchBytes(url, { fetch })` retries network errors, 5xx, 408 and 429 with a doubling backoff
|
|
70
|
+
(default 2 retries from 500 ms), never 4xx. It gives up when no byte arrives for `stallMs`
|
|
71
|
+
(default 15 s) rather than after a fixed total time. With `sha256` a mismatch fails at once.
|
|
72
|
+
Errors are `FetchError` with `failure` (`status`, `network`, `stall`, `integrity`, `aborted`),
|
|
73
|
+
`retryable` and `status`.
|
package/dist/assets.d.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { ByteStore, StorageUsage } from './cache.js';
|
|
2
|
+
import { FetchLike } from './fetch.js';
|
|
3
|
+
export { FetchError } from './fetch.js';
|
|
4
|
+
import { ProgressItem, Progress } from './progress.js';
|
|
5
|
+
export { ItemProgress } from './progress.js';
|
|
6
|
+
import { Retained } from './retain.js';
|
|
7
|
+
|
|
8
|
+
interface AssetSpec {
|
|
9
|
+
id: string;
|
|
10
|
+
url: string;
|
|
11
|
+
size?: number;
|
|
12
|
+
sha256?: string;
|
|
13
|
+
type?: string;
|
|
14
|
+
cacheable?: boolean;
|
|
15
|
+
group?: string;
|
|
16
|
+
}
|
|
17
|
+
interface Runtime<V> {
|
|
18
|
+
build(bytes: Uint8Array, ctx: {
|
|
19
|
+
id: string;
|
|
20
|
+
signal: AbortSignal;
|
|
21
|
+
}): Promise<V>;
|
|
22
|
+
dispose(value: V): void | Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
type AssetPhase = "idle" | "fetching" | "building" | "ready" | "kept" | "failed";
|
|
25
|
+
interface AssetState {
|
|
26
|
+
phase: AssetPhase;
|
|
27
|
+
loaded: number;
|
|
28
|
+
size: number | null | undefined;
|
|
29
|
+
cached: boolean;
|
|
30
|
+
error: string;
|
|
31
|
+
}
|
|
32
|
+
interface AssetsOptions {
|
|
33
|
+
manifest: readonly AssetSpec[];
|
|
34
|
+
fetch: FetchLike;
|
|
35
|
+
name: string;
|
|
36
|
+
version: string;
|
|
37
|
+
store?: ByteStore;
|
|
38
|
+
caches?: CacheStorage | null;
|
|
39
|
+
keepMs?: number;
|
|
40
|
+
stallMs?: number;
|
|
41
|
+
retries?: number;
|
|
42
|
+
}
|
|
43
|
+
type AssetsListener = () => void;
|
|
44
|
+
declare function defaultKeepMs(deviceMemory?: number): number;
|
|
45
|
+
declare class Assets {
|
|
46
|
+
private readonly opts;
|
|
47
|
+
private readonly specs;
|
|
48
|
+
private readonly states;
|
|
49
|
+
private readonly listeners;
|
|
50
|
+
private readonly runtimes;
|
|
51
|
+
private readonly sinks;
|
|
52
|
+
private readonly stamps;
|
|
53
|
+
private readonly views;
|
|
54
|
+
private readonly given;
|
|
55
|
+
private readonly retainer;
|
|
56
|
+
private readonly downloads;
|
|
57
|
+
private readonly store;
|
|
58
|
+
private rev;
|
|
59
|
+
private snap;
|
|
60
|
+
constructor(opts: AssetsOptions);
|
|
61
|
+
spec(id: string): AssetSpec;
|
|
62
|
+
state(id: string): Readonly<AssetState>;
|
|
63
|
+
snapshot(): Readonly<Record<string, Readonly<AssetState>>>;
|
|
64
|
+
get revision(): number;
|
|
65
|
+
subscribe(listener: AssetsListener): () => void;
|
|
66
|
+
bytes(id: string, signal?: AbortSignal, item?: ProgressItem): Promise<Uint8Array>;
|
|
67
|
+
acquire<V>(id: string, runtime: Runtime<V>, signal?: AbortSignal): Promise<Retained<V>>;
|
|
68
|
+
preload(ids: readonly string[], onProgress?: (p: Progress) => void, signal?: AbortSignal): Promise<Progress>;
|
|
69
|
+
progress(ids?: readonly string[]): Progress;
|
|
70
|
+
usage(): Promise<StorageUsage & {
|
|
71
|
+
store: ByteStore["kind"];
|
|
72
|
+
cached: string[];
|
|
73
|
+
}>;
|
|
74
|
+
purgeOld(): Promise<string[]>;
|
|
75
|
+
clear(): Promise<void>;
|
|
76
|
+
private download;
|
|
77
|
+
private create;
|
|
78
|
+
private set;
|
|
79
|
+
private emit;
|
|
80
|
+
}
|
|
81
|
+
declare function createAssets(opts: AssetsOptions): Assets;
|
|
82
|
+
|
|
83
|
+
export { type AssetPhase, type AssetSpec, type AssetState, Assets, type AssetsListener, type AssetsOptions, Progress, Retained, type Runtime, createAssets, defaultKeepMs };
|
package/dist/assets.js
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ProgressTracker
|
|
3
|
+
} from "./chunk-CPL35ABZ.js";
|
|
4
|
+
import {
|
|
5
|
+
Retainer
|
|
6
|
+
} from "./chunk-JRWPS4OS.js";
|
|
7
|
+
import {
|
|
8
|
+
FetchError,
|
|
9
|
+
fetchBytes
|
|
10
|
+
} from "./chunk-ZPGZZXHR.js";
|
|
11
|
+
import {
|
|
12
|
+
openByteStore,
|
|
13
|
+
storageUsage
|
|
14
|
+
} from "./chunk-UUTOMKU7.js";
|
|
15
|
+
|
|
16
|
+
// src/assets.ts
|
|
17
|
+
var LOW_MEMORY_GB = 4;
|
|
18
|
+
var KEEP_MS = 3e4;
|
|
19
|
+
function defaultKeepMs(deviceMemory) {
|
|
20
|
+
const gb = deviceMemory ?? globalThis.navigator?.deviceMemory;
|
|
21
|
+
return typeof gb === "number" && gb <= LOW_MEMORY_GB ? 0 : KEEP_MS;
|
|
22
|
+
}
|
|
23
|
+
var Assets = class {
|
|
24
|
+
constructor(opts) {
|
|
25
|
+
this.opts = opts;
|
|
26
|
+
for (const s of opts.manifest) {
|
|
27
|
+
if (this.specs.has(s.id)) throw new Error(`tskit: asset ${s.id} is declared twice`);
|
|
28
|
+
this.specs.set(s.id, s);
|
|
29
|
+
this.states.set(s.id, { phase: "idle", loaded: 0, size: s.size, cached: false, error: "" });
|
|
30
|
+
this.stamps.set(s.id, 0);
|
|
31
|
+
}
|
|
32
|
+
this.store = opts.store ? Promise.resolve(opts.store) : openByteStore({ name: opts.name, version: opts.version, caches: opts.caches });
|
|
33
|
+
this.retainer = new Retainer({
|
|
34
|
+
keepMs: opts.keepMs ?? defaultKeepMs(),
|
|
35
|
+
create: (id, signal) => this.create(id, signal),
|
|
36
|
+
dispose: async (value, id) => {
|
|
37
|
+
const rt = this.runtimes.get(id);
|
|
38
|
+
this.runtimes.delete(id);
|
|
39
|
+
this.set(id, { phase: "idle", loaded: 0 });
|
|
40
|
+
await rt?.dispose(value);
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
this.downloads = new Retainer({
|
|
44
|
+
create: (id, signal) => this.download(this.spec(id), signal),
|
|
45
|
+
dispose: () => {
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
opts;
|
|
50
|
+
specs = /* @__PURE__ */ new Map();
|
|
51
|
+
states = /* @__PURE__ */ new Map();
|
|
52
|
+
listeners = /* @__PURE__ */ new Set();
|
|
53
|
+
runtimes = /* @__PURE__ */ new Map();
|
|
54
|
+
sinks = /* @__PURE__ */ new Map();
|
|
55
|
+
stamps = /* @__PURE__ */ new Map();
|
|
56
|
+
views = /* @__PURE__ */ new Map();
|
|
57
|
+
given = /* @__PURE__ */ new WeakSet();
|
|
58
|
+
retainer;
|
|
59
|
+
downloads;
|
|
60
|
+
store;
|
|
61
|
+
rev = 0;
|
|
62
|
+
snap = null;
|
|
63
|
+
spec(id) {
|
|
64
|
+
const s = this.specs.get(id);
|
|
65
|
+
if (!s) throw new Error(`tskit: asset ${id} is not in the manifest`);
|
|
66
|
+
return s;
|
|
67
|
+
}
|
|
68
|
+
state(id) {
|
|
69
|
+
this.spec(id);
|
|
70
|
+
const s = this.states.get(id);
|
|
71
|
+
const kept = s.phase === "ready" && this.retainer.state(id) === "kept";
|
|
72
|
+
const key = `${this.stamps.get(id)}:${kept}`;
|
|
73
|
+
const cached = this.views.get(id);
|
|
74
|
+
if (cached && cached.key === key) return cached.view;
|
|
75
|
+
const view = Object.freeze({ ...s, phase: kept ? "kept" : s.phase });
|
|
76
|
+
this.views.set(id, { key, view });
|
|
77
|
+
return view;
|
|
78
|
+
}
|
|
79
|
+
snapshot() {
|
|
80
|
+
if (this.snap && this.snap.rev === this.rev) return this.snap.view;
|
|
81
|
+
const out = {};
|
|
82
|
+
for (const id of this.specs.keys()) out[id] = this.state(id);
|
|
83
|
+
this.snap = { rev: this.rev, view: Object.freeze(out) };
|
|
84
|
+
return this.snap.view;
|
|
85
|
+
}
|
|
86
|
+
get revision() {
|
|
87
|
+
return this.rev;
|
|
88
|
+
}
|
|
89
|
+
subscribe(listener) {
|
|
90
|
+
this.listeners.add(listener);
|
|
91
|
+
return () => this.listeners.delete(listener);
|
|
92
|
+
}
|
|
93
|
+
async bytes(id, signal, item) {
|
|
94
|
+
const spec = this.spec(id);
|
|
95
|
+
if (spec.cacheable !== false) {
|
|
96
|
+
const hit = await (await this.store).get(id);
|
|
97
|
+
if (hit) {
|
|
98
|
+
this.set(id, { cached: true, size: hit.byteLength, loaded: hit.byteLength });
|
|
99
|
+
item?.size(hit.byteLength);
|
|
100
|
+
item?.bytes(hit.byteLength);
|
|
101
|
+
return hit;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
let sinks = this.sinks.get(id);
|
|
105
|
+
if (!sinks) this.sinks.set(id, sinks = /* @__PURE__ */ new Set());
|
|
106
|
+
if (item) {
|
|
107
|
+
const now = this.states.get(id);
|
|
108
|
+
if (this.downloads.state(id) === "creating") {
|
|
109
|
+
if (typeof now.size === "number" || now.size === null) item.size(now.size);
|
|
110
|
+
if (now.loaded > 0) item.bytes(now.loaded);
|
|
111
|
+
}
|
|
112
|
+
sinks.add(item);
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
const h = await this.downloads.acquire(id, signal);
|
|
116
|
+
const bytes = h.value;
|
|
117
|
+
h.release();
|
|
118
|
+
if (this.given.has(bytes)) return bytes.slice();
|
|
119
|
+
this.given.add(bytes);
|
|
120
|
+
return bytes;
|
|
121
|
+
} finally {
|
|
122
|
+
if (item) sinks.delete(item);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
async acquire(id, runtime, signal) {
|
|
126
|
+
this.spec(id);
|
|
127
|
+
if (!this.runtimes.has(id)) this.runtimes.set(id, runtime);
|
|
128
|
+
const h = await this.retainer.acquire(id, signal);
|
|
129
|
+
this.emit();
|
|
130
|
+
let released = false;
|
|
131
|
+
return {
|
|
132
|
+
value: h.value,
|
|
133
|
+
release: () => {
|
|
134
|
+
if (released) return;
|
|
135
|
+
released = true;
|
|
136
|
+
h.release();
|
|
137
|
+
this.emit();
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
async preload(ids, onProgress, signal) {
|
|
142
|
+
const tracker = new ProgressTracker();
|
|
143
|
+
const stop = onProgress ? tracker.subscribe(onProgress) : () => {
|
|
144
|
+
};
|
|
145
|
+
try {
|
|
146
|
+
await Promise.all(
|
|
147
|
+
ids.map(async (id) => {
|
|
148
|
+
const item = tracker.item(id, this.spec(id).size);
|
|
149
|
+
try {
|
|
150
|
+
await this.bytes(id, signal, item);
|
|
151
|
+
item.ready();
|
|
152
|
+
} catch (err) {
|
|
153
|
+
item.fail(err instanceof Error ? err.message : String(err));
|
|
154
|
+
}
|
|
155
|
+
})
|
|
156
|
+
);
|
|
157
|
+
return tracker.snapshot();
|
|
158
|
+
} finally {
|
|
159
|
+
stop();
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
progress(ids = [...this.specs.keys()]) {
|
|
163
|
+
const tracker = new ProgressTracker();
|
|
164
|
+
for (const id of ids) {
|
|
165
|
+
const s = this.states.get(id);
|
|
166
|
+
if (!s) continue;
|
|
167
|
+
const item = tracker.item(id, s.size);
|
|
168
|
+
if (s.loaded) item.bytes(s.loaded);
|
|
169
|
+
if (s.phase === "building") item.building();
|
|
170
|
+
if (s.phase === "ready" || s.phase === "idle" && s.cached) item.ready();
|
|
171
|
+
if (s.phase === "failed") item.fail(s.error);
|
|
172
|
+
}
|
|
173
|
+
return tracker.snapshot();
|
|
174
|
+
}
|
|
175
|
+
async usage() {
|
|
176
|
+
const store = await this.store;
|
|
177
|
+
const [u, cached] = await Promise.all([storageUsage(), store.keys()]);
|
|
178
|
+
return { ...u, store: store.kind, cached };
|
|
179
|
+
}
|
|
180
|
+
async purgeOld() {
|
|
181
|
+
return (await this.store).purgeOld();
|
|
182
|
+
}
|
|
183
|
+
async clear() {
|
|
184
|
+
await this.downloads.clear();
|
|
185
|
+
await this.retainer.clear();
|
|
186
|
+
await (await this.store).clear();
|
|
187
|
+
for (const id of this.specs.keys()) this.set(id, { phase: "idle", loaded: 0, cached: false, error: "" });
|
|
188
|
+
}
|
|
189
|
+
async download(spec, signal) {
|
|
190
|
+
const id = spec.id;
|
|
191
|
+
const sinks = () => this.sinks.get(id) ?? /* @__PURE__ */ new Set();
|
|
192
|
+
this.set(id, { phase: "fetching", loaded: 0, error: "" });
|
|
193
|
+
let bytes;
|
|
194
|
+
try {
|
|
195
|
+
bytes = await fetchBytes(spec.url, {
|
|
196
|
+
fetch: this.opts.fetch,
|
|
197
|
+
signal,
|
|
198
|
+
sha256: spec.sha256,
|
|
199
|
+
stallMs: this.opts.stallMs,
|
|
200
|
+
retries: this.opts.retries,
|
|
201
|
+
onSize: (n) => {
|
|
202
|
+
const size = n ?? (spec.size === void 0 ? null : spec.size);
|
|
203
|
+
for (const it of sinks()) it.size(size);
|
|
204
|
+
this.set(id, { size });
|
|
205
|
+
},
|
|
206
|
+
onBytes: (n) => {
|
|
207
|
+
for (const it of sinks()) {
|
|
208
|
+
if (n < 0) it.rollback();
|
|
209
|
+
else it.bytes(n);
|
|
210
|
+
}
|
|
211
|
+
this.set(id, { loaded: Math.max(0, this.states.get(id).loaded + n) });
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
} catch (err) {
|
|
215
|
+
if (isAbort(err, signal)) this.set(id, { phase: "idle", loaded: 0, error: "" });
|
|
216
|
+
else this.set(id, { phase: "failed", loaded: 0, error: describe(err) });
|
|
217
|
+
throw err;
|
|
218
|
+
}
|
|
219
|
+
const next = this.retainer.state(id) === "creating" ? "building" : "idle";
|
|
220
|
+
this.set(id, { phase: next, size: bytes.byteLength, loaded: bytes.byteLength });
|
|
221
|
+
if (spec.cacheable !== false) {
|
|
222
|
+
try {
|
|
223
|
+
await (await this.store).put(id, bytes, spec.type);
|
|
224
|
+
this.set(id, { cached: true });
|
|
225
|
+
} catch (err) {
|
|
226
|
+
console.warn(`tskit: could not cache ${id}`, err);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return bytes;
|
|
230
|
+
}
|
|
231
|
+
async create(id, signal) {
|
|
232
|
+
const rt = this.runtimes.get(id);
|
|
233
|
+
if (!rt) throw new Error(`tskit: no runtime for ${id}`);
|
|
234
|
+
try {
|
|
235
|
+
this.set(id, { phase: "fetching", error: "" });
|
|
236
|
+
const bytes = await this.bytes(id, signal);
|
|
237
|
+
this.set(id, { phase: "building" });
|
|
238
|
+
const value = await rt.build(bytes, { id, signal });
|
|
239
|
+
this.set(id, { phase: "ready" });
|
|
240
|
+
return value;
|
|
241
|
+
} catch (err) {
|
|
242
|
+
this.runtimes.delete(id);
|
|
243
|
+
if (isAbort(err, signal)) this.set(id, { phase: "idle", error: "" });
|
|
244
|
+
else this.set(id, { phase: "failed", error: describe(err) });
|
|
245
|
+
throw err;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
set(id, patch) {
|
|
249
|
+
const s = this.states.get(id);
|
|
250
|
+
if (!s) return;
|
|
251
|
+
Object.assign(s, patch);
|
|
252
|
+
this.stamps.set(id, (this.stamps.get(id) ?? 0) + 1);
|
|
253
|
+
this.emit();
|
|
254
|
+
}
|
|
255
|
+
emit() {
|
|
256
|
+
this.rev++;
|
|
257
|
+
for (const l of [...this.listeners]) {
|
|
258
|
+
try {
|
|
259
|
+
l();
|
|
260
|
+
} catch (err) {
|
|
261
|
+
this.listeners.delete(l);
|
|
262
|
+
console.error("tskit: an assets listener threw and was removed", err);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
function createAssets(opts) {
|
|
268
|
+
return new Assets(opts);
|
|
269
|
+
}
|
|
270
|
+
function isAbort(err, signal) {
|
|
271
|
+
if (signal.aborted) return true;
|
|
272
|
+
if (err instanceof FetchError) return err.failure === "aborted";
|
|
273
|
+
return err instanceof DOMException && err.name === "AbortError";
|
|
274
|
+
}
|
|
275
|
+
function describe(err) {
|
|
276
|
+
if (err instanceof Error) return err.message;
|
|
277
|
+
return String(err);
|
|
278
|
+
}
|
|
279
|
+
export {
|
|
280
|
+
Assets,
|
|
281
|
+
FetchError,
|
|
282
|
+
createAssets,
|
|
283
|
+
defaultKeepMs
|
|
284
|
+
};
|
|
285
|
+
//# sourceMappingURL=assets.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/assets.ts"],"sourcesContent":["import { openByteStore, storageUsage, type ByteStore, type StorageUsage } from \"./cache\"\nimport { fetchBytes, FetchError, type FetchLike } from \"./fetch\"\nimport { ProgressTracker, type ItemProgress, type Progress, type ProgressItem } from \"./progress\"\nimport { Retainer, type Retained } from \"./retain\"\n\nexport interface AssetSpec {\n id: string\n url: string\n size?: number\n sha256?: string\n type?: string\n cacheable?: boolean\n group?: string\n}\n\nexport interface Runtime<V> {\n build(bytes: Uint8Array, ctx: { id: string; signal: AbortSignal }): Promise<V>\n dispose(value: V): void | Promise<void>\n}\n\nexport type AssetPhase = \"idle\" | \"fetching\" | \"building\" | \"ready\" | \"kept\" | \"failed\"\n\nexport interface AssetState {\n phase: AssetPhase\n loaded: number\n size: number | null | undefined\n cached: boolean\n error: string\n}\n\nexport interface AssetsOptions {\n manifest: readonly AssetSpec[]\n fetch: FetchLike\n name: string\n version: string\n store?: ByteStore\n caches?: CacheStorage | null\n keepMs?: number\n stallMs?: number\n retries?: number\n}\n\nexport type AssetsListener = () => void\n\nconst LOW_MEMORY_GB = 4\nconst KEEP_MS = 30_000\n\nexport function defaultKeepMs(deviceMemory?: number): number {\n const gb = deviceMemory ?? (globalThis as { navigator?: { deviceMemory?: number } }).navigator?.deviceMemory\n return typeof gb === \"number\" && gb <= LOW_MEMORY_GB ? 0 : KEEP_MS\n}\n\nexport class Assets {\n private readonly specs = new Map<string, AssetSpec>()\n private readonly states = new Map<string, AssetState>()\n private readonly listeners = new Set<AssetsListener>()\n private readonly runtimes = new Map<string, Runtime<unknown>>()\n private readonly sinks = new Map<string, Set<ProgressItem>>()\n private readonly stamps = new Map<string, number>()\n private readonly views = new Map<string, { key: string; view: Readonly<AssetState> }>()\n private readonly given = new WeakSet<Uint8Array>()\n private readonly retainer: Retainer<unknown>\n private readonly downloads: Retainer<Uint8Array>\n private readonly store: Promise<ByteStore>\n private rev = 0\n private snap: { rev: number; view: Readonly<Record<string, Readonly<AssetState>>> } | null = null\n\n constructor(private readonly opts: AssetsOptions) {\n for (const s of opts.manifest) {\n if (this.specs.has(s.id)) throw new Error(`tskit: asset ${s.id} is declared twice`)\n this.specs.set(s.id, s)\n this.states.set(s.id, { phase: \"idle\", loaded: 0, size: s.size, cached: false, error: \"\" })\n this.stamps.set(s.id, 0)\n }\n this.store = opts.store ? Promise.resolve(opts.store) : openByteStore({ name: opts.name, version: opts.version, caches: opts.caches })\n this.retainer = new Retainer<unknown>({\n keepMs: opts.keepMs ?? defaultKeepMs(),\n create: (id, signal) => this.create(id, signal),\n dispose: async (value, id) => {\n const rt = this.runtimes.get(id)\n this.runtimes.delete(id)\n this.set(id, { phase: \"idle\", loaded: 0 })\n await rt?.dispose(value)\n },\n })\n this.downloads = new Retainer<Uint8Array>({\n create: (id, signal) => this.download(this.spec(id), signal),\n dispose: () => {},\n })\n }\n\n spec(id: string): AssetSpec {\n const s = this.specs.get(id)\n if (!s) throw new Error(`tskit: asset ${id} is not in the manifest`)\n return s\n }\n\n state(id: string): Readonly<AssetState> {\n this.spec(id)\n const s = this.states.get(id)!\n const kept = s.phase === \"ready\" && this.retainer.state(id) === \"kept\"\n const key = `${this.stamps.get(id)}:${kept}`\n const cached = this.views.get(id)\n if (cached && cached.key === key) return cached.view\n const view = Object.freeze({ ...s, phase: kept ? \"kept\" : s.phase })\n this.views.set(id, { key, view })\n return view\n }\n\n snapshot(): Readonly<Record<string, Readonly<AssetState>>> {\n if (this.snap && this.snap.rev === this.rev) return this.snap.view\n const out: Record<string, Readonly<AssetState>> = {}\n for (const id of this.specs.keys()) out[id] = this.state(id)\n this.snap = { rev: this.rev, view: Object.freeze(out) }\n return this.snap.view\n }\n\n get revision(): number {\n return this.rev\n }\n\n subscribe(listener: AssetsListener): () => void {\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n async bytes(id: string, signal?: AbortSignal, item?: ProgressItem): Promise<Uint8Array> {\n const spec = this.spec(id)\n if (spec.cacheable !== false) {\n const hit = await (await this.store).get(id)\n if (hit) {\n this.set(id, { cached: true, size: hit.byteLength, loaded: hit.byteLength })\n item?.size(hit.byteLength)\n item?.bytes(hit.byteLength)\n return hit\n }\n }\n let sinks = this.sinks.get(id)\n if (!sinks) this.sinks.set(id, (sinks = new Set()))\n if (item) {\n const now = this.states.get(id)!\n if (this.downloads.state(id) === \"creating\") {\n if (typeof now.size === \"number\" || now.size === null) item.size(now.size)\n if (now.loaded > 0) item.bytes(now.loaded)\n }\n sinks.add(item)\n }\n try {\n const h = await this.downloads.acquire(id, signal)\n const bytes = h.value\n h.release()\n if (this.given.has(bytes)) return bytes.slice()\n this.given.add(bytes)\n return bytes\n } finally {\n if (item) sinks.delete(item)\n }\n }\n\n async acquire<V>(id: string, runtime: Runtime<V>, signal?: AbortSignal): Promise<Retained<V>> {\n this.spec(id)\n if (!this.runtimes.has(id)) this.runtimes.set(id, runtime as Runtime<unknown>)\n const h = await this.retainer.acquire(id, signal)\n this.emit()\n let released = false\n return {\n value: h.value as V,\n release: () => {\n if (released) return\n released = true\n h.release()\n this.emit()\n },\n }\n }\n\n async preload(ids: readonly string[], onProgress?: (p: Progress) => void, signal?: AbortSignal): Promise<Progress> {\n const tracker = new ProgressTracker()\n const stop = onProgress ? tracker.subscribe(onProgress) : () => {}\n try {\n await Promise.all(\n ids.map(async (id) => {\n const item = tracker.item(id, this.spec(id).size)\n try {\n await this.bytes(id, signal, item)\n item.ready()\n } catch (err) {\n item.fail(err instanceof Error ? err.message : String(err))\n }\n }),\n )\n return tracker.snapshot()\n } finally {\n stop()\n }\n }\n\n progress(ids: readonly string[] = [...this.specs.keys()]): Progress {\n const tracker = new ProgressTracker()\n for (const id of ids) {\n const s = this.states.get(id)\n if (!s) continue\n const item = tracker.item(id, s.size)\n if (s.loaded) item.bytes(s.loaded)\n if (s.phase === \"building\") item.building()\n if (s.phase === \"ready\" || (s.phase === \"idle\" && s.cached)) item.ready()\n if (s.phase === \"failed\") item.fail(s.error)\n }\n return tracker.snapshot()\n }\n\n async usage(): Promise<StorageUsage & { store: ByteStore[\"kind\"]; cached: string[] }> {\n const store = await this.store\n const [u, cached] = await Promise.all([storageUsage(), store.keys()])\n return { ...u, store: store.kind, cached }\n }\n\n async purgeOld(): Promise<string[]> {\n return (await this.store).purgeOld()\n }\n\n async clear(): Promise<void> {\n await this.downloads.clear()\n await this.retainer.clear()\n await (await this.store).clear()\n for (const id of this.specs.keys()) this.set(id, { phase: \"idle\", loaded: 0, cached: false, error: \"\" })\n }\n\n private async download(spec: AssetSpec, signal: AbortSignal): Promise<Uint8Array> {\n const id = spec.id\n const sinks = () => this.sinks.get(id) ?? new Set<ProgressItem>()\n this.set(id, { phase: \"fetching\", loaded: 0, error: \"\" })\n let bytes: Uint8Array\n try {\n bytes = await fetchBytes(spec.url, {\n fetch: this.opts.fetch,\n signal,\n sha256: spec.sha256,\n stallMs: this.opts.stallMs,\n retries: this.opts.retries,\n onSize: (n) => {\n const size = n ?? (spec.size === undefined ? null : spec.size)\n for (const it of sinks()) it.size(size)\n this.set(id, { size })\n },\n onBytes: (n) => {\n for (const it of sinks()) {\n if (n < 0) it.rollback()\n else it.bytes(n)\n }\n this.set(id, { loaded: Math.max(0, this.states.get(id)!.loaded + n) })\n },\n })\n } catch (err) {\n if (isAbort(err, signal)) this.set(id, { phase: \"idle\", loaded: 0, error: \"\" })\n else this.set(id, { phase: \"failed\", loaded: 0, error: describe(err) })\n throw err\n }\n const next = this.retainer.state(id) === \"creating\" ? \"building\" : \"idle\"\n this.set(id, { phase: next, size: bytes.byteLength, loaded: bytes.byteLength })\n if (spec.cacheable !== false) {\n try {\n await (await this.store).put(id, bytes, spec.type)\n this.set(id, { cached: true })\n } catch (err) {\n console.warn(`tskit: could not cache ${id}`, err)\n }\n }\n return bytes\n }\n\n private async create(id: string, signal: AbortSignal): Promise<unknown> {\n const rt = this.runtimes.get(id)\n if (!rt) throw new Error(`tskit: no runtime for ${id}`)\n try {\n this.set(id, { phase: \"fetching\", error: \"\" })\n const bytes = await this.bytes(id, signal)\n this.set(id, { phase: \"building\" })\n const value = await rt.build(bytes, { id, signal })\n this.set(id, { phase: \"ready\" })\n return value\n } catch (err) {\n this.runtimes.delete(id)\n if (isAbort(err, signal)) this.set(id, { phase: \"idle\", error: \"\" })\n else this.set(id, { phase: \"failed\", error: describe(err) })\n throw err\n }\n }\n\n private set(id: string, patch: Partial<AssetState>) {\n const s = this.states.get(id)\n if (!s) return\n Object.assign(s, patch)\n this.stamps.set(id, (this.stamps.get(id) ?? 0) + 1)\n this.emit()\n }\n\n private emit() {\n this.rev++\n for (const l of [...this.listeners]) {\n try {\n l()\n } catch (err) {\n this.listeners.delete(l)\n console.error(\"tskit: an assets listener threw and was removed\", err)\n }\n }\n }\n}\n\nexport function createAssets(opts: AssetsOptions): Assets {\n return new Assets(opts)\n}\n\nexport { FetchError }\nexport type { ItemProgress, Progress, Retained }\n\nfunction isAbort(err: unknown, signal: AbortSignal): boolean {\n if (signal.aborted) return true\n if (err instanceof FetchError) return err.failure === \"aborted\"\n return err instanceof DOMException && err.name === \"AbortError\"\n}\n\nfunction describe(err: unknown): string {\n if (err instanceof Error) return err.message\n return String(err)\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4CA,IAAM,gBAAgB;AACtB,IAAM,UAAU;AAET,SAAS,cAAc,cAA+B;AACzD,QAAM,KAAK,gBAAiB,WAAyD,WAAW;AAChG,SAAO,OAAO,OAAO,YAAY,MAAM,gBAAgB,IAAI;AAC/D;AAEO,IAAM,SAAN,MAAa;AAAA,EAehB,YAA6B,MAAqB;AAArB;AACzB,eAAW,KAAK,KAAK,UAAU;AAC3B,UAAI,KAAK,MAAM,IAAI,EAAE,EAAE,EAAG,OAAM,IAAI,MAAM,gBAAgB,EAAE,EAAE,oBAAoB;AAClF,WAAK,MAAM,IAAI,EAAE,IAAI,CAAC;AACtB,WAAK,OAAO,IAAI,EAAE,IAAI,EAAE,OAAO,QAAQ,QAAQ,GAAG,MAAM,EAAE,MAAM,QAAQ,OAAO,OAAO,GAAG,CAAC;AAC1F,WAAK,OAAO,IAAI,EAAE,IAAI,CAAC;AAAA,IAC3B;AACA,SAAK,QAAQ,KAAK,QAAQ,QAAQ,QAAQ,KAAK,KAAK,IAAI,cAAc,EAAE,MAAM,KAAK,MAAM,SAAS,KAAK,SAAS,QAAQ,KAAK,OAAO,CAAC;AACrI,SAAK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CAAC,EAAG;AACR,WAAO,OAAO,GAAG,KAAK;AACtB,SAAK,OAAO,IAAI,KAAK,KAAK,OAAO,IAAI,EAAE,KAAK,KAAK,CAAC;AAClD,SAAK,KAAK;AAAA,EACd;AAAA,EAEQ,OAAO;AACX,SAAK;AACL,eAAW,KAAK,CAAC,GAAG,KAAK,SAAS,GAAG;AACjC,UAAI;AACA,UAAE;AAAA,MACN,SAAS,KAAK;AACV,aAAK,UAAU,OAAO,CAAC;AACvB,gBAAQ,MAAM,mDAAmD,GAAG;AAAA,MACxE;AAAA,IACJ;AAAA,EACJ;AACJ;AAEO,SAAS,aAAa,MAA6B;AACtD,SAAO,IAAI,OAAO,IAAI;AAC1B;AAKA,SAAS,QAAQ,KAAc,QAA8B;AACzD,MAAI,OAAO,QAAS,QAAO;AAC3B,MAAI,eAAe,WAAY,QAAO,IAAI,YAAY;AACtD,SAAO,eAAe,gBAAgB,IAAI,SAAS;AACvD;AAEA,SAAS,SAAS,KAAsB;AACpC,MAAI,eAAe,MAAO,QAAO,IAAI;AACrC,SAAO,OAAO,GAAG;AACrB;","names":[]}
|
package/dist/cache.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
type StoreKind = "cache" | "memory";
|
|
2
|
+
interface ByteStore {
|
|
3
|
+
readonly kind: StoreKind;
|
|
4
|
+
readonly name: string;
|
|
5
|
+
get(key: string): Promise<Uint8Array | null>;
|
|
6
|
+
put(key: string, bytes: Uint8Array, type?: string): Promise<void>;
|
|
7
|
+
delete(key: string): Promise<boolean>;
|
|
8
|
+
keys(): Promise<string[]>;
|
|
9
|
+
clear(): Promise<void>;
|
|
10
|
+
purgeOld(): Promise<string[]>;
|
|
11
|
+
}
|
|
12
|
+
interface ByteStoreOptions {
|
|
13
|
+
name: string;
|
|
14
|
+
version: string;
|
|
15
|
+
caches?: CacheStorage | null;
|
|
16
|
+
}
|
|
17
|
+
interface StorageUsage {
|
|
18
|
+
usage: number | null;
|
|
19
|
+
quota: number | null;
|
|
20
|
+
persisted: boolean | null;
|
|
21
|
+
}
|
|
22
|
+
declare function cacheName(name: string, version: string): string;
|
|
23
|
+
declare function openByteStore(opts: ByteStoreOptions): Promise<ByteStore>;
|
|
24
|
+
declare function storageUsage(): Promise<StorageUsage>;
|
|
25
|
+
declare function requestPersistence(): Promise<boolean>;
|
|
26
|
+
|
|
27
|
+
export { type ByteStore, type ByteStoreOptions, type StorageUsage, type StoreKind, cacheName, openByteStore, requestPersistence, storageUsage };
|
package/dist/cache.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// src/progress.ts
|
|
2
|
+
var FETCH_SHARE = 0.9;
|
|
3
|
+
var DEFAULT_INTERVAL_MS = 100;
|
|
4
|
+
var EMPTY_PROGRESS = Object.freeze({ loaded: 0, total: 0, done: 0, failed: 0, building: 0, items: 0, ratio: 1 });
|
|
5
|
+
var ProgressTracker = class {
|
|
6
|
+
entries = /* @__PURE__ */ new Map();
|
|
7
|
+
listeners = /* @__PURE__ */ new Set();
|
|
8
|
+
intervalMs;
|
|
9
|
+
now;
|
|
10
|
+
told = Number.NEGATIVE_INFINITY;
|
|
11
|
+
constructor(opts = {}) {
|
|
12
|
+
this.intervalMs = opts.intervalMs ?? DEFAULT_INTERVAL_MS;
|
|
13
|
+
this.now = opts.now ?? (() => performance.now());
|
|
14
|
+
}
|
|
15
|
+
item(id, size) {
|
|
16
|
+
const e = { phase: "waiting", loaded: 0, size, error: "" };
|
|
17
|
+
this.entries.set(id, e);
|
|
18
|
+
this.tell(true);
|
|
19
|
+
const settled = () => e.phase === "ready" || e.phase === "failed";
|
|
20
|
+
return {
|
|
21
|
+
size: (bytes) => {
|
|
22
|
+
if (settled()) return;
|
|
23
|
+
e.size = bytes !== null && bytes >= 0 ? bytes : null;
|
|
24
|
+
this.tell(false);
|
|
25
|
+
},
|
|
26
|
+
bytes: (n) => {
|
|
27
|
+
if (settled()) return;
|
|
28
|
+
e.phase = "fetching";
|
|
29
|
+
e.loaded += n;
|
|
30
|
+
this.tell(false);
|
|
31
|
+
},
|
|
32
|
+
rollback: () => {
|
|
33
|
+
if (settled()) return;
|
|
34
|
+
e.loaded = 0;
|
|
35
|
+
this.tell(true);
|
|
36
|
+
},
|
|
37
|
+
building: () => {
|
|
38
|
+
if (settled()) return;
|
|
39
|
+
e.phase = "building";
|
|
40
|
+
this.tell(true);
|
|
41
|
+
},
|
|
42
|
+
ready: () => {
|
|
43
|
+
if (settled()) return;
|
|
44
|
+
e.phase = "ready";
|
|
45
|
+
this.tell(true);
|
|
46
|
+
},
|
|
47
|
+
fail: (reason) => {
|
|
48
|
+
if (settled()) return;
|
|
49
|
+
e.phase = "failed";
|
|
50
|
+
e.error = reason;
|
|
51
|
+
e.loaded = 0;
|
|
52
|
+
e.size = 0;
|
|
53
|
+
this.tell(true);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
get(id) {
|
|
58
|
+
return this.entries.get(id);
|
|
59
|
+
}
|
|
60
|
+
snapshot() {
|
|
61
|
+
const all = [...this.entries.values()];
|
|
62
|
+
if (all.length === 0) return { ...EMPTY_PROGRESS };
|
|
63
|
+
const known = all.every((e) => typeof e.size === "number");
|
|
64
|
+
const total = known ? all.reduce((a, e) => a + e.size, 0) : 0;
|
|
65
|
+
const raw = all.reduce((a, e) => a + e.loaded, 0);
|
|
66
|
+
let share = 0;
|
|
67
|
+
for (const e of all) share += itemRatio(e);
|
|
68
|
+
return {
|
|
69
|
+
loaded: total ? Math.min(raw, total) : raw,
|
|
70
|
+
total,
|
|
71
|
+
done: all.filter((e) => e.phase === "ready" || e.phase === "failed").length,
|
|
72
|
+
failed: all.filter((e) => e.phase === "failed").length,
|
|
73
|
+
building: all.filter((e) => e.phase === "building").length,
|
|
74
|
+
items: all.length,
|
|
75
|
+
ratio: share / all.length
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
subscribe(listener) {
|
|
79
|
+
this.listeners.add(listener);
|
|
80
|
+
return () => this.listeners.delete(listener);
|
|
81
|
+
}
|
|
82
|
+
tell(force) {
|
|
83
|
+
if (this.listeners.size === 0) return;
|
|
84
|
+
const t = this.now();
|
|
85
|
+
if (!force && t - this.told < this.intervalMs) return;
|
|
86
|
+
this.told = t;
|
|
87
|
+
const p = this.snapshot();
|
|
88
|
+
for (const l of [...this.listeners]) {
|
|
89
|
+
try {
|
|
90
|
+
l(p);
|
|
91
|
+
} catch (err) {
|
|
92
|
+
this.listeners.delete(l);
|
|
93
|
+
console.error("tskit: a progress listener threw and was removed", err);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
function itemRatio(e) {
|
|
99
|
+
if (e.phase === "ready" || e.phase === "failed") return 1;
|
|
100
|
+
if (e.phase === "building") return FETCH_SHARE;
|
|
101
|
+
if (typeof e.size === "number" && e.size > 0) return FETCH_SHARE * Math.min(1, e.loaded / e.size);
|
|
102
|
+
return 0;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export {
|
|
106
|
+
EMPTY_PROGRESS,
|
|
107
|
+
ProgressTracker
|
|
108
|
+
};
|
|
109
|
+
//# sourceMappingURL=chunk-CPL35ABZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/progress.ts"],"sourcesContent":["export type ItemPhase = \"waiting\" | \"fetching\" | \"building\" | \"ready\" | \"failed\"\n\nexport interface ItemProgress {\n phase: ItemPhase\n loaded: number\n size: number | null | undefined\n error: string\n}\n\nexport interface Progress {\n loaded: number\n total: number\n done: number\n failed: number\n building: number\n items: number\n ratio: number\n}\n\nexport interface ProgressItem {\n size(bytes: number | null): void\n bytes(n: number): void\n rollback(): void\n building(): void\n ready(): void\n fail(reason: string): void\n}\n\nexport interface TrackerOptions {\n intervalMs?: number\n now?: () => number\n}\n\nexport type ProgressListener = (p: Progress) => void\n\nconst FETCH_SHARE = 0.9\nconst DEFAULT_INTERVAL_MS = 100\n\nexport const EMPTY_PROGRESS: Readonly<Progress> = Object.freeze({ loaded: 0, total: 0, done: 0, failed: 0, building: 0, items: 0, ratio: 1 })\n\nexport class ProgressTracker {\n private readonly entries = new Map<string, ItemProgress>()\n private readonly listeners = new Set<ProgressListener>()\n private readonly intervalMs: number\n private readonly now: () => number\n private told = Number.NEGATIVE_INFINITY\n\n constructor(opts: TrackerOptions = {}) {\n this.intervalMs = opts.intervalMs ?? DEFAULT_INTERVAL_MS\n this.now = opts.now ?? (() => performance.now())\n }\n\n item(id: string, size?: number | null): ProgressItem {\n const e: ItemProgress = { phase: \"waiting\", loaded: 0, size, error: \"\" }\n this.entries.set(id, e)\n this.tell(true)\n const settled = () => e.phase === \"ready\" || e.phase === \"failed\"\n return {\n size: (bytes) => {\n if (settled()) return\n e.size = bytes !== null && bytes >= 0 ? bytes : null\n this.tell(false)\n },\n bytes: (n) => {\n if (settled()) return\n e.phase = \"fetching\"\n e.loaded += n\n this.tell(false)\n },\n rollback: () => {\n if (settled()) return\n e.loaded = 0\n this.tell(true)\n },\n building: () => {\n if (settled()) return\n e.phase = \"building\"\n this.tell(true)\n },\n ready: () => {\n if (settled()) return\n e.phase = \"ready\"\n this.tell(true)\n },\n fail: (reason) => {\n if (settled()) return\n e.phase = \"failed\"\n e.error = reason\n e.loaded = 0\n e.size = 0\n this.tell(true)\n },\n }\n }\n\n get(id: string): Readonly<ItemProgress> | undefined {\n return this.entries.get(id)\n }\n\n snapshot(): Progress {\n const all = [...this.entries.values()]\n if (all.length === 0) return { ...EMPTY_PROGRESS }\n const known = all.every((e) => typeof e.size === \"number\")\n const total = known ? all.reduce((a, e) => a + (e.size as number), 0) : 0\n const raw = all.reduce((a, e) => a + e.loaded, 0)\n let share = 0\n for (const e of all) share += itemRatio(e)\n return {\n loaded: total ? Math.min(raw, total) : raw,\n total,\n done: all.filter((e) => e.phase === \"ready\" || e.phase === \"failed\").length,\n failed: all.filter((e) => e.phase === \"failed\").length,\n building: all.filter((e) => e.phase === \"building\").length,\n items: all.length,\n ratio: share / all.length,\n }\n }\n\n subscribe(listener: ProgressListener): () => void {\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n private tell(force: boolean) {\n if (this.listeners.size === 0) return\n const t = this.now()\n if (!force && t - this.told < this.intervalMs) return\n this.told = t\n const p = this.snapshot()\n for (const l of [...this.listeners]) {\n try {\n l(p)\n } catch (err) {\n this.listeners.delete(l)\n console.error(\"tskit: a progress listener threw and was removed\", err)\n }\n }\n }\n}\n\nfunction itemRatio(e: ItemProgress): number {\n if (e.phase === \"ready\" || e.phase === \"failed\") return 1\n if (e.phase === \"building\") return FETCH_SHARE\n if (typeof e.size === \"number\" && e.size > 0) return FETCH_SHARE * Math.min(1, e.loaded / e.size)\n return 0\n}\n"],"mappings":";AAmCA,IAAM,cAAc;AACpB,IAAM,sBAAsB;AAErB,IAAM,iBAAqC,OAAO,OAAO,EAAE,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,QAAQ,GAAG,UAAU,GAAG,OAAO,GAAG,OAAO,EAAE,CAAC;AAErI,IAAM,kBAAN,MAAsB;AAAA,EACR,UAAU,oBAAI,IAA0B;AAAA,EACxC,YAAY,oBAAI,IAAsB;AAAA,EACtC;AAAA,EACA;AAAA,EACT,OAAO,OAAO;AAAA,EAEtB,YAAY,OAAuB,CAAC,GAAG;AACnC,SAAK,aAAa,KAAK,cAAc;AACrC,SAAK,MAAM,KAAK,QAAQ,MAAM,YAAY,IAAI;AAAA,EAClD;AAAA,EAEA,KAAK,IAAY,MAAoC;AACjD,UAAM,IAAkB,EAAE,OAAO,WAAW,QAAQ,GAAG,MAAM,OAAO,GAAG;AACvE,SAAK,QAAQ,IAAI,IAAI,CAAC;AACtB,SAAK,KAAK,IAAI;AACd,UAAM,UAAU,MAAM,EAAE,UAAU,WAAW,EAAE,UAAU;AACzD,WAAO;AAAA,MACH,MAAM,CAAC,UAAU;AACb,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