@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/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +655 -2
- package/dist/codec.d.ts +25 -0
- package/dist/delta.d.ts +51 -0
- package/dist/delta.js +114 -0
- package/dist/document.d.ts +90 -0
- package/dist/engine.d.ts +113 -0
- package/dist/engine.js +467 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +46 -0
- package/dist/load-BaYFdOQQ.js +172 -0
- package/dist/load.d.ts +74 -0
- package/dist/materials.d.ts +12 -0
- package/dist/materials.js +16 -0
- package/dist/migrations.d.ts +31 -0
- package/dist/node.d.ts +18 -0
- package/dist/node.js +108 -0
- package/dist/opfs.d.ts +17 -0
- package/dist/opfs.js +105 -0
- package/dist/prefab-DeWmT5ey.js +277 -0
- package/dist/prefab.d.ts +23 -0
- package/dist/queue-C2AsmZge.js +12 -0
- package/dist/queue.d.ts +2 -0
- package/dist/remote.d.ts +59 -0
- package/dist/remote.js +235 -0
- package/dist/safe-DVo3kH0O.js +128 -0
- package/dist/safe.d.ts +46 -0
- package/dist/safe.js +1 -0
- package/dist/scene-state.d.ts +29 -0
- package/dist/scene-state.js +86 -0
- package/dist/signed.d.ts +17 -0
- package/dist/signed.js +66 -0
- package/dist/slots.d.ts +114 -0
- package/dist/slots.js +248 -0
- package/dist/storage-DZeyzOh1.js +153 -0
- package/dist/storage.d.ts +59 -0
- package/package.json +119 -4
package/dist/prefab.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Json, SaveDocument, SavedTransform } from './document.js';
|
|
2
|
+
/** An entity after prefab expansion: no prefab fields; every reference resolves to an entity of the same list. */
|
|
3
|
+
export interface ResolvedEntity {
|
|
4
|
+
id: string;
|
|
5
|
+
name?: string;
|
|
6
|
+
parent?: string;
|
|
7
|
+
transform?: SavedTransform;
|
|
8
|
+
components: Record<string, Json>;
|
|
9
|
+
/** Prefab key this entity was made from, and its id inside that prefab (for tools; not needed to load). */
|
|
10
|
+
source?: {
|
|
11
|
+
prefab: string;
|
|
12
|
+
local: string;
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/** JSON Merge Patch (RFC 7386): objects merge key by key, `null` removes a key, anything else replaces. */
|
|
16
|
+
export declare function mergePatch(target: Json | undefined, patch: Json): Json | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* Expand every prefab instance of a valid document (see {@link validateSave}) into plain entities, parents before
|
|
19
|
+
* children. Pure: the document is not changed.
|
|
20
|
+
* @throws TypeError when an expanded id collides with another entity or a reference does not resolve after
|
|
21
|
+
* expansion (`door/handle` naming no entity), each naming the fix.
|
|
22
|
+
*/
|
|
23
|
+
export declare function expandSave(document: SaveDocument): ResolvedEntity[];
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
//#region src/queue.ts
|
|
2
|
+
function e() {
|
|
3
|
+
let e = /* @__PURE__ */ new Map();
|
|
4
|
+
return (t, n) => {
|
|
5
|
+
let r = (e.get(t) ?? Promise.resolve()).then(n, n), i = r.then(() => void 0, () => void 0);
|
|
6
|
+
return e.set(t, i), i.then(() => {
|
|
7
|
+
e.get(t) === i && e.delete(t);
|
|
8
|
+
}), r;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
//#endregion
|
|
12
|
+
export { e as t };
|
package/dist/queue.d.ts
ADDED
package/dist/remote.d.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { SaveStorage } from './storage.js';
|
|
2
|
+
/** What two devices disagree on. `null` is a key that is not there. */
|
|
3
|
+
export interface SaveConflict {
|
|
4
|
+
key: string;
|
|
5
|
+
/** What this client wanted to store; null for a delete. */
|
|
6
|
+
local: Uint8Array | null;
|
|
7
|
+
/** What the server holds now. */
|
|
8
|
+
remote: Uint8Array | null;
|
|
9
|
+
}
|
|
10
|
+
/** Returns what the key should hold, or null for nothing. Return `remote` to keep it. */
|
|
11
|
+
export type ConflictResolver = (conflict: SaveConflict) => Uint8Array | null | Promise<Uint8Array | null>;
|
|
12
|
+
/** Options of {@link remoteStorage}. */
|
|
13
|
+
export interface RemoteStorageOptions {
|
|
14
|
+
/** The folder of saves: a key lives at `${url}/${encodeURIComponent(key)}`, and GET on `url` lists keys as JSON. */
|
|
15
|
+
url: string | URL;
|
|
16
|
+
/** Default `globalThis.fetch`. */
|
|
17
|
+
fetch?: typeof globalThis.fetch;
|
|
18
|
+
/** Sent with each request. A function runs for each attempt, for a token that expires. Default none. */
|
|
19
|
+
headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
|
|
20
|
+
/**
|
|
21
|
+
* When the server's save is not the one this client last saw. `'error'` rejects and changes nothing, `'local'` writes
|
|
22
|
+
* over it, `'remote'` keeps it and drops this write, and a function merges the two. Default `'error'`.
|
|
23
|
+
*/
|
|
24
|
+
conflict?: 'error' | 'local' | 'remote' | ConflictResolver;
|
|
25
|
+
/** Milliseconds for one attempt. Default 30,000. */
|
|
26
|
+
timeout?: number;
|
|
27
|
+
/** Further attempts after a network failure, a timeout, a 429 or a 5xx. Default 3. */
|
|
28
|
+
retries?: number;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Saves on an HTTP server, with conflicts found by the server through ETags. Read a key before writing it on a new
|
|
32
|
+
* device, or the write counts as a conflict with what is there. The server must send a strong ETag; a weak one is asked
|
|
33
|
+
* for again before a write, since a server can go from one to the other once a change has settled.
|
|
34
|
+
* @example
|
|
35
|
+
* const storage = remoteStorage({ url: 'https://example.com/saves', headers: () => ({ authorization: `Bearer ${token()}` }) });
|
|
36
|
+
* await saveGame(storage, 'slot-1', document);
|
|
37
|
+
*/
|
|
38
|
+
export declare function remoteStorage(options: RemoteStorageOptions): SaveStorage;
|
|
39
|
+
/** Options of {@link remoteHandler}. */
|
|
40
|
+
export interface RemoteHandlerOptions {
|
|
41
|
+
/** The path the saves sit under. Default `'/'`. */
|
|
42
|
+
base?: string;
|
|
43
|
+
/** The `Access-Control-Allow-Origin` value, for a page on another origin. Default none: same origin only. */
|
|
44
|
+
origin?: string;
|
|
45
|
+
/** Request headers a page may send, beside the conditional ones. Default `['authorization', 'content-type']`. */
|
|
46
|
+
allowHeaders?: readonly string[];
|
|
47
|
+
/** Largest save it takes, in bytes. Default 64 MiB. */
|
|
48
|
+
maxBytes?: number;
|
|
49
|
+
/** Runs first on each request; false answers 403. Default none, so every caller can read and write. */
|
|
50
|
+
authorize?(request: Request): boolean | Promise<boolean>;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* A save server over any storage: takes a fetch `Request` and gives a `Response`, so it runs in a service worker,
|
|
54
|
+
* Deno, Bun or a Node server with a few lines around it. A key's writes run one at a time, so a precondition and its
|
|
55
|
+
* write cannot be split by another request of this handler.
|
|
56
|
+
* @example
|
|
57
|
+
* const handle = remoteHandler(fileStorage('./saves'), { base: '/saves', authorize: (request) => signedIn(request) });
|
|
58
|
+
*/
|
|
59
|
+
export declare function remoteHandler(storage: SaveStorage, options?: RemoteHandlerOptions): (request: Request) => Promise<Response>;
|
package/dist/remote.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { t as e } from "./queue-C2AsmZge.js";
|
|
2
|
+
import { MargoError as t } from "@margoengine/math/errors";
|
|
3
|
+
//#region src/remote.ts
|
|
4
|
+
var n = /* @__PURE__ */ new Set([
|
|
5
|
+
408,
|
|
6
|
+
429,
|
|
7
|
+
500,
|
|
8
|
+
502,
|
|
9
|
+
503,
|
|
10
|
+
504
|
|
11
|
+
]), r = 6e4, i = 5, a = (e) => e >= 200 && e < 300, o = (e, t) => e.length === t.length && e.every((e, n) => e === t[n]);
|
|
12
|
+
function s(e) {
|
|
13
|
+
if (e === null) return null;
|
|
14
|
+
if (/^\d+$/.test(e)) return Number(e) * 1e3;
|
|
15
|
+
let t = Date.parse(e);
|
|
16
|
+
return Number.isNaN(t) ? null : Math.max(0, t - Date.now());
|
|
17
|
+
}
|
|
18
|
+
var c = (e, t) => new Promise((n, r) => {
|
|
19
|
+
let i = () => {
|
|
20
|
+
clearTimeout(a), r(t.reason);
|
|
21
|
+
}, a = setTimeout(() => {
|
|
22
|
+
t?.removeEventListener("abort", i), n();
|
|
23
|
+
}, e);
|
|
24
|
+
t?.addEventListener("abort", i, { once: !0 });
|
|
25
|
+
});
|
|
26
|
+
function l(l) {
|
|
27
|
+
if (!l?.url) throw TypeError("remoteStorage needs a url, e.g. { url: 'https://example.com/saves' }");
|
|
28
|
+
let { headers: u, conflict: d = "error", timeout: f = 3e4, retries: p = 3 } = l, m = String(l.url).replace(/\/+$/, ""), h = l.fetch ?? globalThis.fetch, g = /* @__PURE__ */ new Map(), _ = /* @__PURE__ */ new Map(), v = e();
|
|
29
|
+
if (typeof h != "function") throw new t("unsupported", "There is no fetch here; pass options.fetch");
|
|
30
|
+
if (typeof d != "function" && ![
|
|
31
|
+
"error",
|
|
32
|
+
"local",
|
|
33
|
+
"remote"
|
|
34
|
+
].includes(d)) throw TypeError("conflict must be 'error', 'local', 'remote' or a function");
|
|
35
|
+
if (!(f > 0)) throw RangeError("timeout must be above 0 milliseconds");
|
|
36
|
+
if (!Number.isInteger(p) || p < 0) throw RangeError("retries must be a whole number of 0 or more");
|
|
37
|
+
let y = (e) => {
|
|
38
|
+
if (typeof e != "string" || !e) throw TypeError("Save key must be a non-empty string, e.g. \"slot-1\"");
|
|
39
|
+
return `${m}/${encodeURIComponent(e)}`;
|
|
40
|
+
}, b = async (e, i, a) => {
|
|
41
|
+
let o = a?.signal;
|
|
42
|
+
for (let a = 0;; a++) {
|
|
43
|
+
o?.throwIfAborted();
|
|
44
|
+
let l, d = null;
|
|
45
|
+
try {
|
|
46
|
+
let r = AbortSignal.timeout(f), a = typeof u == "function" ? await u() : u, c = new Headers(a);
|
|
47
|
+
new Headers(i.headers).forEach((e, t) => c.set(t, e));
|
|
48
|
+
let p = await h(e, {
|
|
49
|
+
...i,
|
|
50
|
+
headers: c,
|
|
51
|
+
cache: "no-store",
|
|
52
|
+
signal: o ? AbortSignal.any([o, r]) : r
|
|
53
|
+
}), m = new Uint8Array(await p.arrayBuffer());
|
|
54
|
+
if (!n.has(p.status)) return {
|
|
55
|
+
status: p.status,
|
|
56
|
+
etag: p.headers.get("etag"),
|
|
57
|
+
body: m
|
|
58
|
+
};
|
|
59
|
+
l = new t("failed", `The save server answered ${p.status} for ${e}; try again later`), d = s(p.headers.get("retry-after"));
|
|
60
|
+
} catch (n) {
|
|
61
|
+
if (o?.throwIfAborted(), n instanceof t) throw n;
|
|
62
|
+
l = Object.assign(new t(n?.name === "TimeoutError" ? "timeout" : "failed", `The save server did not answer for ${e}; check the connection, or raise timeout`), { cause: n });
|
|
63
|
+
}
|
|
64
|
+
if (a >= p) throw l;
|
|
65
|
+
let m = d ?? Math.random() * 200 * 2 ** a;
|
|
66
|
+
if (m > r) throw l;
|
|
67
|
+
await c(m, o);
|
|
68
|
+
}
|
|
69
|
+
}, x = (e, n) => new t("failed", e === 401 || e === 403 ? `The save server refused ${n} (${e}); check the headers option` : `The save server answered ${e} for ${n}; check that url points at a save folder`), S = async (e, t) => {
|
|
70
|
+
let { status: n, etag: r, body: i } = await b(y(e), { method: "GET" }, t);
|
|
71
|
+
if (n === 404 || n === 410) return g.set(e, null), null;
|
|
72
|
+
if (!a(n)) throw x(n, `reading '${e}'`);
|
|
73
|
+
return g.set(e, r ?? ""), r?.startsWith("W/") ? _.set(e, i) : _.delete(e), i;
|
|
74
|
+
}, C = (e, n) => {
|
|
75
|
+
let r = g.get(e);
|
|
76
|
+
if (r === "") throw new t("unsupported", `The save server sent no ETag for '${e}'; conflicts need one, so turn on ETags on that server`);
|
|
77
|
+
if (r?.startsWith("W/")) throw new t("unsupported", `The save server gave '${e}' a weak ETag (${r}), which If-Match never matches; make that server send strong ETags, or wait a moment if it just changed`);
|
|
78
|
+
return typeof r == "string" ? { "if-match": r } : n ? { "if-none-match": "*" } : {};
|
|
79
|
+
}, w = async (e, t) => {
|
|
80
|
+
let n = _.get(e);
|
|
81
|
+
if (!n || !g.get(e)?.startsWith("W/")) return !0;
|
|
82
|
+
let r = await S(e, t);
|
|
83
|
+
return r !== null && o(r, n);
|
|
84
|
+
}, T = async (e, n, r) => {
|
|
85
|
+
let s = n;
|
|
86
|
+
for (let n = 0; n < i; n++) {
|
|
87
|
+
let { status: n, etag: i } = await w(e, r) ? s === null ? await b(y(e), {
|
|
88
|
+
method: "DELETE",
|
|
89
|
+
headers: C(e, !1)
|
|
90
|
+
}, r) : await b(y(e), {
|
|
91
|
+
method: "PUT",
|
|
92
|
+
headers: {
|
|
93
|
+
"content-type": "application/octet-stream",
|
|
94
|
+
...C(e, !0)
|
|
95
|
+
},
|
|
96
|
+
body: s
|
|
97
|
+
}, r) : {
|
|
98
|
+
status: 412,
|
|
99
|
+
etag: null
|
|
100
|
+
};
|
|
101
|
+
if (a(n)) {
|
|
102
|
+
if (s === null) g.set(e, null);
|
|
103
|
+
else if (i !== null) g.set(e, i);
|
|
104
|
+
else {
|
|
105
|
+
g.delete(e);
|
|
106
|
+
let t = await S(e, r);
|
|
107
|
+
(!t || !o(t, s)) && g.delete(e);
|
|
108
|
+
}
|
|
109
|
+
return !0;
|
|
110
|
+
}
|
|
111
|
+
if (n === 404 && s === null) return g.set(e, null), !1;
|
|
112
|
+
if (n !== 412) throw x(n, `saving '${e}'`);
|
|
113
|
+
let c = await S(e, r);
|
|
114
|
+
if (c === null ? s === null : s !== null && o(c, s)) return s !== null;
|
|
115
|
+
if (d === "error") throw new t("state", `Save '${e}' changed on the server since this client read it; read it again, or set conflict to 'local', 'remote' or a function`);
|
|
116
|
+
if (d === "remote" || typeof d == "function" && (s = await d({
|
|
117
|
+
key: e,
|
|
118
|
+
local: s,
|
|
119
|
+
remote: c
|
|
120
|
+
}), s === null ? c === null : c !== null && o(s, c))) return c !== null;
|
|
121
|
+
}
|
|
122
|
+
throw new t("state", `Save '${e}' kept changing on the server while this client wrote it; save again later`);
|
|
123
|
+
};
|
|
124
|
+
return {
|
|
125
|
+
async read(e, t) {
|
|
126
|
+
return y(e), v(e, () => S(e, t));
|
|
127
|
+
},
|
|
128
|
+
async write(e, t, n) {
|
|
129
|
+
if (y(e), !(t instanceof Uint8Array)) throw TypeError("Save bytes must be a Uint8Array; encode the document with encodeSave");
|
|
130
|
+
await v(e, () => T(e, t, n));
|
|
131
|
+
},
|
|
132
|
+
async delete(e, t) {
|
|
133
|
+
return y(e), v(e, () => T(e, null, t));
|
|
134
|
+
},
|
|
135
|
+
async keys(e) {
|
|
136
|
+
let { status: t, body: n } = await b(m, {
|
|
137
|
+
method: "GET",
|
|
138
|
+
headers: { accept: "application/json" }
|
|
139
|
+
}, e);
|
|
140
|
+
if (!a(t)) throw x(t, "the list of saves");
|
|
141
|
+
let r;
|
|
142
|
+
try {
|
|
143
|
+
r = JSON.parse(new TextDecoder().decode(n));
|
|
144
|
+
} catch (e) {
|
|
145
|
+
throw Object.assign(/* @__PURE__ */ TypeError(`The list at ${m} is not JSON; serve an array of keys there`), { cause: e });
|
|
146
|
+
}
|
|
147
|
+
if (!Array.isArray(r) || r.some((e) => typeof e != "string")) throw TypeError(`The list at ${m} is not an array of strings; serve an array of keys there`);
|
|
148
|
+
return r.slice().sort();
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
var u = (e) => [...new Uint8Array(e)].map((e) => e.toString(16).padStart(2, "0")).join(""), d = async (e) => `"${u(await crypto.subtle.digest("SHA-256", e)).slice(0, 32)}"`;
|
|
153
|
+
async function f(e, t) {
|
|
154
|
+
if (!e.body) return /* @__PURE__ */ new Uint8Array();
|
|
155
|
+
let n = e.body.getReader(), r = [], i = 0;
|
|
156
|
+
for (;;) {
|
|
157
|
+
let { done: e, value: a } = await n.read();
|
|
158
|
+
if (e) break;
|
|
159
|
+
if (i += a.length, i > t) return await n.cancel(), null;
|
|
160
|
+
r.push(a);
|
|
161
|
+
}
|
|
162
|
+
let a = new Uint8Array(i), o = 0;
|
|
163
|
+
for (let e of r) a.set(e, o), o += e.length;
|
|
164
|
+
return a;
|
|
165
|
+
}
|
|
166
|
+
var p = (e) => e.trim() === "*" ? "*" : e.split(",").map((e) => e.trim()).filter(Boolean);
|
|
167
|
+
function m(t, n = {}) {
|
|
168
|
+
if (typeof t?.read != "function") throw TypeError("remoteHandler needs a storage, e.g. fileStorage(folder)");
|
|
169
|
+
let { origin: r, allowHeaders: i = ["authorization", "content-type"], maxBytes: a = 67108864, authorize: o } = n, s = (n.base ?? "/").replace(/\/+$/, ""), c = e(), l = r ? {
|
|
170
|
+
"access-control-allow-origin": r,
|
|
171
|
+
"access-control-expose-headers": "ETag, Retry-After"
|
|
172
|
+
} : {}, u = (e, t = null, n = {}) => new Response(t, {
|
|
173
|
+
status: e,
|
|
174
|
+
headers: {
|
|
175
|
+
"cache-control": "no-store",
|
|
176
|
+
...l,
|
|
177
|
+
...n
|
|
178
|
+
}
|
|
179
|
+
}), m = "GET, PUT, DELETE, OPTIONS", h = (e, t) => {
|
|
180
|
+
let n = e.headers.get("if-match"), r = e.headers.get("if-none-match");
|
|
181
|
+
if (n !== null) {
|
|
182
|
+
let e = p(n);
|
|
183
|
+
if (t === null || e !== "*" && !e.includes(t)) return !0;
|
|
184
|
+
}
|
|
185
|
+
if (r !== null) {
|
|
186
|
+
let e = p(r);
|
|
187
|
+
if (t !== null && (e === "*" || e.includes(t) || e.includes(`W/${t}`))) return !0;
|
|
188
|
+
}
|
|
189
|
+
return !1;
|
|
190
|
+
}, g = async (e, n) => {
|
|
191
|
+
let r = e.signal, i = await t.read(n, { signal: r }), o = i && await d(i);
|
|
192
|
+
if (e.method === "GET") return i ? u(200, i, {
|
|
193
|
+
etag: o,
|
|
194
|
+
"content-type": "application/octet-stream"
|
|
195
|
+
}) : u(404);
|
|
196
|
+
if (h(e, o)) return u(412, null, o ? { etag: o } : {});
|
|
197
|
+
if (e.method === "DELETE") return i ? (await t.delete(n, { signal: r }), u(204)) : u(404);
|
|
198
|
+
if (Number(e.headers.get("content-length") ?? 0) > a) return u(413);
|
|
199
|
+
let s = await f(e, a);
|
|
200
|
+
return s ? (await t.write(n, s, { signal: r }), u(i ? 204 : 201, null, { etag: await d(s) })) : u(413);
|
|
201
|
+
};
|
|
202
|
+
return async (e) => {
|
|
203
|
+
let n = new URL(e.url).pathname;
|
|
204
|
+
if (n !== s && !n.startsWith(`${s}/`)) return u(404);
|
|
205
|
+
if (e.method === "OPTIONS") return u(204, null, {
|
|
206
|
+
allow: m,
|
|
207
|
+
...r ? {
|
|
208
|
+
"access-control-allow-methods": m,
|
|
209
|
+
"access-control-allow-headers": [
|
|
210
|
+
"if-match",
|
|
211
|
+
"if-none-match",
|
|
212
|
+
...i
|
|
213
|
+
].join(", "),
|
|
214
|
+
"access-control-max-age": "600"
|
|
215
|
+
} : {}
|
|
216
|
+
});
|
|
217
|
+
if (o && !await o(e)) return u(403);
|
|
218
|
+
let a = n.slice(s.length + 1);
|
|
219
|
+
if (!a) return e.method === "GET" ? u(200, JSON.stringify(await t.keys({ signal: e.signal })), { "content-type": "application/json" }) : u(405, null, { allow: "GET, OPTIONS" });
|
|
220
|
+
if (![
|
|
221
|
+
"GET",
|
|
222
|
+
"PUT",
|
|
223
|
+
"DELETE"
|
|
224
|
+
].includes(e.method)) return u(405, null, { allow: m });
|
|
225
|
+
let l;
|
|
226
|
+
try {
|
|
227
|
+
l = decodeURIComponent(a);
|
|
228
|
+
} catch {
|
|
229
|
+
return u(400);
|
|
230
|
+
}
|
|
231
|
+
return c(l, () => g(e, l));
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
//#endregion
|
|
235
|
+
export { m as remoteHandler, l as remoteStorage };
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { t as e } from "./queue-C2AsmZge.js";
|
|
2
|
+
import { MargoError as t } from "@margoengine/math/errors";
|
|
3
|
+
//#region ../shared/crc32.js
|
|
4
|
+
var n;
|
|
5
|
+
function r() {
|
|
6
|
+
n = /* @__PURE__ */ new Int32Array(2048);
|
|
7
|
+
for (let e = 0; e < 256; e++) {
|
|
8
|
+
let t = e;
|
|
9
|
+
for (let e = 0; e < 8; e++) t = t & 1 ? 3988292384 ^ t >>> 1 : t >>> 1;
|
|
10
|
+
n[e] = t;
|
|
11
|
+
}
|
|
12
|
+
for (let e = 0; e < 256; e++) for (let t = 1; t < 8; t++) {
|
|
13
|
+
let r = n[(t - 1) * 256 + e];
|
|
14
|
+
n[t * 256 + e] = r >>> 8 ^ n[r & 255];
|
|
15
|
+
}
|
|
16
|
+
return n;
|
|
17
|
+
}
|
|
18
|
+
function i(e, t = 0) {
|
|
19
|
+
let i = n ?? r(), a = e.length, o = a - (a & 7), s = ~t, c = 0;
|
|
20
|
+
for (; c < o; c += 8) s ^= e[c] | e[c + 1] << 8 | e[c + 2] << 16 | e[c + 3] << 24, s = i[1792 + (s & 255)] ^ i[1536 + (s >>> 8 & 255)] ^ i[1280 + (s >>> 16 & 255)] ^ i[1024 + (s >>> 24)] ^ i[768 + e[c + 4]] ^ i[512 + e[c + 5]] ^ i[256 + e[c + 6]] ^ i[e[c + 7]];
|
|
21
|
+
for (; c < a; c++) s = i[(s ^ e[c]) & 255] ^ s >>> 8;
|
|
22
|
+
return ~s >>> 0;
|
|
23
|
+
}
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/safe.ts
|
|
26
|
+
var a = 1297301830, o = 1, s = 20, c = 4, l = ["~a", "~b"], u = 2n ** 64n - 1n, d = (e) => "payload" in e, f = (e) => "bad" in e;
|
|
27
|
+
function p(e, t) {
|
|
28
|
+
let n = new Uint8Array(s + e.length + c), r = new DataView(n.buffer), l = n.length - c;
|
|
29
|
+
return r.setUint32(0, a), r.setUint8(4, o), r.setUint32(8, e.length), r.setBigUint64(12, t), n.set(e, s), r.setUint32(l, i(n.subarray(0, l)), !0), n;
|
|
30
|
+
}
|
|
31
|
+
function m(e) {
|
|
32
|
+
if (e.length < 24) return "it is shorter than a frame";
|
|
33
|
+
let t = new DataView(e.buffer, e.byteOffset, e.byteLength), n = e.length - c;
|
|
34
|
+
return t.getUint32(0) === a ? t.getUint32(8) === n - s ? t.getUint32(n, !0) === i(e.subarray(0, n)) ? t.getUint8(4) === o ? {
|
|
35
|
+
generation: t.getBigUint64(12),
|
|
36
|
+
payload: e.subarray(s, n)
|
|
37
|
+
} : `it has format version ${t.getUint8(4)}; this build reads version ${o}` : "its checksum does not match" : "its length is wrong" : "it is not a checked copy";
|
|
38
|
+
}
|
|
39
|
+
var h = (e, t) => e.length === t.length && e.every((e, n) => e === t[n]);
|
|
40
|
+
function g(n, r = {}) {
|
|
41
|
+
if (typeof n?.read != "function") throw TypeError("safeStorage needs a storage, e.g. memoryStorage()");
|
|
42
|
+
let { verify: i = !0, legacy: a = !1, onRecover: o } = r, s = e(), c = async (e, t) => {
|
|
43
|
+
let r = [];
|
|
44
|
+
for (let i of l) {
|
|
45
|
+
let a = e + i;
|
|
46
|
+
try {
|
|
47
|
+
let e = await n.read(a, t);
|
|
48
|
+
if (e === null) r.push({ name: a });
|
|
49
|
+
else {
|
|
50
|
+
let t = m(e);
|
|
51
|
+
r.push(typeof t == "string" ? {
|
|
52
|
+
name: a,
|
|
53
|
+
bad: t
|
|
54
|
+
} : {
|
|
55
|
+
name: a,
|
|
56
|
+
...t
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
} catch (e) {
|
|
60
|
+
t?.signal?.throwIfAborted(), r.push({
|
|
61
|
+
name: a,
|
|
62
|
+
bad: String(e?.message ?? e)
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return r;
|
|
67
|
+
}, g = (e) => e.filter(d).sort((e, t) => e.generation < t.generation ? 1 : e.generation > t.generation ? -1 : 0), _ = (e) => {
|
|
68
|
+
if (typeof e != "string" || !e) throw TypeError("Save key must be a non-empty string, e.g. \"slot-1\"");
|
|
69
|
+
};
|
|
70
|
+
return {
|
|
71
|
+
async read(e, r) {
|
|
72
|
+
return _(e), s(e, async () => {
|
|
73
|
+
let i = await c(e, r), [s] = g(i), l = i.filter(f);
|
|
74
|
+
if (s) {
|
|
75
|
+
for (let t of l) o?.({
|
|
76
|
+
key: e,
|
|
77
|
+
copy: t.name,
|
|
78
|
+
reason: t.bad
|
|
79
|
+
});
|
|
80
|
+
return s.payload.slice();
|
|
81
|
+
}
|
|
82
|
+
if (l.length) throw new t("failed", `Save '${e}' is damaged (${l.map((e) => `${e.name}: ${e.bad}`).join(", ")}); no good copy is left, so load another save or delete this one`);
|
|
83
|
+
let u = await n.read(e, r);
|
|
84
|
+
if (u === null || a) return u;
|
|
85
|
+
throw new t("failed", `Save '${e}' has no checksum, so it cannot be trusted; pass legacy: true to read saves from before safeStorage`);
|
|
86
|
+
});
|
|
87
|
+
},
|
|
88
|
+
async write(e, r, o) {
|
|
89
|
+
if (_(e), !(r instanceof Uint8Array)) throw TypeError("Save bytes must be a Uint8Array; encode the document with encodeSave");
|
|
90
|
+
return s(e, async () => {
|
|
91
|
+
let s = await c(e, o), [l] = g(s);
|
|
92
|
+
if (l?.generation === u) throw new t("failed", `Save '${e}' is at the last generation, 2^64 - 1, so another write would wrap to 0 and lose it; delete the key and save again`);
|
|
93
|
+
let d = s.find((e) => e !== l).name, f = p(r, (l?.generation ?? 0n) + 1n);
|
|
94
|
+
if (await n.write(d, f, o), i) {
|
|
95
|
+
let r = await n.read(d, o);
|
|
96
|
+
if (r === null || !h(r, f)) throw new t("failed", `The storage did not keep save '${e}', and the last good save stands; check its free space and save again`);
|
|
97
|
+
}
|
|
98
|
+
a && await n.delete(e, o);
|
|
99
|
+
});
|
|
100
|
+
},
|
|
101
|
+
async delete(e, t) {
|
|
102
|
+
return _(e), s(e, async () => {
|
|
103
|
+
let r = await c(e, t), [i] = g(r), a = !1;
|
|
104
|
+
for (let e of r.filter((e) => e !== i)) a = await n.delete(e.name, t) || a;
|
|
105
|
+
return i && (a = await n.delete(i.name, t) || a), await n.delete(e, t) || a;
|
|
106
|
+
});
|
|
107
|
+
},
|
|
108
|
+
async keys(e) {
|
|
109
|
+
let t = /* @__PURE__ */ new Set();
|
|
110
|
+
for (let r of await n.keys(e)) t.add(l.some((e) => r.endsWith(e)) ? r.slice(0, -2) : r);
|
|
111
|
+
return [...t].sort();
|
|
112
|
+
},
|
|
113
|
+
async check(e, n) {
|
|
114
|
+
return _(e), s(e, async () => {
|
|
115
|
+
let r = await c(e, n), i = g(r), a = i[0]?.generation ?? 0n;
|
|
116
|
+
if (a > BigInt(2 ** 53 - 1)) throw new t("failed", `Save '${e}' has generation ${a}, above 2^53 - 1, which a number cannot hold exactly; read() still loads it`);
|
|
117
|
+
return {
|
|
118
|
+
ok: i.length > 0,
|
|
119
|
+
good: i.length,
|
|
120
|
+
bad: r.filter(f).length,
|
|
121
|
+
generation: Number(a)
|
|
122
|
+
};
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
//#endregion
|
|
128
|
+
export { g as t };
|
package/dist/safe.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { SaveStorage, StorageCallOptions } from './storage.js';
|
|
2
|
+
/** What a read found beside the copy it gave back. */
|
|
3
|
+
export interface SafeRecovery {
|
|
4
|
+
/** The key the read asked for. */
|
|
5
|
+
key: string;
|
|
6
|
+
/** Which copy was bad: `key~a` or `key~b`. */
|
|
7
|
+
copy: string;
|
|
8
|
+
/** Why: a short description, or the error the storage gave. */
|
|
9
|
+
reason: string;
|
|
10
|
+
}
|
|
11
|
+
/** Options of {@link safeStorage}. */
|
|
12
|
+
export interface SafeStorageOptions {
|
|
13
|
+
/** Read each write back and compare it. Default true. */
|
|
14
|
+
verify?: boolean;
|
|
15
|
+
/** Accept a save written before this wrapper, stored plainly under `key`, with no way to check it. Default false. */
|
|
16
|
+
legacy?: boolean;
|
|
17
|
+
/** Called when a read passes over a bad copy. The save is good; the next write replaces the bad copy. */
|
|
18
|
+
onRecover?(recovery: SafeRecovery): void;
|
|
19
|
+
}
|
|
20
|
+
/** The result of {@link SafeStorage.check}. */
|
|
21
|
+
export interface SafeCheck {
|
|
22
|
+
/** True when a read gives a checked save. */
|
|
23
|
+
ok: boolean;
|
|
24
|
+
/** Good copies: 0, 1 or 2. */
|
|
25
|
+
good: number;
|
|
26
|
+
/** Bad copies: 0, 1 or 2. */
|
|
27
|
+
bad: number;
|
|
28
|
+
/**
|
|
29
|
+
* The newest good copy's generation, 0 when there is none. Exact: a generation above 2^53 - 1, which only a copy
|
|
30
|
+
* written elsewhere can hold, makes `check` throw rather than round it.
|
|
31
|
+
*/
|
|
32
|
+
generation: number;
|
|
33
|
+
}
|
|
34
|
+
/** A {@link SaveStorage} with checked copies. */
|
|
35
|
+
export interface SafeStorage extends SaveStorage {
|
|
36
|
+
/** Reads both copies of `key` and reports on them, changing nothing. */
|
|
37
|
+
check(key: string, options?: StorageCallOptions): Promise<SafeCheck>;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Wraps a storage so a failed or torn write never loses the last good save, and damage is found on read.
|
|
41
|
+
* Write costs two reads, one write and, with `verify`, one more read; a key takes twice the room.
|
|
42
|
+
* @example
|
|
43
|
+
* const storage = safeStorage(fileStorage('./saves'), { onRecover: ({ key }) => console.warn('recovered', key) });
|
|
44
|
+
* await saveGame(storage, 'slot-1', document);
|
|
45
|
+
*/
|
|
46
|
+
export declare function safeStorage(storage: SaveStorage, options?: SafeStorageOptions): SafeStorage;
|
package/dist/safe.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as safeStorage } from "./safe-DVo3kH0O.js";
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Json } from './document.js';
|
|
2
|
+
/** A player from animation or animator; definitions and procedural callbacks belong to the app. */
|
|
3
|
+
export interface PlaybackBinding {
|
|
4
|
+
captureState(): object;
|
|
5
|
+
restoreState(state: never): unknown;
|
|
6
|
+
}
|
|
7
|
+
/** Clustered, DirectionalLights and AreaLights expose this interface, including per-light shadow settings. */
|
|
8
|
+
export interface LightBinding {
|
|
9
|
+
readonly list: readonly object[];
|
|
10
|
+
setLights(lights: never): unknown;
|
|
11
|
+
}
|
|
12
|
+
/** Stable application/model ids connect a document to its loaded objects. No GPU objects are serialized. */
|
|
13
|
+
export interface SceneStateBindings {
|
|
14
|
+
animations?: Readonly<Record<string, PlaybackBinding>>;
|
|
15
|
+
lights?: Readonly<Record<string, LightBinding>>;
|
|
16
|
+
/** Directional Shadows.options or other mutable shadow settings, by stable id. */
|
|
17
|
+
shadows?: Readonly<Record<string, object>>;
|
|
18
|
+
}
|
|
19
|
+
/** Versioned detached values for stable playback, light and shadow bindings. */
|
|
20
|
+
export interface SavedSceneState {
|
|
21
|
+
version: 1;
|
|
22
|
+
animations: Record<string, Json>;
|
|
23
|
+
lights: Record<string, Json>;
|
|
24
|
+
shadows: Record<string, Json>;
|
|
25
|
+
}
|
|
26
|
+
/** Capture exact clip times, blend parameters, weights, masks, fades, triggers and light/shadow objects. */
|
|
27
|
+
export declare function captureSceneState(bindings: SceneStateBindings): SavedSceneState;
|
|
28
|
+
/** Apply to already loaded models and installed lighting; failure rolls back every changed binding. */
|
|
29
|
+
export declare function restoreSceneState(state: SavedSceneState, bindings: SceneStateBindings): void;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { MargoError as e } from "@margoengine/math/errors";
|
|
2
|
+
//#region src/scene-state.ts
|
|
3
|
+
function t(n, r = /* @__PURE__ */ new Set()) {
|
|
4
|
+
if (n === null || typeof n == "string" || typeof n == "boolean" || typeof n == "number" && Number.isFinite(n)) return n;
|
|
5
|
+
if (typeof n != "object" || !n || r.has(n)) throw new e("state", "Scene state must contain finite JSON values; keep callbacks and GPU resources in the bindings");
|
|
6
|
+
r.add(n);
|
|
7
|
+
let i;
|
|
8
|
+
if (Array.isArray(n) || ArrayBuffer.isView(n)) i = Array.from(n, (e) => t(e, r));
|
|
9
|
+
else {
|
|
10
|
+
if (Object.getPrototypeOf(n) !== Object.prototype && Object.getPrototypeOf(n) !== null) throw new e("state", "Scene state contains a runtime object; bind its portable settings instead");
|
|
11
|
+
let a = Object.entries(n).filter(([, e]) => e !== void 0);
|
|
12
|
+
i = Object.fromEntries(a.map(([e, n]) => [e, t(n, r)]));
|
|
13
|
+
}
|
|
14
|
+
return r.delete(n), i;
|
|
15
|
+
}
|
|
16
|
+
function n(e) {
|
|
17
|
+
return {
|
|
18
|
+
version: 1,
|
|
19
|
+
animations: Object.fromEntries(Object.entries(e.animations ?? {}).map(([e, n]) => [e, t(n.captureState())])),
|
|
20
|
+
lights: Object.fromEntries(Object.entries(e.lights ?? {}).map(([e, n]) => [e, t(n.list)])),
|
|
21
|
+
shadows: Object.fromEntries(Object.entries(e.shadows ?? {}).map(([e, n]) => [e, t(n)]))
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function r(n, r) {
|
|
25
|
+
let i = t(n);
|
|
26
|
+
if (i.version !== 1) throw new e("state", "Unknown scene state version; use version 1");
|
|
27
|
+
let a = [];
|
|
28
|
+
for (let n of [
|
|
29
|
+
"animations",
|
|
30
|
+
"lights",
|
|
31
|
+
"shadows"
|
|
32
|
+
]) {
|
|
33
|
+
let o = i[n];
|
|
34
|
+
if (!o || Array.isArray(o) || typeof o != "object") throw new e("state", `Missing scene state ${n}; capture the complete state`);
|
|
35
|
+
for (let [i, s] of Object.entries(o)) {
|
|
36
|
+
let o = r[n]?.[i];
|
|
37
|
+
if (!o || !Object.hasOwn(r[n], i)) throw new e("state", `Missing ${n} binding '${i}'; load and bind that object before restoring`);
|
|
38
|
+
if (n === "animations") {
|
|
39
|
+
let e = o, n = t(e.captureState());
|
|
40
|
+
a.push({
|
|
41
|
+
apply: () => {
|
|
42
|
+
e.restoreState(s);
|
|
43
|
+
},
|
|
44
|
+
undo: () => {
|
|
45
|
+
e.restoreState(n);
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
} else if (n === "lights") {
|
|
49
|
+
if (!Array.isArray(s)) throw new e("state", `Light state '${i}' must be an array`);
|
|
50
|
+
let n = o, r = t(n.list);
|
|
51
|
+
a.push({
|
|
52
|
+
apply: () => {
|
|
53
|
+
n.setLights(s);
|
|
54
|
+
},
|
|
55
|
+
undo: () => {
|
|
56
|
+
n.setLights(r);
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
} else {
|
|
60
|
+
if (!s || Array.isArray(s) || typeof s != "object") throw new e("state", `Shadow state '${i}' must be an object`);
|
|
61
|
+
let n = t(o), r = (e) => {
|
|
62
|
+
for (let e of Object.keys(o)) Reflect.deleteProperty(o, e);
|
|
63
|
+
Object.defineProperties(o, Object.getOwnPropertyDescriptors(e));
|
|
64
|
+
};
|
|
65
|
+
a.push({
|
|
66
|
+
apply: () => r(s),
|
|
67
|
+
undo: () => r(n)
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
let o = 0;
|
|
73
|
+
try {
|
|
74
|
+
for (let e of a) o++, e.apply();
|
|
75
|
+
} catch (e) {
|
|
76
|
+
let t = [e];
|
|
77
|
+
for (; o;) try {
|
|
78
|
+
a[--o].undo();
|
|
79
|
+
} catch (e) {
|
|
80
|
+
t.push(e);
|
|
81
|
+
}
|
|
82
|
+
throw t.length > 1 ? AggregateError(t, "Scene state restore and rollback failed") : e;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
//#endregion
|
|
86
|
+
export { n as captureSceneState, r as restoreSceneState };
|
package/dist/signed.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type SafeStorage, type SafeStorageOptions } from './safe.js';
|
|
2
|
+
import type { SaveStorage } from './storage.js';
|
|
3
|
+
/** Options for {@link signedStorage}; unsigned legacy data is never accepted. */
|
|
4
|
+
export interface SignedStorageOptions extends Omit<SafeStorageOptions, 'legacy'> {
|
|
5
|
+
/** WebCrypto provider. Default globalThis.crypto.subtle, resolved on first use. */
|
|
6
|
+
subtle?: SubtleCrypto;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Two-copy safeStorage with HMAC-SHA-256 authentication of every copy, its physical key and generation included.
|
|
10
|
+
* Key is a secret HMAC/SHA-256 CryptoKey with sign+verify usages, or at least 32 random bytes (copied on creation).
|
|
11
|
+
* Import and crypto operations are lazy; keys are never saved. Every read uses WebCrypto.verify before safeStorage sees bytes.
|
|
12
|
+
* A forged/torn newest copy is reported through onRecover and falls back to the older authenticated copy.
|
|
13
|
+
* Authentication does not encrypt saves or prevent replay of an older valid copy under the same physical key.
|
|
14
|
+
* @throws TypeError for an unsuitable key or storage; supply an HMAC-SHA-256 signing/verifying key and a SaveStorage.
|
|
15
|
+
* @throws MargoError 'unsupported' without WebCrypto, 'failed' when no authenticated copy remains. Restore a trusted backup.
|
|
16
|
+
*/
|
|
17
|
+
export declare function signedStorage(storage: SaveStorage, key: CryptoKey | Uint8Array, options?: SignedStorageOptions): SafeStorage;
|