@margoengine/save 0.0.0-stage → 1.0.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/signed.js ADDED
@@ -0,0 +1,66 @@
1
+ import { t as e } from "./safe-DVo3kH0O.js";
2
+ import { MargoError as t } from "@margoengine/math/errors";
3
+ //#region src/signed.ts
4
+ var n = new Uint8Array([
5
+ 77,
6
+ 83,
7
+ 73,
8
+ 71,
9
+ 1
10
+ ]), r = 32, i = (e) => new t("failed", `Save '${e}' failed HMAC authentication; use the correct key or restore a trusted backup`);
11
+ function a(e, t) {
12
+ let r = new Uint8Array(n.length + 4 + e.length * 2 + t.length), i = new DataView(r.buffer);
13
+ r.set(n), i.setUint32(n.length, e.length * 2);
14
+ for (let t = 0; t < e.length; t++) i.setUint16(n.length + 4 + t * 2, e.charCodeAt(t));
15
+ return r.set(t, n.length + 4 + e.length * 2), r;
16
+ }
17
+ function o(o, s, c = {}) {
18
+ if (!o || ![
19
+ "read",
20
+ "write",
21
+ "delete",
22
+ "keys"
23
+ ].every((e) => typeof o[e] == "function")) throw TypeError("signedStorage needs a SaveStorage; pass memoryStorage or another storage adapter");
24
+ let l = s instanceof Uint8Array ? s.slice() : void 0;
25
+ if (l ? l.length < 32 : !((e) => {
26
+ let t = e?.algorithm;
27
+ return e?.type === "secret" && t?.name === "HMAC" && t.hash?.name === "SHA-256" && t.length >= 256 && e.usages.includes("sign") && e.usages.includes("verify");
28
+ })(s)) throw TypeError("signedStorage key must be 32 or more random bytes or a >=256-bit HMAC-SHA-256 CryptoKey with sign and verify usages; generate a suitable key");
29
+ let u, d = () => {
30
+ let e = c.subtle ?? globalThis.crypto?.subtle;
31
+ if (!e) throw new t("unsupported", "WebCrypto is unavailable; use a secure context or supply options.subtle");
32
+ return e;
33
+ }, f = (e) => (u ??= l ? e.importKey("raw", l, {
34
+ name: "HMAC",
35
+ hash: "SHA-256"
36
+ }, !1, ["sign", "verify"]) : Promise.resolve(s), u), { subtle: p, ...m } = c;
37
+ return e({
38
+ async read(e, t) {
39
+ t?.signal?.throwIfAborted();
40
+ let s = await o.read(e, t);
41
+ if (t?.signal?.throwIfAborted(), s === null) return null;
42
+ if (s.length < n.length + r || !n.every((e, t) => e === s[t])) throw i(e);
43
+ let c = s.slice(n.length + r), l = d(), u = await f(l);
44
+ t?.signal?.throwIfAborted();
45
+ let p = await l.verify("HMAC", u, s.slice(n.length, n.length + r), a(e, c));
46
+ if (t?.signal?.throwIfAborted(), !p) throw i(e);
47
+ return c;
48
+ },
49
+ async write(e, t, i) {
50
+ i?.signal?.throwIfAborted();
51
+ let s = t.slice(), c = d(), l = await f(c);
52
+ i?.signal?.throwIfAborted();
53
+ let u = new Uint8Array(await c.sign("HMAC", l, a(e, s)));
54
+ i?.signal?.throwIfAborted();
55
+ let p = new Uint8Array(n.length + r + s.length);
56
+ p.set(n), p.set(u, n.length), p.set(s, n.length + r), await o.write(e, p, i);
57
+ },
58
+ delete: (e, t) => o.delete(e, t),
59
+ keys: (e) => o.keys(e)
60
+ }, {
61
+ ...m,
62
+ legacy: !1
63
+ });
64
+ }
65
+ //#endregion
66
+ export { o as signedStorage };
@@ -0,0 +1,114 @@
1
+ import type { Json, SaveDocument } from './document.js';
2
+ import { type LoadOptions, type SaveGameOptions } from './load.js';
3
+ import type { SaveStorage, StorageCallOptions } from './storage.js';
4
+ /** A thumbnail: image bytes, or a Blob from `canvas.toBlob`. See {@link captureThumbnail}. */
5
+ export type Thumbnail = Uint8Array | Blob;
6
+ /** What a load screen shows for one slot. */
7
+ export interface SlotInfo {
8
+ /** The slot's name; autosaves are `auto-0`, `auto-1` and so on. */
9
+ id: string;
10
+ /** Default the document's `meta.title`. */
11
+ title?: string;
12
+ /** When it was saved, in milliseconds since 1970. */
13
+ savedAt: number;
14
+ /** Seconds played. Default the document's `meta.playTime`. */
15
+ playTime?: number;
16
+ /** True for a slot in the autosave ring. */
17
+ autosave: boolean;
18
+ /** The save's schema version. */
19
+ version: number;
20
+ /** Size of the stored save in bytes. */
21
+ bytes: number;
22
+ /** The thumbnail's media type, when the slot has one. */
23
+ thumbnail?: string;
24
+ /** Your own fields for the load screen: the level, the character. */
25
+ meta: Record<string, Json>;
26
+ /** True when the slot's record cannot be read; only `id` is known, and it can be deleted. */
27
+ damaged?: boolean;
28
+ }
29
+ /** Options of {@link SaveSlots}. */
30
+ export interface SaveSlotsOptions extends Pick<SaveGameOptions, 'compress' | 'validate'> {
31
+ /** Kept apart from other slots in the same storage, for profiles. Default `'slot'`. */
32
+ namespace?: string;
33
+ /** How many autosaves take turns. Default 3. */
34
+ autosaves?: number;
35
+ /** The time in milliseconds. Default `Date.now`. */
36
+ now?: () => number;
37
+ }
38
+ /** Options of {@link SaveSlots.save} and {@link SaveSlots.autosave}. */
39
+ export interface SlotSaveOptions extends StorageCallOptions {
40
+ /** Default the document's `meta.title`. */
41
+ title?: string;
42
+ /** Seconds played. Default the document's `meta.playTime`. */
43
+ playTime?: number;
44
+ /** Your own fields for the load screen. */
45
+ meta?: Record<string, Json>;
46
+ /** Shown on the load screen. Default none. */
47
+ thumbnail?: Thumbnail;
48
+ }
49
+ /** Options of {@link SaveSlots.autosaveEvery}. */
50
+ export interface AutosaveTimerOptions extends Omit<SlotSaveOptions, 'thumbnail'> {
51
+ /** Called with each failed autosave; the timer goes on. Default none, and the failure is dropped. */
52
+ onError?(error: unknown): void;
53
+ }
54
+ /** A running autosave timer. */
55
+ export interface AutosaveTimer {
56
+ /** Stops it; an autosave under way finishes. */
57
+ stop(): void;
58
+ [Symbol.dispose](): void;
59
+ }
60
+ /**
61
+ * Slots over a {@link SaveStorage}. Writes run one at a time, in call order.
62
+ * @example
63
+ * const slots = new SaveSlots(indexedDBStorage());
64
+ * await slots.save('slot-1', document, { title: 'Chapter 2' });
65
+ * for (const slot of await slots.list()) console.log(slot.title, new Date(slot.savedAt));
66
+ */
67
+ export declare class SaveSlots {
68
+ #private;
69
+ constructor(storage: SaveStorage, options?: SaveSlotsOptions);
70
+ /**
71
+ * Saves to the slot `id`, replacing what it holds in one step: a failure keeps the old save.
72
+ * Rejects with a TypeError for an invalid document or an id starting `auto-`, which the autosaves own.
73
+ */
74
+ save(id: string, document: SaveDocument, options?: SlotSaveOptions): Promise<SlotInfo>;
75
+ /** Saves over the oldest autosave, or an unused one, so the last few are always there. Other slots are not touched. */
76
+ autosave(document: SaveDocument, options?: SlotSaveOptions): Promise<SlotInfo>;
77
+ /**
78
+ * Autosaves every `milliseconds` with what `capture` returns, until stopped. An autosave that is still running when
79
+ * the next is due makes that one wait; a `capture` returning null skips a turn, for a menu or a cutscene.
80
+ */
81
+ autosaveEvery(milliseconds: number, capture: () => SaveDocument | null | Promise<SaveDocument | null>, options?: AutosaveTimerOptions): AutosaveTimer;
82
+ /** Every slot, newest first, read from the records alone. A slot whose record is damaged is listed with `damaged`. */
83
+ list(options?: StorageCallOptions): Promise<SlotInfo[]>;
84
+ /** The newest slot, autosaves included: what a Continue button loads. Null when there is none. */
85
+ latest(options?: StorageCallOptions): Promise<SlotInfo | null>;
86
+ /** One slot's record, or null when the slot is empty. */
87
+ info(id: string, options?: StorageCallOptions): Promise<SlotInfo | null>;
88
+ /**
89
+ * The slot's save: decoded, migrated and validated as by `loadGame`. Null when the slot is empty.
90
+ * Rejects with a TypeError for a damaged save or record, a MargoError `'failed'` when a migration fails.
91
+ */
92
+ load(id: string, options?: LoadOptions): Promise<SaveDocument | null>;
93
+ /** The slot's thumbnail as a Blob of its type, for `URL.createObjectURL` or `createImageBitmap`. Null when it has none. */
94
+ thumbnail(id: string, options?: StorageCallOptions): Promise<Blob | null>;
95
+ /** Copies a slot to another name, keeping its record's time. An existing slot `to` is replaced in one step. */
96
+ copy(from: string, to: string, options?: StorageCallOptions): Promise<SlotInfo>;
97
+ /** Empties a slot; resolves whether it held anything. Its record goes first, so a crash cannot leave half a slot. */
98
+ delete(id: string, options?: StorageCallOptions): Promise<boolean>;
99
+ }
100
+ /** Options of {@link captureThumbnail}. */
101
+ export interface ThumbnailOptions {
102
+ /** Width in pixels; the height follows the canvas's shape. Default 320. */
103
+ width?: number;
104
+ /** Default `'image/webp'`; a browser without it gives PNG. */
105
+ type?: string;
106
+ /** Between 0 and 1. Default 0.8. */
107
+ quality?: number;
108
+ }
109
+ /**
110
+ * A small picture of a canvas, for `thumbnail`. Call it right after `engine.render()`, in the same task: a WebGPU
111
+ * canvas keeps its picture only until the frame is shown.
112
+ * @throws MargoError `'unsupported'` where there is no OffscreenCanvas.
113
+ */
114
+ export declare function captureThumbnail(canvas: HTMLCanvasElement | OffscreenCanvas, options?: ThumbnailOptions): Promise<Blob>;
package/dist/slots.js ADDED
@@ -0,0 +1,248 @@
1
+ import { a as e, n as t } from "./load-BaYFdOQQ.js";
2
+ import { MargoError as n } from "@margoengine/math/errors";
3
+ //#region src/slots.ts
4
+ var r = class extends TypeError {}, i = "auto-", a = "margo-slot", o = (e, t) => t.slot.savedAt - e.slot.savedAt || t.sequence - e.sequence || (e.slot.id < t.slot.id ? -1 : 1), s = (e) => e.reduce((e, { sequence: t }) => Math.max(e, t), 0) + 1, c = (e) => {
5
+ let t = (t, n) => [...n].every((n, r) => e[t + r] === n.charCodeAt(0));
6
+ return t(1, "PNG") ? "image/png" : e[0] === 255 && e[1] === 216 ? "image/jpeg" : t(0, "RIFF") && t(8, "WEBP") ? "image/webp" : "application/octet-stream";
7
+ }, l = class {
8
+ #e;
9
+ #t;
10
+ #n;
11
+ #r;
12
+ #i;
13
+ #a = Promise.resolve();
14
+ constructor(e, t = {}) {
15
+ if (typeof e?.read != "function") throw TypeError("SaveSlots needs a storage, e.g. memoryStorage()");
16
+ let { namespace: n = "slot", autosaves: r = 3, now: i = Date.now, compress: a, validate: o } = t;
17
+ if (typeof n != "string" || !n || n.includes(":")) throw TypeError("namespace must be a non-empty string with no ':', e.g. 'profile-1'");
18
+ if (!Number.isInteger(r) || r < 1) throw RangeError("autosaves must be a whole number of 1 or more");
19
+ this.#e = e, this.#t = n, this.#n = r, this.#r = i, this.#i = {
20
+ compress: a,
21
+ validate: o
22
+ };
23
+ }
24
+ #o(e) {
25
+ let t = this.#a.then(e, e);
26
+ return this.#a = t.then(() => void 0, () => void 0), t;
27
+ }
28
+ #s(e) {
29
+ return `${this.#t}:${encodeURIComponent(e)}.info`;
30
+ }
31
+ #c(e, t) {
32
+ return `${this.#t}:${encodeURIComponent(e)}:${t}.data`;
33
+ }
34
+ #l(e, t) {
35
+ return `${this.#t}:${encodeURIComponent(e)}:${t}.image`;
36
+ }
37
+ async #u(e, t) {
38
+ let n = await this.#e.read(this.#s(e), t);
39
+ if (n === null) return null;
40
+ let i;
41
+ try {
42
+ i = JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(n));
43
+ } catch (t) {
44
+ throw Object.assign(new r(`Slot '${e}' has a damaged record; delete the slot`), { cause: t });
45
+ }
46
+ if (i?.format !== a || !Number.isInteger(i.generation)) throw new r(`Slot '${e}' has a damaged record; delete the slot`);
47
+ return i;
48
+ }
49
+ async #d(e, t) {
50
+ try {
51
+ return ((await this.#u(e, t))?.generation ?? 0) + 1;
52
+ } catch (e) {
53
+ if (e instanceof r) return 1;
54
+ throw e;
55
+ }
56
+ }
57
+ async #f(e, t, n) {
58
+ let r = `${this.#t}:${encodeURIComponent(e)}:`;
59
+ for (let e of await this.#e.keys(n)) e.startsWith(r) && !t.includes(e) && await this.#e.delete(e, n);
60
+ }
61
+ async #p(t, r, i, o, s) {
62
+ let { title: l, playTime: u, meta: d = {}, thumbnail: p, signal: m } = i, h = { signal: m }, g = await this.#d(t, h), _ = this.#c(t, g), v = this.#l(t, g);
63
+ await e(this.#e, _, r, {
64
+ ...this.#i,
65
+ signal: m
66
+ });
67
+ let y = await this.#e.read(_, h);
68
+ if (y === null) throw new n("failed", `Slot '${t}': the storage kept nothing, so the old slot stands; check the storage and save again`);
69
+ let b = {
70
+ format: a,
71
+ generation: g,
72
+ sequence: s,
73
+ savedAt: this.#r(),
74
+ autosave: o,
75
+ version: r.version,
76
+ bytes: y.length,
77
+ meta: d
78
+ }, x = l ?? r.meta?.title, S = u ?? r.meta?.playTime;
79
+ if (typeof x == "string" && (b.title = x), typeof S == "number" && (b.playTime = S), p !== void 0) {
80
+ let e = p instanceof Uint8Array ? p : new Uint8Array(await p.arrayBuffer());
81
+ b.thumbnail = p.type || c(e), await this.#e.write(v, e, h);
82
+ }
83
+ return await this.#e.write(this.#s(t), new TextEncoder().encode(JSON.stringify(b)), h), await this.#f(t, p === void 0 ? [_] : [_, v], h), f(t, b);
84
+ }
85
+ async save(e, t, n = {}) {
86
+ if (d(e), e.startsWith(i)) throw TypeError(`Slot id '${e}': 'auto-' names belong to autosave(); use another id`);
87
+ return this.#o(async () => this.#p(e, t, n, !1, s(await this.#m(n))));
88
+ }
89
+ autosave(e, t = {}) {
90
+ return this.#o(async () => {
91
+ let n = await this.#m(t), r = /* @__PURE__ */ new Map();
92
+ for (let e of n) e.slot.autosave && r.set(e.slot.id, e);
93
+ let a = "", c;
94
+ for (let e = 0; e < this.#n; e++) {
95
+ let t = `${i}${e}`, n = r.get(t);
96
+ if (!n) {
97
+ a = t;
98
+ break;
99
+ }
100
+ (!c || o(c, n) < 0) && (a = t, c = n);
101
+ }
102
+ return this.#p(a, e, t, !0, s(n));
103
+ });
104
+ }
105
+ autosaveEvery(e, t, n = {}) {
106
+ if (!(e > 0)) throw RangeError("autosaveEvery: milliseconds must be above 0");
107
+ if (typeof t != "function") throw TypeError("autosaveEvery: capture must return a document, e.g. () => captureScene(engine)");
108
+ let { onError: r, signal: i, ...a } = n, o, s = !1, c = () => {
109
+ s = !0, clearTimeout(o), i?.removeEventListener("abort", c);
110
+ }, l = async () => {
111
+ try {
112
+ let e = await t();
113
+ e && !s && await this.autosave(e, {
114
+ ...a,
115
+ signal: i
116
+ });
117
+ } catch (e) {
118
+ s || r?.(e);
119
+ }
120
+ s || (o = setTimeout(l, e));
121
+ };
122
+ return i?.addEventListener("abort", c, { once: !0 }), i?.aborted ? c() : o = setTimeout(l, e), {
123
+ stop: c,
124
+ [Symbol.dispose]: c
125
+ };
126
+ }
127
+ async #m(e) {
128
+ let t = `${this.#t}:`, n = [];
129
+ for (let a of await this.#e.keys(e)) {
130
+ if (!a.startsWith(t) || !a.endsWith(".info")) continue;
131
+ let o = u(a.slice(t.length, -5));
132
+ if (o !== null) try {
133
+ let t = await this.#u(o, e);
134
+ t && n.push({
135
+ slot: f(o, t),
136
+ sequence: t.sequence ?? 0
137
+ });
138
+ } catch (e) {
139
+ if (!(e instanceof r)) throw e;
140
+ n.push({
141
+ slot: {
142
+ id: o,
143
+ savedAt: 0,
144
+ autosave: o.startsWith(i),
145
+ version: 0,
146
+ bytes: 0,
147
+ meta: {},
148
+ damaged: !0
149
+ },
150
+ sequence: 0
151
+ });
152
+ }
153
+ }
154
+ return n.sort(o);
155
+ }
156
+ async #h(e) {
157
+ return (await this.#m(e)).map(({ slot: e }) => e);
158
+ }
159
+ list(e) {
160
+ return this.#o(() => this.#h(e));
161
+ }
162
+ async latest(e) {
163
+ return (await this.list(e)).find((e) => !e.damaged) ?? null;
164
+ }
165
+ async info(e, t) {
166
+ return d(e), this.#o(async () => {
167
+ let n = await this.#u(e, t);
168
+ return n ? f(e, n) : null;
169
+ });
170
+ }
171
+ async load(e, n = {}) {
172
+ return d(e), this.#o(async () => {
173
+ let r = await this.#u(e, n);
174
+ if (!r) return null;
175
+ let i = await t(this.#e, this.#c(e, r.generation), n);
176
+ if (!i) throw TypeError(`Slot '${e}' has lost its save; delete the slot`);
177
+ return i;
178
+ });
179
+ }
180
+ async thumbnail(e, t) {
181
+ return d(e), this.#o(async () => {
182
+ let n = await this.#u(e, t);
183
+ if (!n?.thumbnail) return null;
184
+ let r = await this.#e.read(this.#l(e, n.generation), t);
185
+ return r && new Blob([r], { type: n.thumbnail });
186
+ });
187
+ }
188
+ async copy(e, t, r) {
189
+ if (d(e), d(t), t.startsWith(i)) throw TypeError(`Slot id '${t}': 'auto-' names belong to autosave(); use another id`);
190
+ return this.#o(async () => {
191
+ let i = await this.#u(e, r);
192
+ if (!i) throw new n("state", `Slot '${e}' is empty; copy a slot that holds a save`);
193
+ let a = await this.#d(t, r), o = [this.#c(t, a)], c = await this.#e.read(this.#c(e, i.generation), r);
194
+ if (!c) throw TypeError(`Slot '${e}' has lost its save; delete the slot`);
195
+ if (await this.#e.write(o[0], c, r), i.thumbnail) {
196
+ let n = await this.#e.read(this.#l(e, i.generation), r);
197
+ n && (o.push(this.#l(t, a)), await this.#e.write(o[1], n, r));
198
+ }
199
+ let l = {
200
+ ...i,
201
+ generation: a,
202
+ sequence: s(await this.#m(r)),
203
+ autosave: !1
204
+ };
205
+ return await this.#e.write(this.#s(t), new TextEncoder().encode(JSON.stringify(l)), r), await this.#f(t, o, r), f(t, l);
206
+ });
207
+ }
208
+ async delete(e, t) {
209
+ return d(e), this.#o(async () => {
210
+ let n = await this.#e.delete(this.#s(e), t);
211
+ return await this.#f(e, [], t), n;
212
+ });
213
+ }
214
+ };
215
+ function u(e) {
216
+ try {
217
+ return decodeURIComponent(e);
218
+ } catch {
219
+ return null;
220
+ }
221
+ }
222
+ function d(e) {
223
+ if (typeof e != "string" || !e) throw TypeError("Slot id must be a non-empty string, e.g. \"slot-1\"");
224
+ }
225
+ function f(e, t) {
226
+ let { format: n, generation: r, sequence: i, ...a } = t;
227
+ return {
228
+ id: e,
229
+ ...a
230
+ };
231
+ }
232
+ async function p(e, t = {}) {
233
+ let { width: r = 320, type: i = "image/webp", quality: a = .8 } = t;
234
+ if (!(r > 0)) throw RangeError("width must be above 0");
235
+ if (!e.width || !e.height) throw RangeError("captureThumbnail needs a canvas with a size; render a frame first");
236
+ if (typeof OffscreenCanvas != "function" || typeof createImageBitmap != "function") throw new n("unsupported", "captureThumbnail needs OffscreenCanvas; pass your own thumbnail bytes here");
237
+ let o = Math.max(1, Math.round(r * e.height / e.width)), s = new OffscreenCanvas(r, o), c = await createImageBitmap(e, {
238
+ resizeWidth: r,
239
+ resizeHeight: o,
240
+ resizeQuality: "medium"
241
+ });
242
+ return s.getContext("2d").drawImage(c, 0, 0), c.close(), s.convertToBlob({
243
+ type: i,
244
+ quality: a
245
+ });
246
+ }
247
+ //#endregion
248
+ export { l as SaveSlots, p as captureThumbnail };
@@ -0,0 +1,153 @@
1
+ import { MargoError as e } from "@margoengine/math/errors";
2
+ //#region src/storage.ts
3
+ var t = (e) => {
4
+ if (typeof e != "string" || !e) throw TypeError("Save key must be a non-empty string, e.g. \"slot-1\"");
5
+ }, n = (e) => {
6
+ if (!(e instanceof Uint8Array)) throw TypeError("Save bytes must be a Uint8Array; encode the document with encodeSave");
7
+ };
8
+ function r() {
9
+ let e = /* @__PURE__ */ new Map();
10
+ return {
11
+ async read(n, r) {
12
+ r?.signal?.throwIfAborted(), t(n);
13
+ let i = e.get(n);
14
+ return i ? i.slice() : null;
15
+ },
16
+ async write(r, i, a) {
17
+ a?.signal?.throwIfAborted(), t(r), n(i), e.set(r, i.slice());
18
+ },
19
+ async delete(n, r) {
20
+ return r?.signal?.throwIfAborted(), t(n), e.delete(n);
21
+ },
22
+ async keys(t) {
23
+ return t?.signal?.throwIfAborted(), [...e.keys()].sort();
24
+ }
25
+ };
26
+ }
27
+ var i = (e) => {
28
+ let t = "";
29
+ for (let n = 0; n < e.length; n += 32768) t += String.fromCharCode(...e.subarray(n, n + 32768));
30
+ return btoa(t);
31
+ }, a = (e) => Uint8Array.from(atob(e), (e) => e.charCodeAt(0));
32
+ function o(r, o = "margo-save:") {
33
+ let s = r ?? globalThis.localStorage;
34
+ if (!s) throw new e("unsupported", "localStorage is not available here; pass a Storage or use indexedDBStorage or memoryStorage");
35
+ return {
36
+ async read(e, n) {
37
+ n?.signal?.throwIfAborted(), t(e);
38
+ let r = s.getItem(o + e);
39
+ if (r === null) return null;
40
+ try {
41
+ return a(r);
42
+ } catch (t) {
43
+ throw Object.assign(/* @__PURE__ */ TypeError(`Saved data under '${e}' is not base64; it was not written by webStorage, delete it`), { cause: t });
44
+ }
45
+ },
46
+ async write(r, a, c) {
47
+ c?.signal?.throwIfAborted(), t(r), n(a);
48
+ try {
49
+ s.setItem(o + r, i(a));
50
+ } catch (t) {
51
+ throw Object.assign(new e("failed", `Web Storage refused the save '${r}' (it is full or blocked); compress saves or use indexedDBStorage`), { cause: t });
52
+ }
53
+ },
54
+ async delete(e, n) {
55
+ n?.signal?.throwIfAborted(), t(e);
56
+ let r = s.getItem(o + e) !== null;
57
+ return s.removeItem(o + e), r;
58
+ },
59
+ async keys(e) {
60
+ e?.signal?.throwIfAborted();
61
+ let t = [];
62
+ for (let e = 0; e < s.length; e++) {
63
+ let n = s.key(e);
64
+ n?.startsWith(o) && t.push(n.slice(o.length));
65
+ }
66
+ return t.sort();
67
+ }
68
+ };
69
+ }
70
+ var s = (t, n) => new Promise((r, i) => {
71
+ let a = () => i(n.reason);
72
+ n?.addEventListener("abort", a, { once: !0 }), t.onsuccess = () => {
73
+ n?.removeEventListener("abort", a), r(t.result);
74
+ }, t.onerror = () => {
75
+ n?.removeEventListener("abort", a), i(Object.assign(new e("failed", "IndexedDB request failed; check the storage quota and private-mode settings"), { cause: t.error }));
76
+ };
77
+ });
78
+ function c(r = {}) {
79
+ let i = r.database ?? "margo-saves", a = r.store ?? "saves", o = null, c = (t) => {
80
+ t?.throwIfAborted();
81
+ let n = r.factory ?? globalThis.indexedDB;
82
+ if (!n) return Promise.reject(new e("unsupported", "IndexedDB is not available here; pass options.factory or use memoryStorage"));
83
+ let s = (t, r) => new Promise((s, c) => {
84
+ let l = t === void 0 ? n.open(i) : n.open(i, t);
85
+ l.onupgradeneeded = () => {
86
+ l.result.objectStoreNames.contains(a) || l.result.createObjectStore(a);
87
+ }, l.onsuccess = () => {
88
+ let e = l.result;
89
+ e.onversionchange = () => {
90
+ e.close(), o === r() && (o = null);
91
+ }, s(e);
92
+ }, l.onerror = () => c(Object.assign(new e("failed", `IndexedDB database '${i}' did not open; check private-mode and storage settings`), { cause: l.error }));
93
+ });
94
+ if (!o) {
95
+ let e = (async () => {
96
+ let t = await s(void 0, () => e);
97
+ for (; !t.objectStoreNames.contains(a);) {
98
+ let n = t.version;
99
+ t.close(), t = await s(n + 1, () => e);
100
+ }
101
+ return t;
102
+ })();
103
+ o = e, e.catch(() => {
104
+ o === e && (o = null);
105
+ });
106
+ }
107
+ return o;
108
+ }, l = async (t, n, r) => {
109
+ let i = await c(n);
110
+ n?.throwIfAborted();
111
+ let o = i.transaction(a, t, { durability: t === "readwrite" ? "strict" : "default" }), l = new Promise((t, n) => {
112
+ o.oncomplete = () => t(), o.onabort = o.onerror = () => n(Object.assign(new e("failed", "IndexedDB transaction failed; check the storage quota"), { cause: o.error }));
113
+ }), u = () => o.abort();
114
+ n?.addEventListener("abort", u, { once: !0 });
115
+ try {
116
+ let [e] = await Promise.all([s(r(o.objectStore(a))), l]);
117
+ return e;
118
+ } catch (e) {
119
+ throw n?.throwIfAborted(), e;
120
+ } finally {
121
+ n?.removeEventListener("abort", u);
122
+ }
123
+ }, u = async () => {
124
+ let e = o;
125
+ o = null, (await e?.catch(() => null))?.close();
126
+ };
127
+ return {
128
+ close: u,
129
+ [Symbol.dispose]() {
130
+ u();
131
+ },
132
+ async read(e, n) {
133
+ t(e);
134
+ let r = await l("readonly", n?.signal, (t) => t.get(e));
135
+ if (r === void 0) return null;
136
+ if (!(r instanceof Uint8Array)) throw TypeError(`Saved data under '${e}' is not bytes; it was not written by indexedDBStorage, delete it`);
137
+ return r;
138
+ },
139
+ async write(e, r, i) {
140
+ t(e), n(r), await l("readwrite", i?.signal, (t) => t.put(r.slice(), e));
141
+ },
142
+ async delete(e, n) {
143
+ t(e);
144
+ let r = n?.signal, i = await l("readonly", r, (t) => t.count(e)) > 0;
145
+ return await l("readwrite", r, (t) => t.delete(e)), i;
146
+ },
147
+ async keys(e) {
148
+ return (await l("readonly", e?.signal, (e) => e.getAllKeys())).map(String).sort();
149
+ }
150
+ };
151
+ }
152
+ //#endregion
153
+ export { o as a, i, c as n, r, a as t };
@@ -0,0 +1,59 @@
1
+ /** Options every storage call takes. */
2
+ export interface StorageCallOptions {
3
+ /** Stops the call; the promise rejects with the signal's reason. */
4
+ signal?: AbortSignal;
5
+ }
6
+ /** A place to keep saves under string keys. Every call is async and takes an AbortSignal. */
7
+ export interface SaveStorage {
8
+ /** The bytes under `key`, or null when there are none. */
9
+ read(key: string, options?: StorageCallOptions): Promise<Uint8Array | null>;
10
+ /** Store `bytes` under `key`, replacing what was there in one step. */
11
+ write(key: string, bytes: Uint8Array, options?: StorageCallOptions): Promise<void>;
12
+ /** Remove `key`; resolves whether it existed. */
13
+ delete(key: string, options?: StorageCallOptions): Promise<boolean>;
14
+ /** Every key, sorted. */
15
+ keys(options?: StorageCallOptions): Promise<string[]>;
16
+ }
17
+ /** Saves in a Map, for tests, servers and undo snapshots. */
18
+ export declare function memoryStorage(): SaveStorage;
19
+ export declare const toBase64: (bytes: Uint8Array) => string;
20
+ export declare const fromBase64: (text: string) => Uint8Array;
21
+ /** The part of the Web Storage interface the adapter uses (`localStorage` and `sessionStorage` have it). */
22
+ export interface WebStorageLike {
23
+ getItem(key: string): string | null;
24
+ setItem(key: string, value: string): void;
25
+ removeItem(key: string): void;
26
+ key(index: number): string | null;
27
+ readonly length: number;
28
+ }
29
+ /**
30
+ * Saves in Web Storage (default `localStorage`), base64 under `prefix + key` (default prefix `'margo-save:'`).
31
+ * Web Storage holds about 5 MB per origin: compress saves, or use {@link indexedDBStorage} for big worlds.
32
+ * @throws MargoError `'unsupported'` when there is no Web Storage (Node, a worker): pass one or use another adapter.
33
+ */
34
+ export declare function webStorage(storage?: WebStorageLike, prefix?: string): SaveStorage;
35
+ /** Options of {@link indexedDBStorage}. */
36
+ export interface IndexedDBStorageOptions {
37
+ /** Database name (default `'margo-saves'`). */
38
+ database?: string;
39
+ /** Object store name (default `'saves'`). */
40
+ store?: string;
41
+ /** The IndexedDB factory (default `globalThis.indexedDB`). */
42
+ factory?: IDBFactory;
43
+ }
44
+ /** {@link indexedDBStorage}'s adapter: a {@link SaveStorage} that also lets go of its database connection. */
45
+ export interface IndexedDBStorage extends SaveStorage {
46
+ /**
47
+ * Closes the database connection once its transactions finish. The storage stays usable: the next call opens the
48
+ * database again. Safe to call twice.
49
+ */
50
+ close(): Promise<void>;
51
+ /** Same as {@link IndexedDBStorage.close}, for `using`. */
52
+ [Symbol.dispose](): void;
53
+ }
54
+ /**
55
+ * Saves in IndexedDB: large, binary, asynchronous, one transaction per write. The database opens on first use and
56
+ * stays open until `close()` (or `using`), so an app that is done with saving can release the connection.
57
+ * @throws MargoError `'unsupported'` (on first use) when there is no IndexedDB: pass a factory or use another adapter.
58
+ */
59
+ export declare function indexedDBStorage(options?: IndexedDBStorageOptions): IndexedDBStorage;