@needle-tools/addressing 0.3.4 → 0.4.0-1791982227.dramatic-tempura.8b3a85e

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.
Files changed (58) hide show
  1. package/Readme.md +151 -70
  2. package/dist/address.d.ts +5 -0
  3. package/dist/address.js +25 -3
  4. package/dist/document/assets.d.ts +27 -0
  5. package/dist/document/assets.js +75 -0
  6. package/dist/document/collectionSelector.d.ts +9 -0
  7. package/dist/document/collectionSelector.js +29 -0
  8. package/dist/document/evaluate.d.ts +86 -0
  9. package/dist/document/evaluate.js +1082 -0
  10. package/dist/document/index.d.ts +11 -0
  11. package/dist/document/index.js +11 -0
  12. package/dist/document/inspection.d.ts +30 -0
  13. package/dist/document/inspection.js +130 -0
  14. package/dist/document/loadedDocument.d.ts +18 -0
  15. package/dist/document/loadedDocument.js +35 -0
  16. package/dist/document/references.d.ts +7 -0
  17. package/dist/document/references.js +36 -0
  18. package/dist/document/runtime.d.ts +119 -0
  19. package/dist/document/runtime.js +1 -0
  20. package/dist/document/types.d.ts +240 -0
  21. package/dist/document/types.js +43 -0
  22. package/dist/document/validation.d.ts +36 -0
  23. package/dist/document/validation.js +222 -0
  24. package/dist/document/valueCodecs.d.ts +20 -0
  25. package/dist/document/valueCodecs.js +3 -0
  26. package/dist/document/write.d.ts +31 -0
  27. package/dist/document/write.js +131 -0
  28. package/dist/id.d.ts +2 -0
  29. package/dist/id.js +4 -0
  30. package/dist/index.d.ts +2 -1
  31. package/dist/index.js +2 -1
  32. package/dist/loadedGltf.d.ts +32 -0
  33. package/dist/loadedGltf.js +62 -0
  34. package/dist/resolve.js +8 -6
  35. package/package.json +10 -2
  36. package/src/address.ts +169 -144
  37. package/src/anchor.ts +71 -71
  38. package/src/document/assets.ts +77 -0
  39. package/src/document/collectionSelector.ts +37 -0
  40. package/src/document/evaluate.ts +1111 -0
  41. package/src/document/index.ts +11 -0
  42. package/src/document/inspection.ts +123 -0
  43. package/src/document/loadedDocument.ts +48 -0
  44. package/src/document/references.ts +41 -0
  45. package/src/document/runtime.ts +113 -0
  46. package/src/document/schema.json +293 -0
  47. package/src/document/types.ts +265 -0
  48. package/src/document/validation.ts +226 -0
  49. package/src/document/valueCodecs.ts +23 -0
  50. package/src/document/write.ts +132 -0
  51. package/src/gltf.ts +33 -33
  52. package/src/hash.ts +58 -58
  53. package/src/id.ts +206 -201
  54. package/src/index.ts +49 -46
  55. package/src/loadedGltf.ts +93 -0
  56. package/src/resolve.ts +319 -317
  57. package/src/target.ts +126 -126
  58. package/src/uuid.ts +48 -48
