@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/load.d.ts ADDED
@@ -0,0 +1,74 @@
1
+ import { type SaveDocument, type ValidateOptions } from './document.js';
2
+ import type { Migrations } from './migrations.js';
3
+ import { type ResolvedEntity } from './prefab.js';
4
+ import type { SaveStorage } from './storage.js';
5
+ /**
6
+ * How a world takes a load. `create` builds one entity (off-screen, or marked as loading) and returns your handle;
7
+ * `link` (optional) is called for every entity once all exist, to connect references; `commit` (optional) makes the
8
+ * load visible (swap the scene, clear the old world). `destroy` undoes one `create` and is called, latest first, when
9
+ * a later step fails.
10
+ */
11
+ export interface WorldAdapter<H> {
12
+ create(entity: ResolvedEntity): H;
13
+ link?(handle: H, entity: ResolvedEntity, resolve: (id: string) => H): void;
14
+ commit?(handles: ReadonlyMap<string, H>): void;
15
+ destroy(handle: H): void;
16
+ }
17
+ /** Options of {@link loadWorld} and {@link loadGame}. */
18
+ export interface LoadOptions extends ValidateOptions {
19
+ /** Migrations that bring older saves to the current schema version (default none: a save loads at the version it has). */
20
+ migrations?: Migrations;
21
+ /** Stops the load before the commit; nothing stays built. */
22
+ signal?: AbortSignal;
23
+ }
24
+ /**
25
+ * Load a save into a world through `adapter`, all or nothing. Returns the handles by entity id.
26
+ * @throws TypeError for an invalid document (naming its first problem's path and fix); MargoError `'failed'` when a
27
+ * migration fails or the adapter throws (the error is its `cause`), after destroying everything built; the signal's
28
+ * reason when it aborts.
29
+ */
30
+ export declare function loadWorld<H>(document: SaveDocument | string | unknown, adapter: WorldAdapter<H>, options?: LoadOptions): Map<string, H>;
31
+ /** Options of {@link saveGame}. */
32
+ export interface SaveGameOptions {
33
+ /** Gzip the save (default true when CompressionStream exists). */
34
+ compress?: boolean;
35
+ /** Checks the document before writing (component checks); an invalid save is never written. */
36
+ validate?: ValidateOptions;
37
+ signal?: AbortSignal;
38
+ }
39
+ /**
40
+ * Validate `document` and write it to `storage` under `key` in one step (encoded, compressed by default).
41
+ * @throws TypeError for an invalid document; nothing is written.
42
+ */
43
+ export declare function saveGame(storage: SaveStorage, key: string, document: SaveDocument, options?: SaveGameOptions): Promise<void>;
44
+ /**
45
+ * Read the save under `key`: decoded, migrated to the current version and validated. Null when there is none.
46
+ * Load it into your world with {@link loadWorld}.
47
+ * @throws TypeError for a damaged or invalid save; MargoError `'failed'` when a migration fails.
48
+ */
49
+ export declare function loadGame(storage: SaveStorage, key: string, options?: LoadOptions): Promise<SaveDocument | null>;
50
+ /** A numeric ECS component as `@margoengine/ecs` makes it (structural, so this package does not depend on ecs). */
51
+ export interface EcsComponentLike {
52
+ readonly fields: Readonly<Record<string, ArrayLike<number>>>;
53
+ readonly entities: ArrayLike<number>;
54
+ readonly size: number;
55
+ index(entity: number): number;
56
+ add(entity: number, values?: Record<string, number>): number;
57
+ }
58
+ /** The ECS world calls the adapter uses. */
59
+ export interface EcsWorldLike {
60
+ create(): number;
61
+ destroy(entity: number): void;
62
+ alive(entity: number): boolean;
63
+ }
64
+ /**
65
+ * The entities of an ECS world that hold any of `components`, as a save document (component fields as numbers,
66
+ * entity ids as `e<entity>`). Entities are listed in a stable order: by first component, then row.
67
+ */
68
+ export declare function saveEcs(world: EcsWorldLike, components: Readonly<Record<string, EcsComponentLike>>, version?: number): SaveDocument;
69
+ /**
70
+ * A {@link WorldAdapter} for an `@margoengine/ecs` World: each entity becomes a new ECS entity with the named
71
+ * components' fields. Values are checked by the components themselves (a value that does not fit a field throws,
72
+ * and the whole load is undone). Components the adapter does not know are refused with a TypeError naming them.
73
+ */
74
+ export declare function ecsAdapter(world: EcsWorldLike, components: Readonly<Record<string, EcsComponentLike>>): WorldAdapter<number>;
@@ -0,0 +1,12 @@
1
+ // @ts-ignore optional peer: its types apply when it is installed
2
+ import { type MaterialCaptureOptions, type MaterialRestoreOptions, type MaterialLibrary, type MaterialKinds, type RestoredMaterials, type TypedMaterialRestoreOptions } from '@margoengine/materials/serialization';
3
+ // @ts-ignore optional peer: its types apply when it is installed
4
+ export type { MaterialLibrary, MaterialClass, MaterialKinds, RestoredMaterials, TypedMaterialRestoreOptions, MaterialCaptureOptions, MaterialRestoreOptions, } from '@margoengine/materials/serialization';
5
+ /** Lossless material library: kind, all factors, maps, per-slot UVs, render state and shader parameters. */
6
+ export declare function captureMaterials(materials: Readonly<Record<string, object>>, options?: MaterialCaptureOptions): Promise<MaterialLibrary>;
7
+ /**
8
+ * Recreate materials and shared textures; install returned objects on the loaded scene's meshes.
9
+ * With `expect: { red: PbrMaterial }` each named result is checked and typed as that class.
10
+ */
11
+ export declare function restoreMaterials<K extends MaterialKinds>(library: MaterialLibrary, options: TypedMaterialRestoreOptions<K>): Promise<RestoredMaterials<K>>;
12
+ export declare function restoreMaterials(library: MaterialLibrary, options?: MaterialRestoreOptions): Promise<Record<string, object>>;
@@ -0,0 +1,16 @@
1
+ import { captureMaterialLibrary as e, restoreMaterialLibrary as t } from "@margoengine/materials/serialization";
2
+ //#region src/materials.ts
3
+ function n(t, n = {}) {
4
+ return e(t, {
5
+ ...n,
6
+ loadCodecs: n.loadCodecs ?? (async () => (await import("@margoengine/shader/serialization")).shaderMaterialCodecs)
7
+ });
8
+ }
9
+ function r(e, n = {}) {
10
+ return t(e, {
11
+ ...n,
12
+ loadCodecs: n.loadCodecs ?? (async () => (await import("@margoengine/shader/serialization")).shaderMaterialCodecs)
13
+ });
14
+ }
15
+ //#endregion
16
+ export { n as captureMaterials, r as restoreMaterials };
@@ -0,0 +1,31 @@
1
+ import type { SaveDocument } from './document.js';
2
+ /** One migration step: takes a document at version `from` and returns it at `from + 1` (a copy or the same object). */
3
+ export type Migration = (document: SaveDocument) => SaveDocument;
4
+ /**
5
+ * Migrations between schema versions. Register one step per version (`register(1, fn)` moves 1 to 2); `migrate`
6
+ * applies the steps from the document's version up to `latest` (or a given target) on a deep copy, so the input is
7
+ * never changed and a failing step leaves nothing half-migrated.
8
+ */
9
+ export declare class Migrations {
10
+ private readonly current;
11
+ private readonly steps;
12
+ /** @param latest The current schema version (default 1, or the highest registered `from + 1`, whichever is higher). */
13
+ constructor(current?: number);
14
+ /** The version `migrate` brings documents to by default. */
15
+ get latest(): number;
16
+ /**
17
+ * Register the step from version `from` to `from + 1`.
18
+ * @throws RangeError for a version that is not a whole number of 1 or more; MargoError `'state'` for a version
19
+ * that already has a step.
20
+ */
21
+ register(from: number, migration: Migration): this;
22
+ /** True when every step from `from` up to `to` is registered. */
23
+ covers(from: number, to?: number): boolean;
24
+ /**
25
+ * A copy of `document` at version `to` (default `latest`). A document already there is returned as a copy.
26
+ * @throws MargoError `'failed'` when a step is missing, a step throws (the error is its `cause`), or a step returns
27
+ * something that is not a save at the next version; RangeError for a document newer than `to` (a save from a
28
+ * newer game).
29
+ */
30
+ migrate(document: SaveDocument, to?: number): SaveDocument;
31
+ }
package/dist/node.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ import type { SaveStorage } from './storage.js';
2
+ /** Options of {@link fileStorage}. */
3
+ export interface FileStorageOptions {
4
+ /**
5
+ * The largest save a read accepts, in bytes; a bigger file is refused from its size, before any of it is read.
6
+ * Default 268,435,456 (256 MiB), the `decodeSave` default.
7
+ */
8
+ maxBytes?: number;
9
+ }
10
+ /**
11
+ * Saves as files in `directory` (created on first write): the key, percent-escaped with its capitals, and `.save`. Writes go to a
12
+ * temporary file first, made exclusively under this process's id, and are renamed over the old save, which is atomic on
13
+ * one file system, and the folder is then fsynced where the system has that. On Windows a save that
14
+ * another program has open cannot be replaced: the write rejects with MargoError `'failed'` and the old save stands.
15
+ * Use one writer per folder: a second process saving the same key races the first, and the last rename wins.
16
+ * @throws RangeError when `maxBytes` is not a whole number of 0 or more.
17
+ */
18
+ export declare function fileStorage(directory: string, options?: FileStorageOptions): SaveStorage;
package/dist/node.js ADDED
@@ -0,0 +1,108 @@
1
+ import { t as e } from "./queue-C2AsmZge.js";
2
+ import { MargoError as t } from "@margoengine/math/errors";
3
+ import { mkdir as n, open as r, readdir as i, rename as a, rm as o, writeFile as s } from "node:fs/promises";
4
+ import { dirname as c, join as l, resolve as u, sep as d, toNamespacedPath as f } from "node:path";
5
+ //#region src/node.ts
6
+ var p = ".save", m = (e) => encodeURIComponent(e).replace(/%[0-9A-F]{2}|[A-Z*]/g, (e) => e.length > 1 ? e : `%${e.charCodeAt(0).toString(16).toUpperCase()}`) + p, h = (e) => {
7
+ if (typeof e != "string" || !e) throw TypeError("Save key must be a non-empty string, e.g. \"slot-1\"");
8
+ }, g = (e) => e?.code === "ENOENT", _ = (e, t) => t?.aborted ? t.reason : e, v = 0, y = e(), b = (e) => process.platform === "win32" && [
9
+ "EPERM",
10
+ "EACCES",
11
+ "EBUSY"
12
+ ].includes(e?.code ?? "");
13
+ async function x(e) {
14
+ if (process.platform === "win32") return;
15
+ let t = await r(e, "r");
16
+ try {
17
+ await t.sync();
18
+ } catch (e) {
19
+ if (!["EINVAL", "ENOTSUP"].includes(e?.code ?? "")) throw e;
20
+ } finally {
21
+ await t.close();
22
+ }
23
+ }
24
+ function S(e, S = {}) {
25
+ if (typeof e != "string" || !e) throw TypeError("fileStorage needs a directory path, e.g. \"./saves\"");
26
+ let C = S?.maxBytes ?? 268435456;
27
+ if (!Number.isSafeInteger(C) || C < 0) throw RangeError("fileStorage maxBytes must be a whole number of bytes, 0 or more; pass a byte count");
28
+ let w = (t) => l(e, m(t)), T = async (e, n, i) => {
29
+ let a = await r(n);
30
+ try {
31
+ let { size: n } = await a.stat();
32
+ if (n > C) throw new t("failed", `Save '${e}' is ${n} bytes, past maxBytes ${C}; it is not a save of this game, or pass a larger maxBytes to fileStorage`);
33
+ let r = new Uint8Array(n), o = 0;
34
+ for (; o < n;) {
35
+ i?.throwIfAborted();
36
+ let { bytesRead: e } = await a.read(r, o, n - o, o);
37
+ if (!e) break;
38
+ o += e;
39
+ }
40
+ return o === n ? r : r.subarray(0, o);
41
+ } finally {
42
+ await a.close();
43
+ }
44
+ };
45
+ return {
46
+ async read(e, t) {
47
+ h(e), t?.signal?.throwIfAborted();
48
+ try {
49
+ let n = w(e);
50
+ return await y(u(n), () => T(e, n, t?.signal));
51
+ } catch (e) {
52
+ if (g(e)) return null;
53
+ throw _(e, t?.signal);
54
+ }
55
+ },
56
+ async write(r, i, l) {
57
+ if (h(r), !(i instanceof Uint8Array)) throw TypeError("Save bytes must be a Uint8Array; encode the document with encodeSave");
58
+ l?.signal?.throwIfAborted();
59
+ let p = await n(e, { recursive: !0 }), m = `${w(r)}.${process.pid}-${Date.now().toString(36)}-${++v}.tmp`;
60
+ try {
61
+ await s(m, i, {
62
+ signal: l?.signal,
63
+ flush: !0,
64
+ flag: "wx"
65
+ }), l?.signal?.throwIfAborted(), await y(u(w(r)), () => a(m, w(r)));
66
+ } catch (e) {
67
+ throw e?.code === "EEXIST" ? Object.assign(new t("failed", `Save '${r}' could not make its temporary file, as another writer has one of that name; use one fileStorage writer per folder`), { cause: e }) : (await o(m, { force: !0 }), b(e) && !l?.signal?.aborted ? Object.assign(new t("failed", `Save '${r}' is open in another program, so the old save stands; close it and save again`), { cause: e }) : _(e, l?.signal));
68
+ }
69
+ if (await x(e), p) {
70
+ let t = f(u(e)).split(d).length - p.split(d).length;
71
+ for (let n = 0, r = c(u(e)); n <= t; n++, r = c(r)) await x(r);
72
+ }
73
+ },
74
+ async delete(e, t) {
75
+ h(e), t?.signal?.throwIfAborted();
76
+ try {
77
+ return await y(u(w(e)), () => o(w(e))), !0;
78
+ } catch (e) {
79
+ if (g(e)) return !1;
80
+ throw e;
81
+ }
82
+ },
83
+ async keys(t) {
84
+ t?.signal?.throwIfAborted();
85
+ let n;
86
+ try {
87
+ n = await i(e);
88
+ } catch (e) {
89
+ if (g(e)) return [];
90
+ throw e;
91
+ }
92
+ let r = [];
93
+ for (let e of n) {
94
+ if (!e.endsWith(p)) continue;
95
+ let t;
96
+ try {
97
+ t = decodeURIComponent(e.slice(0, -5));
98
+ } catch {
99
+ continue;
100
+ }
101
+ t && m(t) === e && r.push(t);
102
+ }
103
+ return r.sort();
104
+ }
105
+ };
106
+ }
107
+ //#endregion
108
+ export { S as fileStorage };
package/dist/opfs.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { type SaveStorage } from './storage.js';
2
+ /** Options of {@link opfsStorage}. */
3
+ export interface OPFSStorageOptions {
4
+ /** Subdirectory of the origin's private root. Default 'margo-saves'. */
5
+ namespace?: string;
6
+ /** An already opened private root, for workers or an application-owned directory. Default navigator.storage.getDirectory(). */
7
+ directory?: FileSystemDirectoryHandle;
8
+ }
9
+ /**
10
+ * Origin Private File System storage. A writable stream's close atomically swaps its temporary file into place.
11
+ * Operations on one key run in call order per adapter; separate adapters/tabs have last-close-wins semantics.
12
+ * Abort is checked after each filesystem await and immediately before close, the irreversible commit point.
13
+ * Empty files left by an interrupted first write are uncommitted and do not appear in reads or keys.
14
+ * @throws MargoError 'unsupported' without OPFS; 'failed' for an invalid committed frame. Use another adapter or delete damaged data.
15
+ * @throws TypeError for invalid namespace/key/bytes; RangeError for an oversized key. Supply valid options and shorter keys.
16
+ */
17
+ export declare function opfsStorage(options?: OPFSStorageOptions): SaveStorage;
package/dist/opfs.js ADDED
@@ -0,0 +1,105 @@
1
+ import { i as e, t } from "./storage-DZeyzOh1.js";
2
+ import { t as n } from "./queue-C2AsmZge.js";
3
+ import { MargoError as r } from "@margoengine/math/errors";
4
+ //#region src/opfs.ts
5
+ var i = new Uint8Array([
6
+ 77,
7
+ 79,
8
+ 80,
9
+ 70,
10
+ 1
11
+ ]), a = (e) => e?.name === "NotFoundError", o = (t) => {
12
+ if (typeof t != "string" || !t || new TextDecoder().decode(new TextEncoder().encode(t)) !== t) throw TypeError("OPFS save key must be non-empty well-formed Unicode; supply a slot name");
13
+ let n = "s-" + e(new TextEncoder().encode(t)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "") + ".bin";
14
+ if (n.length > 240) throw RangeError("OPFS save key exceeds 175 UTF-8 bytes; use a shorter slot name");
15
+ return n;
16
+ }, s = (e) => {
17
+ if (/^s-[A-Za-z0-9_-]+\.bin$/.test(e)) try {
18
+ let n = new TextDecoder("utf-8", { fatal: !0 }).decode(t(e.slice(2, -4).replaceAll("-", "+").replaceAll("_", "/")));
19
+ return o(n) === e ? n : void 0;
20
+ } catch (e) {
21
+ if (e instanceof TypeError || e instanceof RangeError || e?.name === "InvalidCharacterError") return;
22
+ throw e;
23
+ }
24
+ };
25
+ function c(e = {}) {
26
+ let { namespace: t = "margo-saves", directory: c } = e;
27
+ if (!t || t === "." || t === ".." || /[/\\\0]/.test(t)) throw TypeError("OPFS namespace must be a single directory name; use a name such as margo-saves");
28
+ let l = n(), u, d = async (e) => {
29
+ if (e?.throwIfAborted(), !u) {
30
+ let n = globalThis.navigator?.storage;
31
+ if (!c && typeof n?.getDirectory != "function") throw new r("unsupported", "OPFS is unavailable; use indexedDBStorage or memoryStorage, or supply a private directory");
32
+ let i = c ?? await n.getDirectory();
33
+ e?.throwIfAborted();
34
+ let a = await i.getDirectoryHandle(t, { create: !0 });
35
+ e?.throwIfAborted(), u = a;
36
+ }
37
+ return u;
38
+ }, f = async (e, t) => {
39
+ try {
40
+ return await (await e.getFileHandle(t)).getFile();
41
+ } catch (e) {
42
+ if (a(e)) return null;
43
+ throw e;
44
+ }
45
+ };
46
+ return {
47
+ async read(e, t) {
48
+ let n = o(e), a = t?.signal;
49
+ return l(e, async () => {
50
+ let t = await d(a), o = await f(t, n);
51
+ if (a?.throwIfAborted(), !o?.size) return null;
52
+ let s = new Uint8Array(await o.arrayBuffer());
53
+ if (a?.throwIfAborted(), !i.every((e, t) => s[t] === e)) throw new r("failed", `OPFS save '${e}' has an invalid frame; restore a backup or delete it`);
54
+ return s.slice(i.length);
55
+ });
56
+ },
57
+ async write(e, t, n) {
58
+ let r = o(e), a = n?.signal;
59
+ if (!(t instanceof Uint8Array)) throw TypeError("OPFS save bytes must be a Uint8Array; use encodeSave");
60
+ let s = new Uint8Array(i.length + t.length);
61
+ return s.set(i), s.set(t, i.length), l(e, async () => {
62
+ let e = await d(a);
63
+ a?.throwIfAborted();
64
+ let t = await e.getFileHandle(r, { create: !0 });
65
+ a?.throwIfAborted();
66
+ let n = await t.createWritable({ keepExistingData: !1 });
67
+ try {
68
+ a?.throwIfAborted(), await n.write(s), a?.throwIfAborted(), await n.close();
69
+ } catch (e) {
70
+ try {
71
+ await n.abort(e);
72
+ } catch (t) {
73
+ throw AggregateError([e, t], "OPFS write and cleanup failed; inspect both errors and restore a backup");
74
+ }
75
+ throw e;
76
+ }
77
+ });
78
+ },
79
+ async delete(e, t) {
80
+ let n = o(e), r = t?.signal;
81
+ return l(e, async () => {
82
+ let e = await d(r), t = await f(e, n);
83
+ if (r?.throwIfAborted(), !t) return !1;
84
+ try {
85
+ await e.removeEntry(n);
86
+ } catch (e) {
87
+ if (a(e)) return !1;
88
+ throw e;
89
+ }
90
+ return t.size > 0;
91
+ });
92
+ },
93
+ async keys(e) {
94
+ let t = e?.signal, n = await d(t), r = [];
95
+ for await (let [e, i] of n.entries()) {
96
+ if (t?.throwIfAborted(), i.kind !== "file") continue;
97
+ let a = s(e);
98
+ a !== void 0 && (await f(n, e))?.size && r.push(a);
99
+ }
100
+ return t?.throwIfAborted(), r.sort();
101
+ }
102
+ };
103
+ }
104
+ //#endregion
105
+ export { c as opfsStorage };
@@ -0,0 +1,277 @@
1
+ //#region src/document.ts
2
+ var e = 32, t = 1e6, n = 64, r = (e) => typeof e == "object" && !!e && !Array.isArray(e), i = (e, t) => Array.isArray(e) && e.length === t && e.every((e) => typeof e == "number" && Number.isFinite(e));
3
+ function a(e, t = 0) {
4
+ if (t > 64) return "nests deeper than 64 levels; flatten it";
5
+ if (e === null || typeof e == "boolean" || typeof e == "string") return null;
6
+ if (typeof e == "number") return Number.isFinite(e) ? null : "holds a non-finite number; JSON has no NaN or Infinity";
7
+ if (Array.isArray(e)) {
8
+ for (let n of e) {
9
+ let e = a(n, t + 1);
10
+ if (e) return e;
11
+ }
12
+ return null;
13
+ }
14
+ if (r(e) && Object.getPrototypeOf(e) === Object.prototype) {
15
+ for (let n of Object.values(e)) {
16
+ let e = a(n, t + 1);
17
+ if (e) return e;
18
+ }
19
+ return null;
20
+ }
21
+ return `holds a ${typeof e} that is not JSON; store plain objects, arrays, strings, numbers, booleans and null`;
22
+ }
23
+ function o(e, t = "", n = []) {
24
+ if (Array.isArray(e)) e.forEach((e, r) => o(e, `${t}[${r}]`, n));
25
+ else if (r(e)) {
26
+ if (typeof e.$ref == "string" && Object.keys(e).length === 1) n.push({
27
+ path: t,
28
+ id: e.$ref
29
+ });
30
+ else for (let [r, i] of Object.entries(e)) o(i, `${t}.${r}`, n);
31
+ }
32
+ return n;
33
+ }
34
+ function s(e, n = {}) {
35
+ let s = [], c = (e, t) => {
36
+ s.length < 1e3 && s.push({
37
+ path: e,
38
+ message: t
39
+ });
40
+ };
41
+ if (!r(e)) return c("", "must be a save document {format: \"margo-save\", version, entities}"), s;
42
+ if (e.format !== "margo-save" && c("format", "must be 'margo-save'; this is not a save document"), Number.isInteger(e.version) && e.version >= 1 || c("version", "must be your schema version, a whole number of 1 or more"), "meta" in e) {
43
+ if (!r(e.meta)) c("meta", "must be an object");
44
+ else {
45
+ let t = a(e.meta);
46
+ t && c("meta", t);
47
+ }
48
+ }
49
+ let l = r(e.prefabs) ? e.prefabs : {};
50
+ "prefabs" in e && !r(e.prefabs) && c("prefabs", "must be an object of key: prefab");
51
+ let u = n.components ?? {}, d = (e, s, d) => {
52
+ let f = /* @__PURE__ */ new Map();
53
+ if (!Array.isArray(e)) return c(s, "must be an array of entities"), f;
54
+ if (e.length > 1e6) return c(s, `holds more than ${t} entities; split the save`), f;
55
+ e.forEach((e, t) => {
56
+ let o = `${s}[${t}]`;
57
+ if (!r(e)) c(o, "must be an entity object {id, components}");
58
+ else {
59
+ typeof e.id != "string" || !e.id ? c(`${o}.id`, "must be a non-empty string") : f.has(e.id) ? c(`${o}.id`, `'${e.id}' is used by another entity; give each entity its own id`) : f.set(e.id, e);
60
+ for (let t of Object.keys(e)) [
61
+ "id",
62
+ "name",
63
+ "parent",
64
+ "transform",
65
+ "components",
66
+ "prefab",
67
+ "overrides"
68
+ ].includes(t) || c(`${o}.${t}`, "is not an entity field; move it into components");
69
+ if ("name" in e && typeof e.name != "string" && c(`${o}.name`, "must be a string"), "parent" in e && (typeof e.parent != "string" || !e.parent) && c(`${o}.parent`, "must be the id of another entity"), "transform" in e) {
70
+ let t = e.transform;
71
+ if (!r(t)) c(`${o}.transform`, "must be {position?, rotation?, scale?}");
72
+ else {
73
+ for (let e of Object.keys(t)) [
74
+ "position",
75
+ "rotation",
76
+ "scale"
77
+ ].includes(e) || c(`${o}.transform.${e}`, "is not a transform field; use position, rotation or scale");
78
+ "position" in t && !i(t.position, 3) && c(`${o}.transform.position`, "must be [x, y, z] with finite numbers"), "scale" in t && !i(t.scale, 3) && c(`${o}.transform.scale`, "must be [x, y, z] with finite numbers"), "rotation" in t && (!i(t.rotation, 4) || Math.abs(Math.hypot(...t.rotation) - 1) > .001) && c(`${o}.transform.rotation`, "must be a unit quaternion [x, y, z, w]");
79
+ }
80
+ }
81
+ if ("components" in e) {
82
+ if (!r(e.components)) c(`${o}.components`, "must be an object of name: value");
83
+ else for (let [t, r] of Object.entries(e.components)) {
84
+ let e = a(r);
85
+ if (e) {
86
+ c(`${o}.components.${t}`, e);
87
+ continue;
88
+ }
89
+ let i = Object.hasOwn(u, t) ? u[t] : void 0;
90
+ if (i) {
91
+ let e;
92
+ try {
93
+ e = i(r);
94
+ } catch (t) {
95
+ e = `its check threw (${t?.message ?? String(t)}); make the check return a message instead`;
96
+ }
97
+ e && c(`${o}.components.${t}`, e);
98
+ } else n.strictComponents && c(`${o}.components.${t}`, `unknown component '${t}'; add a check for it or remove it`);
99
+ }
100
+ }
101
+ if ("prefab" in e && !(typeof e.prefab == "string" && Object.hasOwn(l, e.prefab)) && c(`${o}.prefab`, `must name a prefab in the document's prefabs (${Object.keys(l).join(", ") || "none defined"})`), "overrides" in e) {
102
+ if ("prefab" in e || c(`${o}.overrides`, "needs prefab; only prefab instances take overrides"), !r(e.overrides)) c(`${o}.overrides`, "must be an object of prefab entity id: patch");
103
+ else {
104
+ let t = a(e.overrides);
105
+ t && c(`${o}.overrides`, t);
106
+ let n = typeof e.prefab == "string" && Object.hasOwn(l, e.prefab) ? l[e.prefab] : null, i = r(n) && Array.isArray(n.entities) ? new Map(n.entities.map((e) => r(e) ? [e.id, e] : [null, e])) : null, s = (e) => i.has(e) || e.includes("/") && r(i.get(e.split("/")[0])) && typeof i.get(e.split("/")[0]).prefab == "string";
107
+ for (let [t, n] of Object.entries(e.overrides)) i && !s(t) && c(`${o}.overrides.${t}`, `names no entity of prefab '${e.prefab}'; use one of its entity ids`), n !== null && !r(n) && c(`${o}.overrides.${t}`, "must be a patch object, or null to remove that entity");
108
+ }
109
+ }
110
+ }
111
+ });
112
+ for (let [t, n] of f) {
113
+ let i = e.indexOf(n);
114
+ if (typeof n.parent == "string") {
115
+ if (!f.has(n.parent)) c(`${s}[${i}].parent`, `'${n.parent}' is not an entity ${d ? "of this prefab" : "of this document"}`);
116
+ else {
117
+ let e = /* @__PURE__ */ new Set([t]), r = n.parent;
118
+ for (; typeof r == "string" && f.has(r);) {
119
+ if (e.has(r)) {
120
+ c(`${s}[${i}].parent`, `makes a parent cycle through '${r}'; give the hierarchy a root`);
121
+ break;
122
+ }
123
+ e.add(r), r = f.get(r).parent;
124
+ }
125
+ }
126
+ }
127
+ if (r(n.components) && !a(n.components)) for (let e of o(n.components)) !f.has(e.id) && (d || !e.id.includes("/") || typeof f.get(e.id.split("/")[0])?.prefab != "string") && c(`${s}[${i}].components${e.path}`, `references '${e.id}', which is not an entity ${d ? "of this prefab" : "of this document"}`);
128
+ }
129
+ return f;
130
+ };
131
+ d(e.entities, "entities", !1);
132
+ for (let [e, t] of Object.entries(l)) {
133
+ let n = `prefabs.${e}`;
134
+ if (!r(t)) {
135
+ c(n, "must be a prefab {entities, root?}");
136
+ continue;
137
+ }
138
+ let i = d(t.entities, `${n}.entities`, !0);
139
+ "root" in t && !(typeof t.root == "string" && i.has(t.root)) && c(`${n}.root`, "must be the id of one of its entities"), Array.isArray(t.entities) && !t.entities.length && c(`${n}.entities`, "must hold at least one entity");
140
+ let a = typeof t.root == "string" ? t.root : r(t.entities?.[0]) ? t.entities[0].id : void 0, o = typeof a == "string" ? i.get(a) : void 0;
141
+ o && "parent" in o && c(`${n}.root`, "the root entity must have no parent inside the prefab");
142
+ }
143
+ let f = (e) => {
144
+ let t = l[e];
145
+ return !r(t) || !Array.isArray(t.entities) ? [] : t.entities.flatMap((e) => r(e) && typeof e.prefab == "string" && Object.hasOwn(l, e.prefab) ? [e.prefab] : []);
146
+ }, p = /* @__PURE__ */ new Map(), m = /* @__PURE__ */ new Map(), h = (e, t) => {
147
+ if (p.get(e) === 2) return m.get(e);
148
+ if (p.get(e) === 1) return c(`prefabs.${e}`, `contains itself (${[...t, e].join(" > ")}); remove the cycle`), 0;
149
+ p.set(e, 1);
150
+ let n = 0;
151
+ for (let r of f(e)) n = Math.max(n, 1 + h(r, [...t, e]));
152
+ return p.set(e, 2), m.set(e, n), n;
153
+ };
154
+ for (let e of Object.keys(l)) h(e, []) + 1 > 32 && c(`prefabs.${e}`, "nests deeper than 32 prefabs; flatten it");
155
+ return s;
156
+ }
157
+ function c(e, t = {}) {
158
+ let n;
159
+ if (typeof e == "string") try {
160
+ n = JSON.parse(e);
161
+ } catch (e) {
162
+ throw TypeError(`Save is not valid JSON (${e.message}); the file is damaged or not a save`);
163
+ }
164
+ else {
165
+ let t = a(e);
166
+ if (t) throw TypeError(`Invalid save; fix the document: it ${t}`);
167
+ n = JSON.parse(JSON.stringify(e));
168
+ }
169
+ let r = s(n, t);
170
+ if (r.length) throw TypeError(`Invalid save; fix ${r[0].path || "the document"}: ${r[0].message}${r.length > 1 ? ` (and ${r.length - 1} more; see validateSave)` : ""}`);
171
+ return n;
172
+ }
173
+ //#endregion
174
+ //#region src/prefab.ts
175
+ var l = (e) => typeof e == "object" && !!e && !Array.isArray(e);
176
+ function u(e, t) {
177
+ if (!l(t)) return t === null ? void 0 : structuredClone(t);
178
+ let n = l(e) ? { ...e } : {};
179
+ for (let [e, r] of Object.entries(t)) if (r === null) delete n[e];
180
+ else {
181
+ let t = u(n[e], r);
182
+ t === void 0 ? delete n[e] : n[e] = t;
183
+ }
184
+ return n;
185
+ }
186
+ function d(e, t) {
187
+ return Array.isArray(e) ? e.map((e) => d(e, t)) : l(e) ? typeof e.$ref == "string" && Object.keys(e).length === 1 ? { $ref: t(e.$ref) } : Object.fromEntries(Object.entries(e).map(([e, n]) => [e, d(n, t)])) : e;
188
+ }
189
+ var f = (e) => {
190
+ let t = { components: e.components };
191
+ return e.name !== void 0 && (t.name = e.name), e.parent !== void 0 && (t.parent = e.parent), e.transform !== void 0 && (t.transform = e.transform), t;
192
+ };
193
+ function p(e) {
194
+ let t = e.prefabs ?? {}, n = /* @__PURE__ */ new Map(), r = (e) => {
195
+ let r = n.get(e);
196
+ return r || (r = i(t[e].entities, e), n.set(e, r)), r;
197
+ }, i = (e, n) => {
198
+ let i = [];
199
+ for (let a of e) {
200
+ let e = {
201
+ id: a.id,
202
+ components: structuredClone(a.components ?? {})
203
+ };
204
+ if (a.name !== void 0 && (e.name = a.name), a.parent !== void 0 && (e.parent = a.parent), a.transform !== void 0 && (e.transform = structuredClone(a.transform)), n && (e.source = {
205
+ prefab: n,
206
+ local: a.id
207
+ }), !a.prefab) {
208
+ i.push(e);
209
+ continue;
210
+ }
211
+ let o = t[a.prefab], s = o.root ?? o.entities[0].id, c = r(a.prefab), p = new Set(c.map((e) => e.id)), m = (e) => e === s ? a.id : p.has(e) ? `${a.id}/${e}` : e, h = c.map((t) => {
212
+ let n = {
213
+ ...structuredClone(t),
214
+ id: m(t.id),
215
+ components: d(t.components, m)
216
+ };
217
+ return t.parent !== void 0 && (n.parent = m(t.parent)), t.id === s && (n.components = {
218
+ ...n.components,
219
+ ...e.components
220
+ }, e.name !== void 0 && (n.name = e.name), e.transform !== void 0 && (n.transform = e.transform), e.parent === void 0 ? delete n.parent : n.parent = e.parent, n.source = e.source ? e.source : {
221
+ prefab: a.prefab,
222
+ local: s
223
+ }), n;
224
+ }), g = /* @__PURE__ */ new Set();
225
+ for (let [e, t] of Object.entries(a.overrides ?? {})) {
226
+ let n = m(e);
227
+ if (!h.some((e) => e.id === n)) throw TypeError(`Entity '${a.id}' overrides '${e}', which prefab '${a.prefab}' does not have; use one of its entity ids`);
228
+ t === null ? g.add(n) : h = h.map((e) => {
229
+ if (e.id !== n) return e;
230
+ let r = d(t, m);
231
+ l(r) && typeof r.parent == "string" && (r.parent = m(r.parent));
232
+ let i = u(f(e), r), a = {
233
+ id: e.id,
234
+ components: i.components ?? {}
235
+ };
236
+ return typeof i.name == "string" && (a.name = i.name), typeof i.parent == "string" && (a.parent = i.parent), l(i.transform) && (a.transform = i.transform), e.source && (a.source = e.source), a;
237
+ });
238
+ }
239
+ if (g.size) {
240
+ let e = !0;
241
+ for (; e;) {
242
+ e = !1;
243
+ for (let t of h) !g.has(t.id) && t.parent !== void 0 && g.has(t.parent) && (g.add(t.id), e = !0);
244
+ }
245
+ h = h.filter((e) => !g.has(e.id));
246
+ }
247
+ i.push(...h);
248
+ }
249
+ return i;
250
+ }, a = i(e.entities, null), o = /* @__PURE__ */ new Map();
251
+ for (let e of a) {
252
+ if (o.has(e.id)) throw TypeError(`Prefab expansion made two entities '${e.id}'; rename the entity or the instance that collides`);
253
+ o.set(e.id, e);
254
+ }
255
+ for (let e of a) {
256
+ if (e.parent !== void 0 && !o.has(e.parent)) throw TypeError(`Entity '${e.id}' has parent '${e.parent}', which does not exist after prefab expansion; fix the parent or the override that removed it`);
257
+ for (let t of m(e.components)) if (!o.has(t)) throw TypeError(`Entity '${e.id}' references '${t}', which does not exist after prefab expansion; fix the reference or the override that removed it`);
258
+ }
259
+ let s = [], c = /* @__PURE__ */ new Set(), p = (e, t) => {
260
+ if (!c.has(e.id)) {
261
+ if (t.has(e.id)) throw TypeError(`Entity '${e.id}' is its own ancestor after prefab overrides; give the hierarchy a root`);
262
+ t.add(e.id), e.parent !== void 0 && p(o.get(e.parent), t), c.add(e.id), s.push(e);
263
+ }
264
+ };
265
+ for (let e of a) p(e, /* @__PURE__ */ new Set());
266
+ return s;
267
+ }
268
+ function m(e, t = []) {
269
+ if (Array.isArray(e)) for (let n of e) m(n, t);
270
+ else if (l(e)) {
271
+ if (typeof e.$ref == "string" && Object.keys(e).length === 1) t.push(e.$ref);
272
+ else for (let n of Object.values(e)) m(n, t);
273
+ }
274
+ return t;
275
+ }
276
+ //#endregion
277
+ export { e as a, s as c, n as i, u as n, o, t as r, c as s, p as t };