@@ -0,0 +1,265 @@
1
+ import type { NeedleAddress } from "../address.js";
2
+ import type { DocumentNode, DocumentModel } from "./runtime.js";
3
+
4
+ /** the version discriminator key every project document must carry */
5
+ export const PROJECT_DOCUMENT_KEY = "needle:project";
6
+
7
+ export type ProjectDocumentAsset = {
8
+ /** where the asset lives — resolved against `EvaluateProjectDocumentOptions.baseUrl` */
9
+ src: string;
10
+ /**
11
+ * Optional PROVIDER IDENTITY for assets whose resources (textures, buffers) live at
12
+ * provider-specific urls that `src` alone can't reach (e.g. PolyHaven). The host recovers
13
+ * the provider's resolver from this identity at load time (see
14
+ * `EvaluateProjectDocumentOptions.resolveAssetUrl`). Self-contained assets omit it and
15
+ * load by `src`. The engine ignores it; only the host (editor) reads it.
16
+ */
17
+ asset?: { id: string; provider?: string };
18
+ /**
19
+ * Optional SEMANTIC KIND, decided at USE time by the writer ("model", "material",
20
+ * "hdr", "texture", "image", "video", "audio", "code", "text") — the same file can
21
+ * be a texture on a material slot or a plain image in UI, and downstream
22
+ * processing (compression at publish) follows the use, not the extension. The
23
+ * engine ignores it; only hosts/tooling read it.
24
+ */
25
+ kind?: string;
26
+ /**
27
+ * INFORMATIONAL: the server `ETag` observed when this document captured the
28
+ * asset — lets a future reader detect "the upstream file changed since".
29
+ * Never used for loading decisions; the engine ignores it.
30
+ */
31
+ etag?: string;
32
+ };
33
+
34
+ export type ProjectDocumentReference = {
35
+ /** project-local id of this reference — the resolution scope (or entity handle) for targets */
36
+ id: string;
37
+ /** key into the document's `assets` map */
38
+ asset: string;
39
+ /**
40
+ * ELEMENT REFERENCE discriminator: when present, this reference instantiates the
41
+ * addressed element INSIDE the asset (e.g. a material) into the composition's ENTITY
42
+ * POOL instead of placing a scene subtree. Entity references are first-class composed
43
+ * entities: overs can target them (`{ ref: <id>, path: "map/repeat" }`) and values can
44
+ * point at them (`{ ref: <id> }` — e.g. a mesh's material assignment). N consumers of
45
+ * the same entity share ONE runtime instance by construction (USD: a Material-prim
46
+ * reference; assignment ≈ material:binding).
47
+ */
48
+ address?: NeedleAddress;
49
+ /** @deprecated (2026-08-03, read-only shim — remove soon) replaced by parent OVERS
50
+ * (`{ target: { ref, path: "parent" }, value: { ref | "$scene", address?, index? } }`)
51
+ * days after shipping; only unreleased documents from that week carry this field.
52
+ * The writer no longer emits it; the evaluator still honors it at placement. */
53
+ parent?: { ref: string; address?: NeedleAddress };
54
+ };
55
+
56
+ /** A host-owned root that document opinions compose onto instead of instantiating. */
57
+ export type ProjectDocumentBinding = {
58
+ /** Document-local reference used by targets. `$`-prefixed ids are reserved. */
59
+ id: string;
60
+ /** The kind of host root required by this document. */
61
+ kind: "scene";
62
+ /** Stable structural identity used by the host to match this root before applying edits. */
63
+ signature: string;
64
+ /** Informational label for diagnostics only; never used as identity. */
65
+ name?: string;
66
+ /** Existing asset-reference ids whose instances belong to this host root. */
67
+ references?: string[];
68
+ };
69
+
70
+ export type ProjectDocumentTarget = {
71
+ /** which placed reference the address resolves WITHIN; omitted → the composition root */
72
+ ref?: string;
73
+ /** fat address of the element inside the reference (needle-id / anchor / path) */
74
+ address?: NeedleAddress;
75
+ /**
76
+ * Property path within the resolved element, "/"-separated.
77
+ *
78
+ * A segment landing on a COLLECTION may be a `<field>:<value>` qualifier instead of an
79
+ * index — `components/type:DragControls/enabled`, `components/guid:6f1f…/enabled` —
80
+ * so a document never depends on array order (`userData.components` reorders whenever
81
+ * a component is added or removed). A bare numeric segment on an array is still an
82
+ * index, but it is now an explicit opt-in rather than the only option.
83
+ * `components` is a synthesized segment on a node: the live layout
84
+ * (`userData.components`) stays an implementation detail.
85
+ *
86
+ * Reserved LAST segment: `active` — with `value: false` it removes whatever the rest
87
+ * of the path resolved to (the node itself, or a component) from the composed result.
88
+ */
89
+ path?: string;
90
+ };
91
+
92
+ export type ProjectDocumentDef = {
93
+ target: ProjectDocumentTarget;
94
+ /** Owner of all component entries in this def; omitted for legacy data. */
95
+ extension?: string;
96
+ /**
97
+ * When present, the def CREATES a new node (USD-proper: def defines prims) under the
98
+ * resolved target (composition root when the target is empty) and the components
99
+ * apply to IT — e.g. the runtime start camera. Without `create`, components apply to
100
+ * the resolved existing node.
101
+ */
102
+ create?: {
103
+ id?: string;
104
+ name?: string;
105
+ position?: number[];
106
+ quaternion?: number[];
107
+ scale?: number[];
108
+ /** Recreate a hierarchy duplicate from its stable source and seed. */
109
+ copy?: {
110
+ source: ProjectDocumentTarget;
111
+ seed: string;
112
+ reference?: boolean;
113
+ } & ({ batch: string; index: number } | { batch?: never; index?: never });
114
+ };
115
+ /** VERBATIM NEEDLE_components wire entries ({ name, guid, ...fields }) */
116
+ components?: Array<{ name: string } & Record<string, unknown>>;
117
+ };
118
+
119
+ export type ProjectDocumentOver = {
120
+ target: ProjectDocumentTarget;
121
+ value: unknown;
122
+ };
123
+
124
+ /** Saved-data version required from an extension, independent of its package version. */
125
+ export type ProjectDocumentExtension = {
126
+ version: number;
127
+ };
128
+
129
+ export type ProjectDocument = {
130
+ [PROJECT_DOCUMENT_KEY]: string;
131
+ /** layer metadata (USD's "layer metadata" concept — e.g. `name`); free-form */
132
+ metadata?: Record<string, unknown>;
133
+ /** Required document extensions, not installed packages or runtime dependencies. */
134
+ extensions?: Record<string, ProjectDocumentExtension>;
135
+ /** named remote origins for `remote://<name>/<path>` srcs — the scheme
136
+ * routes, the AUTHORITY names the remote, this table supplies the base.
137
+ * Resolved per DOCUMENT (a nested document resolves with ITS table), so
138
+ * the document works wherever it travels. Semantics mirror the editor's
139
+ * remoteSrc.ts — keep the two in sync. */
140
+ remotes?: Record<string, string>;
141
+ assets?: Record<string, ProjectDocumentAsset>;
142
+ /** Required host-owned roots. The host resolves these before evaluation. */
143
+ bindings?: ProjectDocumentBinding[];
144
+ references?: ProjectDocumentReference[];
145
+ defs?: ProjectDocumentDef[];
146
+ overs?: ProjectDocumentOver[];
147
+ /** unknown arcs are ignored by evaluation and must be preserved by writers */
148
+ [arc: string]: unknown;
149
+ };
150
+
151
+ const REMOTE_SRC_SCHEME = "remote://";
152
+
153
+ /**
154
+ * Resolve a `remote://name/path` src via the document's remotes table
155
+ * (`overrides` win for known names — the host's per-environment repoint, e.g.
156
+ * the editor's dev proxy). Non-remote srcs pass through. An UNKNOWN remote
157
+ * name resolves to null — the caller reports it; guessing a base would load
158
+ * the wrong bytes silently. MIRRORS the editor's remoteSrc.ts resolveRemoteSrc.
159
+ */
160
+ export function resolveDocumentRemoteSrc(src: string, remotes: Record<string, string> | undefined, overrides?: Record<string, string>): string | null {
161
+ if (!src.startsWith(REMOTE_SRC_SCHEME)) return src;
162
+ const rest = src.substring(REMOTE_SRC_SCHEME.length);
163
+ const slash = rest.indexOf("/");
164
+ if (slash <= 0) return null;
165
+ const name = rest.substring(0, slash);
166
+ const path = rest.substring(slash); // keeps the leading "/"
167
+ const base = overrides?.[name] ?? remotes?.[name];
168
+ if (base === undefined) return null;
169
+ // "" base = host-relative; trim a trailing slash otherwise
170
+ return (base.endsWith("/") ? base.substring(0, base.length - 1) : base) + path;
171
+ }
172
+
173
+ /** structural check for the version discriminator — the opener/sniffing entry point */
174
+ export function isProjectDocument(value: unknown): value is ProjectDocument {
175
+ return !!value && typeof value === "object" && typeof (value as Record<string, unknown>)[PROJECT_DOCUMENT_KEY] === "string";
176
+ }
177
+
178
+ // ---------------------------------------------------------------------------
179
+ // evaluation
180
+ // ---------------------------------------------------------------------------
181
+
182
+ export type ProjectEvaluationIssue = {
183
+ arc: "reference" | "def" | "over";
184
+ message: string;
185
+ };
186
+
187
+ /**
188
+ * Report evaluation issues to the console — in PRODUCTION too. Every issue
189
+ * means the document asked for something the runtime could not provide (a
190
+ * dropped def, an unresolved over, a failed asset), i.e. the loaded scene
191
+ * silently differs from what the author saved. The author debugs on the
192
+ * deployed page: gating this behind dev/?debugproject cost a full day of
193
+ * blind hunting when a deployed scene lost a component with a clean console
194
+ * (2026-09-01). A healthy document reports nothing.
195
+ */
196
+ export function reportProjectIssues(issues: readonly ProjectEvaluationIssue[], warn: (message: string) => void = console.warn): void {
197
+ for (const issue of issues) {
198
+ warn(`[needle:project] ${issue.arc}: ${issue.message}`);
199
+ }
200
+ }
201
+
202
+ export type ProjectEvaluationResult = {
203
+ /** the object all non-mounted references were added to */
204
+ root: DocumentNode;
205
+ /** Placed reference roots by reference id. Populated during the host's scheduled
206
+ * composition phase, after template deserialization; await `completed` first. */
207
+ references: Map<string, DocumentNode>;
208
+ /** per-reference Model views by reference id (`scene` is that reference's placed
209
+ * INSTANCE; parser etc. come from the shared template). Populated at `completed`,
210
+ * like `references`. */
211
+ models: Map<string, DocumentModel>;
212
+ /**
213
+ * misses and errors — an issue never aborts evaluation, the arc is skipped.
214
+ * Populated up to `completed` (defs/overs apply in the host's composition phase).
215
+ */
216
+ issues: ProjectEvaluationIssue[];
217
+ /**
218
+ * Resolves once defs/overs have been applied. Hosts schedule composition after
219
+ * asset deserialization and before component activation. Needle's adapter uses
220
+ * its pre-setup phase, requiring a context tick; a vanilla host can run immediately.
221
+ */
222
+ completed: Promise<void>;
223
+ };
224
+
225
+ export type EvaluateProjectDocumentOptions = {
226
+ /** Restore components on existing nodes without loading assets or replaying structural edits. */
227
+ componentRecovery?: {
228
+ readonly signal: AbortSignal;
229
+ readonly resolveTarget: (target: ProjectDocumentTarget) => DocumentNode | null;
230
+ };
231
+ /** Resolve extension readers after loading, in the runtime's pre-activation context. */
232
+ extensions?: (context: import('./runtime.js').DocumentDefContext) => ReadonlyMap<string, import('./runtime.js').DocumentExtensionProvider>;
233
+ /** Reuse existing roots as named resolution scopes. Bindings may supply external
234
+ * host roots that have no asset reference in the document. When supplied, every
235
+ * declared scene reference must also be bound; a missing binding is reported
236
+ * instead of loading another instance. */
237
+ referenceBindings?: ReadonlyMap<string, DocumentNode>;
238
+ /** where references are placed; defaults to `context.scene` */
239
+ parent?: DocumentNode;
240
+ /** resolves `assets.src` for the document — tests/tools provide in-memory data here */
241
+ resolveAsset?: (assetId: string, src: string) => Promise<ArrayBuffer | string>;
242
+ /** base for resolving relative `assets.src` urls with the default (fetch) resolver */
243
+ baseUrl?: string;
244
+ /** per-environment overrides for the document's `remotes` table (known
245
+ * names only — the editor maps needle-cloud to its dev proxy); the
246
+ * document's own table is the default */
247
+ remotes?: Record<string, string>;
248
+ /**
249
+ * Rewrites a resource url (texture / external buffer) encountered while parsing an
250
+ * asset — the asset service's `resolveUrl` re-entering at load time. Needed for provider
251
+ * assets (e.g. PolyHaven) whose textures live at urls that plain relative resolution
252
+ * against `assets.src` cannot reach. Passed to the host's parse operation;
253
+ * the editor opener supplies it from `IAssetsService` so this
254
+ * evaluator carries NO provider knowledge.
255
+ */
256
+ resolveAssetUrl?: (assetId: string, url: string) => string;
257
+ /**
258
+ * AGGREGATE download progress across the document's assets: `loaded` bytes summed
259
+ * over all asset downloads, `total` summed over the known Content-Lengths (0 while
260
+ * nothing reported a length). Fired per received chunk — the loader chain adapts it
261
+ * to the ProgressEvent shape the loading UI expects.
262
+ */
263
+ onProgress?: (loaded: number, total: number) => void;
264
+ };
265
+
@@ -0,0 +1,226 @@
1
+ /**
2
+ * Structural validation of Needle project documents against the JSON Schema in
3
+ * `schema.json` — the format's machine-readable spec.
4
+ *
5
+ * The schema is the SINGLE source of truth: this file interprets it, it does not
6
+ * restate it. That is the whole point — a hand-written second validator would drift
7
+ * from the schema exactly like the plan's example drifted from the types.
8
+ *
9
+ * Deliberately dependency-free (a JSON Schema library is a lot of surface for the
10
+ * handful of keywords this schema uses), and STRICT about that: any keyword the
11
+ * schema uses and this interpreter does not implement THROWS. A validator that
12
+ * silently ignores keywords it doesn't know is worse than no validator — it reports
13
+ * "valid" for documents it never actually checked. If you extend the schema with a
14
+ * new keyword, this file fails loudly until you implement it.
15
+ *
16
+ * This validates SHAPE, not resolvability: whether an address actually hits a node in
17
+ * the loaded content is the evaluator's job (it reports issues and skips the arc).
18
+ */
19
+
20
+ /** a JSON Schema node — `true`/`false` schema forms are not used by our schema */
21
+ type SchemaNode = Record<string, unknown>;
22
+
23
+ export type SchemaValidationError = {
24
+ /** "/"-separated path to the offending value, relative to the document root */
25
+ readonly path: string;
26
+ readonly message: string;
27
+ };
28
+
29
+ /** keywords that carry no constraint — annotations, identity, and the definition bag */
30
+ const IGNORED_KEYWORDS = new Set(["$schema", "$id", "$comment", "title", "description", "default", "examples", "definitions"]);
31
+
32
+ /** keywords this interpreter implements; anything else in the schema is a hard error */
33
+ const SUPPORTED_KEYWORDS = new Set([
34
+ "$ref", "type", "enum", "const", "required", "properties", "additionalProperties",
35
+ "items", "minItems", "maxItems", "minLength", "minimum", "allOf", "anyOf", "not",
36
+ ]);
37
+
38
+ /**
39
+ * Validate `value` against `schema`. Returns every error found (not just the first) —
40
+ * a writer regression usually shows up as several related failures and seeing them
41
+ * together is what makes the cause obvious.
42
+ *
43
+ * @throws if the schema uses a keyword this interpreter does not implement.
44
+ */
45
+ export function validateAgainstSchema(schema: SchemaNode, value: unknown): SchemaValidationError[] {
46
+ const errors: SchemaValidationError[] = [];
47
+ validateNode(schema, value, "", schema, errors);
48
+ return errors;
49
+ }
50
+
51
+ /** one-line-per-error rendering for assertion messages */
52
+ export function formatSchemaErrors(errors: readonly SchemaValidationError[]): string {
53
+ return errors.map(e => ` ${e.path || "<root>"}: ${e.message}`).join("\n");
54
+ }
55
+
56
+ function validateNode(schema: SchemaNode, value: unknown, path: string, root: SchemaNode, errors: SchemaValidationError[]): void {
57
+ for (const keyword of Object.keys(schema)) {
58
+ if (IGNORED_KEYWORDS.has(keyword) || SUPPORTED_KEYWORDS.has(keyword)) continue;
59
+ throw new Error(`projectDocumentValidation: unsupported JSON Schema keyword "${keyword}" at "${path || "<root>"}" — implement it before using it in the schema`);
60
+ }
61
+ assertWellFormed(schema, path);
62
+
63
+ if (typeof schema.$ref === "string") {
64
+ validateNode(resolveRef(schema.$ref, root), value, path, root, errors);
65
+ // sibling keywords next to $ref are ignored in draft-07 — our schema never mixes them
66
+ return;
67
+ }
68
+
69
+ if (schema.type !== undefined && !matchesType(schema.type, value)) {
70
+ errors.push({ path, message: `expected type ${JSON.stringify(schema.type)}, got ${describe(value)}` });
71
+ return; // every remaining keyword assumes the type held — reporting them too is noise
72
+ }
73
+
74
+ if (Array.isArray(schema.enum) && !schema.enum.some(candidate => deepEquals(candidate, value))) {
75
+ errors.push({ path, message: `expected one of ${JSON.stringify(schema.enum)}, got ${describe(value)}` });
76
+ }
77
+ if ("const" in schema && !deepEquals(schema.const, value)) {
78
+ errors.push({ path, message: `expected ${JSON.stringify(schema.const)}, got ${describe(value)}` });
79
+ }
80
+
81
+ if (typeof schema.minLength === "number" && typeof value === "string" && value.length < schema.minLength) {
82
+ errors.push({ path, message: `expected at least ${schema.minLength} character(s), got ${value.length}` });
83
+ }
84
+
85
+ if (typeof schema.minimum === "number" && typeof value === "number" && value < schema.minimum) {
86
+ errors.push({ path, message: `expected at least ${schema.minimum}, got ${value}` });
87
+ }
88
+
89
+ if (Array.isArray(value)) {
90
+ if (typeof schema.minItems === "number" && value.length < schema.minItems) {
91
+ errors.push({ path, message: `expected at least ${schema.minItems} item(s), got ${value.length}` });
92
+ }
93
+ if (typeof schema.maxItems === "number" && value.length > schema.maxItems) {
94
+ errors.push({ path, message: `expected at most ${schema.maxItems} item(s), got ${value.length}` });
95
+ }
96
+ if (isSchema(schema.items)) {
97
+ for (let i = 0; i < value.length; i++) validateNode(schema.items, value[i], join(path, String(i)), root, errors);
98
+ }
99
+ }
100
+
101
+ if (isPlainObject(value)) {
102
+ if (Array.isArray(schema.required)) {
103
+ for (const key of schema.required) {
104
+ if (typeof key === "string" && !(key in value)) {
105
+ errors.push({ path, message: `missing required property "${key}"` });
106
+ }
107
+ }
108
+ }
109
+ const properties = isPlainObject(schema.properties) ? schema.properties : undefined;
110
+ if (properties) {
111
+ for (const [key, sub] of Object.entries(properties)) {
112
+ if (key in value && isSchema(sub)) validateNode(sub, value[key], join(path, key), root, errors);
113
+ }
114
+ }
115
+ const additional = schema.additionalProperties;
116
+ if (additional === false || isSchema(additional)) {
117
+ for (const [key, entry] of Object.entries(value)) {
118
+ if (properties && key in properties) continue;
119
+ if (additional === false) {
120
+ errors.push({ path: join(path, key), message: "unexpected property" });
121
+ }
122
+ else {
123
+ validateNode(additional as SchemaNode, entry, join(path, key), root, errors);
124
+ }
125
+ }
126
+ }
127
+ }
128
+
129
+ if (Array.isArray(schema.allOf)) {
130
+ for (const sub of schema.allOf) if (isSchema(sub)) validateNode(sub, value, path, root, errors);
131
+ }
132
+ if (Array.isArray(schema.anyOf)) {
133
+ const matched = schema.anyOf.some(sub => isSchema(sub) && validateAgainstSchemaIn(sub, value, root).length === 0);
134
+ if (!matched) errors.push({ path, message: "matched none of the allowed forms (anyOf)" });
135
+ }
136
+ if (isSchema(schema.not) && validateAgainstSchemaIn(schema.not, value, root).length === 0) {
137
+ // our schema uses `not: {}` to mark RETIRED fields — say so rather than leaking
138
+ // "must not match the empty schema" at the reader
139
+ const why = typeof schema.description === "string" ? schema.description : "value is not allowed here";
140
+ errors.push({ path, message: why });
141
+ }
142
+ }
143
+
144
+ /**
145
+ * A keyword whose VALUE has an unexpected shape would be skipped by the checks below —
146
+ * the same silent-pass hazard as an unknown keyword, so it is the same hard error.
147
+ */
148
+ function assertWellFormed(schema: SchemaNode, path: string): void {
149
+ const bad = (keyword: string, expected: string): never => {
150
+ throw new Error(`projectDocumentValidation: "${keyword}" at "${path || "<root>"}" must be ${expected}`);
151
+ };
152
+ if ("$ref" in schema && typeof schema.$ref !== "string") bad("$ref", "a string");
153
+ if ("type" in schema && typeof schema.type !== "string" && !Array.isArray(schema.type)) bad("type", "a string or array of strings");
154
+ if ("enum" in schema && !Array.isArray(schema.enum)) bad("enum", "an array");
155
+ if ("required" in schema && !Array.isArray(schema.required)) bad("required", "an array");
156
+ if ("properties" in schema && !isPlainObject(schema.properties)) bad("properties", "an object");
157
+ if ("items" in schema && !isPlainObject(schema.items)) bad("items", "a schema object (tuple form is not supported)");
158
+ if ("not" in schema && !isPlainObject(schema.not)) bad("not", "a schema object");
159
+ if ("allOf" in schema && !Array.isArray(schema.allOf)) bad("allOf", "an array");
160
+ if ("anyOf" in schema && !Array.isArray(schema.anyOf)) bad("anyOf", "an array");
161
+ if ("additionalProperties" in schema && typeof schema.additionalProperties !== "boolean" && !isPlainObject(schema.additionalProperties)) bad("additionalProperties", "a boolean or schema object");
162
+ for (const keyword of ["minItems", "maxItems", "minLength", "minimum"]) {
163
+ if (keyword in schema && typeof schema[keyword] !== "number") bad(keyword, "a number");
164
+ }
165
+ }
166
+
167
+ /** sub-validation that keeps the same `$ref` root (used by anyOf/not) */
168
+ function validateAgainstSchemaIn(schema: SchemaNode, value: unknown, root: SchemaNode): SchemaValidationError[] {
169
+ const errors: SchemaValidationError[] = [];
170
+ validateNode(schema, value, "", root, errors);
171
+ return errors;
172
+ }
173
+
174
+ function resolveRef(ref: string, root: SchemaNode): SchemaNode {
175
+ if (!ref.startsWith("#/")) throw new Error(`projectDocumentValidation: only local "#/..." $refs are supported, got "${ref}"`);
176
+ let current: unknown = root;
177
+ for (const segment of ref.slice(2).split("/")) {
178
+ if (!isPlainObject(current)) throw new Error(`projectDocumentValidation: $ref "${ref}" does not resolve`);
179
+ current = current[decodeURIComponent(segment.replace(/~1/g, "/").replace(/~0/g, "~"))];
180
+ }
181
+ if (!isSchema(current)) throw new Error(`projectDocumentValidation: $ref "${ref}" does not resolve to a schema`);
182
+ return current;
183
+ }
184
+
185
+ function matchesType(type: unknown, value: unknown): boolean {
186
+ if (Array.isArray(type)) return type.some(t => matchesType(t, value));
187
+ switch (type) {
188
+ case "object": return isPlainObject(value);
189
+ case "array": return Array.isArray(value);
190
+ case "string": return typeof value === "string";
191
+ case "number": return typeof value === "number" && Number.isFinite(value);
192
+ case "integer": return typeof value === "number" && Number.isInteger(value);
193
+ case "boolean": return typeof value === "boolean";
194
+ case "null": return value === null;
195
+ default: throw new Error(`projectDocumentValidation: unsupported "type" value ${JSON.stringify(type)}`);
196
+ }
197
+ }
198
+
199
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
200
+ return typeof value === "object" && value !== null && !Array.isArray(value);
201
+ }
202
+
203
+ function isSchema(value: unknown): value is SchemaNode {
204
+ return isPlainObject(value);
205
+ }
206
+
207
+ function join(path: string, segment: string): string {
208
+ return path ? `${path}/${segment}` : segment;
209
+ }
210
+
211
+ function describe(value: unknown): string {
212
+ if (value === null) return "null";
213
+ if (Array.isArray(value)) return "array";
214
+ if (value === undefined) return "undefined";
215
+ return typeof value;
216
+ }
217
+
218
+ function deepEquals(a: unknown, b: unknown): boolean {
219
+ if (a === b) return true;
220
+ if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((v, i) => deepEquals(v, b[i]));
221
+ if (isPlainObject(a) && isPlainObject(b)) {
222
+ const keys = Object.keys(a);
223
+ return keys.length === Object.keys(b).length && keys.every(k => k in b && deepEquals(a[k], b[k]));
224
+ }
225
+ return false;
226
+ }
@@ -0,0 +1,23 @@
1
+ import type { ProjectDocumentTarget } from './types.js';
2
+
3
+ /** A typed extension value stored in an override or operation. */
4
+ export interface DocumentExtensionValue {
5
+ readonly $extension: string;
6
+ readonly type: string;
7
+ readonly version: number;
8
+ readonly data: unknown;
9
+ }
10
+
11
+ /** Resolves references against the receiving document, never the sending instances. */
12
+ export interface DocumentValueContext {
13
+ resolveReference(target: ProjectDocumentTarget & { ref: string; pathPrefix?: string }): object | null;
14
+ }
15
+
16
+ /** Reconstructs one value type using its extension's saved-data version. */
17
+ export interface DocumentValueCodec {
18
+ decode(data: unknown, context: DocumentValueContext): unknown;
19
+ }
20
+
21
+ export function isDocumentExtensionValue(value: unknown): value is DocumentExtensionValue {
22
+ return !!value && typeof value === 'object' && '$extension' in value;
23
+ }
@@ -0,0 +1,132 @@
1
+ import type { NeedleAddress } from "../address.js";
2
+ import type { ProjectDocumentOver, ProjectDocumentTarget } from "./types.js";
3
+ import { isDocumentExtensionValue } from './valueCodecs.js';
4
+
5
+ export interface PropertyOverInput {
6
+ readonly target: ProjectDocumentTarget;
7
+ readonly value: unknown;
8
+ readonly previousValue: unknown;
9
+ readonly sequence?: number;
10
+ readonly alwaysWrite?: boolean;
11
+ }
12
+
13
+ export type PropertyOverResult =
14
+ | { over: ProjectDocumentOver; sequence: number }
15
+ | { reverted: ProjectDocumentOver }
16
+ | { issue: string };
17
+
18
+ /** Serialize one captured edit; adapters supply ownership and live-target checks. */
19
+ export function writePropertyOver(input: PropertyOverInput, encodeNode?: (object: object) => unknown): PropertyOverResult {
20
+ const value = captureDocumentValue(input.value, encodeNode);
21
+ if (value === undefined) return { issue: "value type is not expressible in the document yet" };
22
+ const base = captureDocumentValue(input.previousValue, encodeNode);
23
+ if (!input.alwaysWrite && base !== undefined && JSON.stringify(base) === JSON.stringify(value)) {
24
+ return { reverted: { target: input.target, value: base } };
25
+ }
26
+ return { over: { target: input.target, value }, sequence: input.sequence ?? 0 };
27
+ }
28
+
29
+ export function isDocumentReferenceValue(value: unknown): value is { ref: string; address?: NeedleAddress } {
30
+ if (!value || typeof value !== "object") return false;
31
+ const candidate = value as Record<string, unknown>;
32
+ if (typeof candidate.ref !== "string" || Object.keys(candidate).some(key => key !== "ref" && key !== "address")) return false;
33
+ const address = candidate.address;
34
+ return address === undefined || (!!address && typeof address === "object" && !Array.isArray(address)
35
+ && Object.entries(address).every(([key, entry]) => ["id", "anchor", "type", "name", "path"].includes(key) && typeof entry === "string"));
36
+ }
37
+
38
+ export function captureDocumentValue(value: unknown, encodeNode?: (object: object) => unknown): unknown {
39
+ if (value === null) return null;
40
+ if (isDocumentExtensionValue(value)) {
41
+ if (typeof value.$extension !== 'string' || !value.$extension || typeof value.type !== 'string' || !value.type
42
+ || !Number.isSafeInteger(value.version) || value.version < 1) return undefined;
43
+ const data = captureExtensionData(value.data, new Set());
44
+ return data === undefined ? undefined : { $extension: value.$extension, type: value.type, version: value.version, data };
45
+ }
46
+ if (isDocumentReferenceValue(value)) return { ref: value.ref, ...(value.address ? { address: { ...value.address } } : {}) };
47
+ switch (typeof value) {
48
+ case "number": return Number.isFinite(value) ? value : undefined;
49
+ case "string":
50
+ case "boolean":
51
+ return value;
52
+ case "object": {
53
+ // scene-object values (object slots) → NODE REFERENCES ({ref, address?});
54
+ // unattributable objects fall through to undefined = "not expressible"
55
+ if ((value as { isObject3D?: boolean }).isObject3D === true) {
56
+ return encodeNode?.(value);
57
+ }
58
+ const toArray = (value as { toArray?: unknown }).toArray;
59
+ if (typeof toArray === "function") {
60
+ const array = (value as { toArray(): unknown[] }).toArray();
61
+ if (Array.isArray(array)) {
62
+ // three value types are numeric arrays: Vector[234]/Quaternion/Color
63
+ // ([x,y,z(,w)]). Euler trails a string `order` — take the leading
64
+ // numeric run; the evaluator's Euler.fromArray([x,y,z]) keeps the
65
+ // node's own order. Reject anything with more than one trailing
66
+ // non-number (not a known value type).
67
+ const nums: number[] = [];
68
+ for (const v of array) { if (typeof v === "number" && Number.isFinite(v)) nums.push(v); else break; }
69
+ if (nums.length > 0 && (nums.length === array.length || (nums.length === array.length - 1 && typeof array[array.length - 1] === "string"))) return nums;
70
+ }
71
+ }
72
+ if (Array.isArray(value) && value.every(v => (typeof v === "number" && Number.isFinite(v)) || typeof v === "string" || typeof v === "boolean")) {
73
+ return [...value];
74
+ }
75
+ return undefined;
76
+ }
77
+ default:
78
+ return undefined;
79
+ }
80
+ }
81
+
82
+ export function documentOverKey(over: ProjectDocumentOver): string {
83
+ const t = over.target;
84
+ const addressKey = t.address?.id ?? t.address?.path ?? t.address?.name ?? "";
85
+ return `${t.ref ?? ""}::${addressKey}::${t.path ?? ""}`;
86
+ }
87
+
88
+ /**
89
+ * Merge base-document overs with freshly captured ones: a new over SUPERSEDES a base
90
+ * over on the same target (the user re-edited it); base overs whose reference is gone
91
+ * are dropped; everything else is preserved.
92
+ */
93
+ export function mergeDocumentOvers(baseOvers: readonly ProjectDocumentOver[], newOvers: readonly ProjectDocumentOver[], liveRefs: ReadonlySet<string>, contentRefIds: ReadonlySet<string>, alwaysSuperseded?: ReadonlySet<string>, skipped?: string[]): ProjectDocumentOver[] {
94
+ const superseded = new Set(newOvers.map(documentOverKey));
95
+ const result: ProjectDocumentOver[] = [];
96
+ for (const over of baseOvers) {
97
+ // parent overs of the REGENERATED classes never merge back (re-derived
98
+ // live every save): address-less = reference roots; addressed on a CONTENT
99
+ // ref = content children. Addressed parent overs on OTHER refs are
100
+ // ops-recorded asset moves — they PERSIST across sessions and supersede
101
+ // by key on re-move.
102
+ if (over.target.path === "parent" && (!over.target.address || (over.target.ref !== undefined && contentRefIds.has(over.target.ref)))) continue;
103
+ if (over.target.ref && !liveRefs.has(over.target.ref)) {
104
+ // reference removed — the over dies with it. EXPECTED after a reference
105
+ // delete, but SURFACED regardless ("Save Project never drops an edit
106
+ // silently"): an unexpected entry here is the symptom of an attribution
107
+ // bug (wrong ref id), and silence cost a debugging session once
108
+ // (plans/project-format-v0.md item 7b).
109
+ skipped?.push(`over ${over.target.path ?? "?"} on reference "${over.target.ref}" — reference no longer exists, over dropped`);
110
+ continue;
111
+ }
112
+ const key = documentOverKey(over);
113
+ if (superseded.has(key)) continue; // re-edited below
114
+ if (alwaysSuperseded?.has(key)) continue; // rebuilt-from-live paths (placement)
115
+ result.push(over);
116
+ }
117
+ result.push(...newOvers);
118
+ return result;
119
+ }
120
+
121
+ /** Codec data is already encoded; validate and detach it without interpreting its fields. */
122
+ function captureExtensionData(value: unknown, seen: Set<object>): unknown {
123
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;
124
+ if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;
125
+ if (!value || typeof value !== 'object' || seen.has(value)) return undefined;
126
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return undefined;
127
+ seen.add(value);
128
+ const entries = Object.entries(value).map(([key, entry]) => [key, captureExtensionData(entry, seen)] as const);
129
+ seen.delete(value);
130
+ if (entries.some(([, entry]) => entry === undefined)) return undefined;
131
+ return Array.isArray(value) ? entries.map(([, entry]) => entry) : Object.fromEntries(entries);
132
+ }