@spacexr/3d-tiles-runtime 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +93 -2
  3. package/dist/chunk-AI6NWGCA.js +316 -0
  4. package/dist/chunk-AI6NWGCA.js.map +1 -0
  5. package/dist/chunk-G7YVZYMR.js +24 -0
  6. package/dist/chunk-G7YVZYMR.js.map +1 -0
  7. package/dist/chunk-PJIVVIOF.js +205 -0
  8. package/dist/chunk-PJIVVIOF.js.map +1 -0
  9. package/dist/chunk-Q2AL6LWU.js +3 -0
  10. package/dist/chunk-Q2AL6LWU.js.map +1 -0
  11. package/dist/chunk-Q35HKP5V.js +249 -0
  12. package/dist/chunk-Q35HKP5V.js.map +1 -0
  13. package/dist/chunk-URZDM4BH.js +488 -0
  14. package/dist/chunk-URZDM4BH.js.map +1 -0
  15. package/dist/implicit/index.d.ts +64 -0
  16. package/dist/implicit/index.js +4 -0
  17. package/dist/implicit/index.js.map +1 -0
  18. package/dist/index-CNnPRQZc.d.ts +350 -0
  19. package/dist/index.d.ts +713 -0
  20. package/dist/index.js +3074 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/metadata/index.d.ts +12 -0
  23. package/dist/metadata/index.js +3 -0
  24. package/dist/metadata/index.js.map +1 -0
  25. package/dist/pipeline/index.d.ts +5 -0
  26. package/dist/pipeline/index.js +3 -0
  27. package/dist/pipeline/index.js.map +1 -0
  28. package/dist/ports/index.d.ts +62 -0
  29. package/dist/ports/index.js +4 -0
  30. package/dist/ports/index.js.map +1 -0
  31. package/dist/resource-DH72MRMN.d.ts +34 -0
  32. package/dist/spatial/index.d.ts +402 -0
  33. package/dist/spatial/index.js +3 -0
  34. package/dist/spatial/index.js.map +1 -0
  35. package/dist/spatial-3IDPbyv4.d.ts +28 -0
  36. package/dist/types-Dn5i8Uqg.d.ts +78 -0
  37. package/dist/types-ri64XfSE.d.ts +237 -0
  38. package/package.json +102 -5
  39. package/src/implicit/availability.ts +55 -0
  40. package/src/implicit/coordinates.ts +193 -0
  41. package/src/implicit/dense-subtree-loader.ts +23 -0
  42. package/src/implicit/index.ts +6 -0
  43. package/src/implicit/standard-subtree-loader.ts +71 -0
  44. package/src/implicit/tile-data-source.ts +120 -0
  45. package/src/implicit/types.ts +156 -0
  46. package/src/index.ts +6 -0
  47. package/src/metadata/index.ts +2 -0
  48. package/src/metadata/metadata-resolver.ts +308 -0
  49. package/src/metadata/types.ts +91 -0
  50. package/src/pipeline/index.ts +4 -0
  51. package/src/pipeline/metadata-store.ts +44 -0
  52. package/src/pipeline/ports.ts +62 -0
  53. package/src/pipeline/states.ts +56 -0
  54. package/src/pipeline/tile-3d.ts +165 -0
  55. package/src/ports/camera.ts +12 -0
  56. package/src/ports/content.ts +71 -0
  57. package/src/ports/glyph.ts +13 -0
  58. package/src/ports/index.ts +32 -0
  59. package/src/ports/resource.ts +54 -0
  60. package/src/ports/spatial.ts +28 -0
  61. package/src/ports/telemetry.ts +44 -0
  62. package/src/runtime/cache.ts +112 -0
  63. package/src/runtime/contracts.ts +77 -0
  64. package/src/runtime/events.ts +57 -0
  65. package/src/runtime/hooks.ts +99 -0
  66. package/src/runtime/index.ts +7 -0
  67. package/src/runtime/instrumentation.ts +163 -0
  68. package/src/runtime/priority-scheduler.ts +88 -0
  69. package/src/runtime/quadtree-balance.ts +215 -0
  70. package/src/runtime/tile-runtime.ts +3508 -0
  71. package/src/spatial/bounding-volumes.ts +159 -0
  72. package/src/spatial/ecef-types.ts +110 -0
  73. package/src/spatial/ecef.ts +196 -0
  74. package/src/spatial/index.ts +6 -0
  75. package/src/spatial/utm-bounds.ts +151 -0
  76. package/src/spatial/utm-types.ts +83 -0
  77. package/src/spatial/vertical-scale.ts +125 -0
  78. package/src/spatial/view-metrics.ts +132 -0
@@ -0,0 +1,71 @@
1
+ import { SubtreeCodec } from "@spacexr/3d-tiles-core";
2
+
3
+ import type { IRuntimeUriResolver } from "../ports/resource";
4
+ import { StandardUriResolver } from "../ports/resource";
5
+ import type { IImplicitSubtreeLoader, IImplicitSubtreeLoadRequest, ILoadedImplicitSubtree } from "./types";
6
+
7
+ export interface IByteResourceLoadRequest {
8
+ uri: string;
9
+ signal: AbortSignal;
10
+ }
11
+
12
+ export interface IByteResourceLoader {
13
+ load(request: IByteResourceLoadRequest): Promise<Uint8Array>;
14
+ }
15
+
16
+ export type FetchFunction = (input: string, init?: RequestInit) => Promise<Response>;
17
+
18
+ export class FetchByteResourceLoader implements IByteResourceLoader {
19
+ public constructor(private readonly fetcher: FetchFunction = globalThis.fetch.bind(globalThis)) {}
20
+
21
+ public async load(request: IByteResourceLoadRequest): Promise<Uint8Array> {
22
+ const response = await this.fetcher(request.uri, { signal: request.signal });
23
+ if (!response.ok) throw new Error(`Resource request failed with HTTP ${response.status} for ${request.uri}.`);
24
+ return new Uint8Array(await response.arrayBuffer());
25
+ }
26
+ }
27
+
28
+ export interface IStandardImplicitSubtreeLoaderOptions {
29
+ resources: IByteResourceLoader;
30
+ uri?: IRuntimeUriResolver;
31
+ }
32
+
33
+ /** Loads standard JSON and binary subtree files, including external buffers. */
34
+ export class StandardImplicitSubtreeLoader implements IImplicitSubtreeLoader {
35
+ private readonly resources: IByteResourceLoader;
36
+ private readonly uri: IRuntimeUriResolver;
37
+ private readonly codec = new SubtreeCodec();
38
+
39
+ public constructor(options: IStandardImplicitSubtreeLoaderOptions) {
40
+ this.resources = options.resources;
41
+ this.uri = options.uri ?? new StandardUriResolver();
42
+ }
43
+
44
+ public async load(request: IImplicitSubtreeLoadRequest): Promise<ILoadedImplicitSubtree> {
45
+ const bytes = await this.resources.load({ uri: request.uri, signal: request.signal });
46
+ const decoded = this.codec.decode(bytes);
47
+ const declarations = decoded.subtree.buffers ?? [];
48
+ if (declarations.length === 0) return { subtree: decoded.subtree };
49
+
50
+ const baseUri = this.uri.baseOf(request.uri);
51
+ const buffers = await Promise.all(
52
+ declarations.map(async (buffer, index) => {
53
+ let payload: Uint8Array;
54
+ if (buffer.uri) {
55
+ payload = await this.resources.load({ uri: this.uri.resolve(buffer.uri, baseUri), signal: request.signal });
56
+ } else if (index === 0 && decoded.binaryChunk) {
57
+ payload = decoded.binaryChunk;
58
+ } else {
59
+ throw new Error(`Subtree buffer ${index} has no URI and no internal binary chunk.`);
60
+ }
61
+ if (payload.byteLength < buffer.byteLength) {
62
+ throw new Error(
63
+ `Subtree buffer ${index} declares ${buffer.byteLength} bytes but only ${payload.byteLength} were loaded.`,
64
+ );
65
+ }
66
+ return payload.subarray(0, buffer.byteLength);
67
+ }),
68
+ );
69
+ return { subtree: decoded.subtree, buffers };
70
+ }
71
+ }
@@ -0,0 +1,120 @@
1
+ import type { IBoundingVolume, IContent, IMetadataEntity, ITileset } from "@spacexr/3d-tiles-core";
2
+
3
+ import type { ITileMetrics } from "@spacexr/tiles";
4
+ import type {
5
+ IImplicitCoordinates,
6
+ IImplicitTileAddressContext,
7
+ IImplicitTileOverride,
8
+ IImplicitTileResolveContext,
9
+ IImplicitTileResolver,
10
+ } from "./types";
11
+
12
+ export interface ITileAddress {
13
+ /** Root of the address on a pyramid of several roots, such as a multi-root pyramid; omitted for face 0. */
14
+ face?: number;
15
+ lod: number;
16
+ x: number;
17
+ y: number;
18
+ z?: number;
19
+ }
20
+
21
+ export interface ITileDataSourceTile {
22
+ address: ITileAddress;
23
+ boundingVolume: IBoundingVolume;
24
+ geometricError: number;
25
+ contents: readonly IContent[];
26
+ metadata?: IMetadataEntity;
27
+ }
28
+
29
+ /**
30
+ * Owns the physical pyramid definition consumed by a tileset decorator.
31
+ *
32
+ * Metrics, addressing and URL templates belong to the data source. The 3D
33
+ * Tiles implicit representation is only one possible view over this source.
34
+ */
35
+ export interface ITileDataSource {
36
+ readonly id: string;
37
+ readonly metrics: Pick<ITileMetrics, "minLOD" | "maxLOD">;
38
+ readonly rootAddress: ITileAddress;
39
+ readonly urlTemplates: readonly string[];
40
+ addressOf(coordinates: IImplicitCoordinates): ITileAddress;
41
+ resolve(coordinates: IImplicitCoordinates, computedContents?: readonly IContent[]): ITileDataSourceTile;
42
+ }
43
+
44
+ export interface IImplicitTilesetDecoratorOptions {
45
+ subtreeLevels?: number;
46
+ refine?: "ADD" | "REPLACE";
47
+ }
48
+
49
+ function implicitTemplate(template: string): string {
50
+ return template.replaceAll("{z}", "{level}").replaceAll("{lod}", "{level}");
51
+ }
52
+
53
+ /**
54
+ * Presents an `ITileDataSource` as a standard implicit 3D Tiles tileset.
55
+ *
56
+ * The decorator owns no pyramid metric or URL policy. `availableLevels` is
57
+ * derived from the source metrics and resolution delegates back to the source.
58
+ */
59
+ export class ImplicitTilesetDecorator implements IImplicitTileResolver {
60
+ public readonly tileset: ITileset;
61
+
62
+ public constructor(
63
+ public readonly dataSource: ITileDataSource,
64
+ options: IImplicitTilesetDecoratorOptions = {},
65
+ ) {
66
+ const { metrics, rootAddress } = dataSource;
67
+ if (rootAddress.lod !== metrics.minLOD)
68
+ throw new RangeError(`The source root LOD ${rootAddress.lod} must equal metrics.minLOD ${metrics.minLOD}.`);
69
+ if (dataSource.urlTemplates.length === 0) throw new RangeError("A tile data source must expose at least one URL template.");
70
+ const subtreeLevels = options.subtreeLevels ?? 4;
71
+ if (!Number.isInteger(subtreeLevels) || subtreeLevels < 1)
72
+ throw new RangeError("Implicit subtreeLevels must be a positive integer.");
73
+
74
+ const root = dataSource.resolve({ level: 0, x: 0, y: 0 });
75
+ const templates = dataSource.urlTemplates.map((template, index) => ({
76
+ ...(root.contents[index] ?? root.contents[0] ?? {}),
77
+ uri: implicitTemplate(template),
78
+ }));
79
+ const contentShape =
80
+ templates.length === 1
81
+ ? { content: templates[0]! }
82
+ : {
83
+ contents: templates as [IContent, ...IContent[]],
84
+ };
85
+ this.tileset = {
86
+ asset: { version: "1.1" },
87
+ geometricError: root.geometricError,
88
+ root: {
89
+ boundingVolume: root.boundingVolume,
90
+ geometricError: root.geometricError,
91
+ refine: options.refine ?? "REPLACE",
92
+ ...(root.metadata ? { metadata: root.metadata } : {}),
93
+ ...contentShape,
94
+ implicitTiling: {
95
+ subdivisionScheme: "QUADTREE",
96
+ subtreeLevels,
97
+ availableLevels: metrics.maxLOD - metrics.minLOD + 1,
98
+ subtrees: {
99
+ uri: "virtual-subtrees/{level}/{x}/{y}.subtree",
100
+ },
101
+ },
102
+ },
103
+ };
104
+ }
105
+
106
+ /** Address of the tile in the source pyramid, shared by every decorator of the same pyramid. */
107
+ public addressOf(context: IImplicitTileAddressContext): ITileAddress {
108
+ return this.dataSource.addressOf(context.coordinates);
109
+ }
110
+
111
+ public resolve(context: IImplicitTileResolveContext): IImplicitTileOverride {
112
+ const tile = this.dataSource.resolve(context.coordinates, context.computedContents);
113
+ return {
114
+ boundingVolume: tile.boundingVolume,
115
+ geometricError: tile.geometricError,
116
+ contents: tile.contents,
117
+ ...(tile.metadata ? { metadata: tile.metadata } : {}),
118
+ };
119
+ }
120
+ }
@@ -0,0 +1,156 @@
1
+ import type { IBoundingVolume, IContent, IImplicitTiling, IMetadataEntity, IMetadataSchema, ISubtree, ITile } from "@spacexr/3d-tiles-core";
2
+
3
+ import type { TileReadinessState } from "../pipeline/states";
4
+ import type { ITileAddress } from "./tile-data-source";
5
+
6
+ export interface IImplicitCoordinates {
7
+ level: number;
8
+ x: number;
9
+ y: number;
10
+ z?: number;
11
+ }
12
+
13
+ export interface ILoadedImplicitSubtree {
14
+ subtree: ISubtree;
15
+ /** Buffer payloads indexed exactly like subtree.buffers. */
16
+ buffers?: readonly Uint8Array[];
17
+ }
18
+
19
+ export interface IImplicitSubtreeLoadRequest {
20
+ uri: string;
21
+ documentUri: string;
22
+ coordinates: IImplicitCoordinates;
23
+ implicitTiling: IImplicitTiling;
24
+ contentCount: number;
25
+ signal: AbortSignal;
26
+ }
27
+
28
+ export interface IImplicitSubtreeLoader {
29
+ load(request: IImplicitSubtreeLoadRequest): Promise<ILoadedImplicitSubtree>;
30
+ }
31
+
32
+ export interface IImplicitTileResolveContext {
33
+ documentUri: string;
34
+ rootTile: ITile;
35
+ implicitTiling: IImplicitTiling;
36
+ coordinates: IImplicitCoordinates;
37
+ computedBoundingVolume: IBoundingVolume;
38
+ computedGeometricError: number;
39
+ computedContents: readonly IContent[];
40
+ }
41
+
42
+ export interface IImplicitTileOverride {
43
+ boundingVolume?: IBoundingVolume;
44
+ geometricError?: number;
45
+ contents?: readonly IContent[];
46
+ metadata?: IMetadataEntity;
47
+ /** Heights of the terrain of the tile when they are known before its content, prepared by its parent for example. */
48
+ heightRange?: readonly [number, number];
49
+ }
50
+
51
+ export interface IImplicitTileAddressContext {
52
+ documentUri: string;
53
+ rootTile: ITile;
54
+ implicitTiling: IImplicitTiling;
55
+ coordinates: IImplicitCoordinates;
56
+ }
57
+
58
+ /**
59
+ * Optional runtime override for sources whose physical pyramid differs from
60
+ * the regular 3D Tiles subdivision, for example XYZ Web Mercator services.
61
+ */
62
+ export interface IImplicitTileResolver {
63
+ resolve(context: IImplicitTileResolveContext): IImplicitTileOverride | undefined;
64
+ /**
65
+ * Address of an implicit tile in a pyramid shared by several implicit
66
+ * tilesets, in the XYZ convention. Quadtree balancing uses it to find
67
+ * neighbours across implicit roots; without it, neighbours are searched
68
+ * within each implicit tileset only.
69
+ */
70
+ addressOf?(context: IImplicitTileAddressContext): ITileAddress | undefined;
71
+ /**
72
+ * Implicit subtree registered at an implicit tile, whose rules apply from
73
+ * that tile down; `undefined` keeps the rules of the tileset. Called for
74
+ * each tile the tileset makes available, before the tile is created.
75
+ */
76
+ subtreeAt?(context: IImplicitTileAddressContext): IImplicitSubtreeGraft | undefined;
77
+ }
78
+
79
+ /**
80
+ * An implicit subtree registered at a tile of an implicit tileset, with its own rules.
81
+ *
82
+ * From the registered tile down, the subtree replaces the rules of the tileset: its implicit tiling, hence its own
83
+ * levels and availability, its content templates, its resolver and its subtree loader. Its root tile takes the place
84
+ * of the registered tile, contents included. A subtree may stop the refinement early, make tiles unavailable, supply
85
+ * other contents, or go deeper than the tileset. Subtrees may register subtrees of their own.
86
+ */
87
+ export interface IImplicitSubtreeGraft {
88
+ /** Root tile of the subtree: an implicit root tile, with `implicitTiling` and the content templates of the subtree. */
89
+ tile: ITile;
90
+ /** Resolves the tiles of the subtree, and the subtrees registered inside it. Defaults to the resolver of the tileset. */
91
+ resolver?: IImplicitTileResolver;
92
+ /** Loads the availability subtrees of the subtree. Defaults to the subtree loader of the adapter. */
93
+ subtrees?: IImplicitSubtreeLoader;
94
+ }
95
+
96
+ export interface IImplicitMetadataDecodeRequest {
97
+ loaded: ILoadedImplicitSubtree;
98
+ availability: ISubtreeAvailability;
99
+ schema?: IMetadataSchema;
100
+ implicitTiling: IImplicitTiling;
101
+ coordinates: IImplicitCoordinates;
102
+ localCoordinates: IImplicitCoordinates;
103
+ contentCount: number;
104
+ }
105
+
106
+ export interface IImplicitMetadataDecodeResult {
107
+ tileMetadata?: IMetadataEntity;
108
+ contentMetadata?: readonly (IMetadataEntity | undefined)[];
109
+ }
110
+
111
+ /** Decodes binary property tables after a standard subtree has been loaded. */
112
+ export interface IImplicitMetadataDecoder {
113
+ decode(request: IImplicitMetadataDecodeRequest): IImplicitMetadataDecodeResult;
114
+ }
115
+
116
+ export type ImplicitSubtreeStatus = TileReadinessState;
117
+
118
+ export interface IRuntimeImplicitContext {
119
+ id: string;
120
+ rootTile: ITile;
121
+ implicitTiling: IImplicitTiling;
122
+ contentTemplates: readonly IContent[];
123
+ /** Resolver of a registered subtree, in place of the resolver of the adapter. */
124
+ resolver?: IImplicitTileResolver;
125
+ /** Subtree loader of a registered subtree, in place of the loader of the adapter. */
126
+ subtrees?: IImplicitSubtreeLoader;
127
+ }
128
+
129
+ export interface IRuntimeImplicitSubtree {
130
+ uri: string;
131
+ coordinates: IImplicitCoordinates;
132
+ status: ImplicitSubtreeStatus;
133
+ attempts: number;
134
+ loaded?: ILoadedImplicitSubtree;
135
+ availability?: ISubtreeAvailability;
136
+ error?: unknown;
137
+ estimatedBytes: number;
138
+ lastTouchedFrame: number;
139
+ }
140
+
141
+ export interface IRuntimeImplicitTile {
142
+ context: IRuntimeImplicitContext;
143
+ coordinates: IImplicitCoordinates;
144
+ localCoordinates: IImplicitCoordinates;
145
+ subtree: IRuntimeImplicitSubtree;
146
+ childrenMaterialized: boolean;
147
+ metadataApplied: boolean;
148
+ /** Heights given by the resolver the last time it resolved the tile. */
149
+ heightRange?: readonly [number, number];
150
+ }
151
+
152
+ export interface ISubtreeAvailability {
153
+ isTileAvailable(coordinates: IImplicitCoordinates): boolean;
154
+ isContentAvailable(contentIndex: number, coordinates: IImplicitCoordinates): boolean;
155
+ isChildSubtreeAvailable(coordinates: IImplicitCoordinates): boolean;
156
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./implicit";
2
+ export * from "./metadata";
3
+ export * from "./pipeline";
4
+ export * from "./ports";
5
+ export * from "./runtime";
6
+ export * from "./spatial";
@@ -0,0 +1,2 @@
1
+ export * from "./metadata-resolver";
2
+ export * from "./types";
@@ -0,0 +1,308 @@
1
+ import type {
2
+ IMetadataClassProperty,
3
+ IMetadataEntity,
4
+ IMetadataSchema,
5
+ MetadataComponentType,
6
+ MetadataValue,
7
+ } from "@spacexr/3d-tiles-core";
8
+
9
+ import type {
10
+ IMetadataDiagnostic,
11
+ IMetadataResolutionInput,
12
+ IMetadataSnapshot,
13
+ IResolvedMetadataEntity,
14
+ IResolvedMetadataProperty,
15
+ MetadataScopeKind,
16
+ MetadataScopeOrder,
17
+ } from "./types";
18
+
19
+ const VECTOR_LENGTHS: Readonly<Record<string, number>> = { VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16 };
20
+
21
+ const INTEGER_RANGES: Readonly<Record<MetadataComponentType, readonly [number, number] | undefined>> = {
22
+ INT8: [-128, 127],
23
+ UINT8: [0, 255],
24
+ INT16: [-32768, 32767],
25
+ UINT16: [0, 65535],
26
+ INT32: [-2147483648, 2147483647],
27
+ UINT32: [0, 4294967295],
28
+ INT64: undefined,
29
+ UINT64: undefined,
30
+ FLOAT32: undefined,
31
+ FLOAT64: undefined,
32
+ };
33
+
34
+ export const DEFAULT_METADATA_SCOPE_ORDER: MetadataScopeOrder = [
35
+ "feature",
36
+ "content",
37
+ "tile",
38
+ "ancestor-tile",
39
+ "subtree",
40
+ "group",
41
+ "tileset",
42
+ ];
43
+
44
+ function valuesEqual(left: unknown, right: unknown): boolean {
45
+ if (left === right) return true;
46
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;
47
+ return left.every((value, index) => valuesEqual(value, right[index]));
48
+ }
49
+
50
+ function valueAt(value: MetadataValue | undefined, index: number): MetadataValue | undefined {
51
+ if (!Array.isArray(value)) return value;
52
+ return value[index];
53
+ }
54
+
55
+ function normalizeNumber(value: number, componentType: MetadataComponentType | undefined): number {
56
+ if (!componentType) return value;
57
+ const range = INTEGER_RANGES[componentType];
58
+ if (!range) return value;
59
+ if (range[0] < 0) return Math.max(value / range[1], -1);
60
+ return value / range[1];
61
+ }
62
+
63
+ function transformValue(value: MetadataValue, definition: IMetadataClassProperty): MetadataValue {
64
+ const transformNumber = (item: number, index: number): number => {
65
+ const normalized = definition.normalized ? normalizeNumber(item, definition.componentType) : item;
66
+ const scale = valueAt(definition.scale, index);
67
+ const offset = valueAt(definition.offset, index);
68
+ return normalized * (typeof scale === "number" ? scale : 1) + (typeof offset === "number" ? offset : 0);
69
+ };
70
+
71
+ if (typeof value === "number") return transformNumber(value, 0);
72
+ if (Array.isArray(value)) {
73
+ return value.map((item, index) => (typeof item === "number" ? transformNumber(item, index) : item)) as MetadataValue;
74
+ }
75
+ return value;
76
+ }
77
+
78
+ function validateComponentNumber(value: unknown, definition: IMetadataClassProperty): boolean {
79
+ if (typeof value !== "number" || !Number.isFinite(value)) return false;
80
+ const component = definition.componentType;
81
+ if (!component || component.startsWith("FLOAT")) return true;
82
+ if (!Number.isInteger(value)) return false;
83
+ const range = INTEGER_RANGES[component];
84
+ return !range || (value >= range[0] && value <= range[1]);
85
+ }
86
+
87
+ function isValueValid(value: unknown, definition: IMetadataClassProperty, schema: IMetadataSchema | undefined): boolean {
88
+ if (definition.array) {
89
+ if (!Array.isArray(value)) return false;
90
+ if (definition.count !== undefined && value.length !== definition.count) return false;
91
+ return value.every((item) => isSingleValueValid(item, { ...definition, array: false }, schema));
92
+ }
93
+ return isSingleValueValid(value, definition, schema);
94
+ }
95
+
96
+ function isSingleValueValid(value: unknown, definition: IMetadataClassProperty, schema: IMetadataSchema | undefined): boolean {
97
+ if (definition.type === "BOOLEAN") return typeof value === "boolean";
98
+ if (definition.type === "STRING") return typeof value === "string";
99
+ if (definition.type === "ENUM") {
100
+ if (typeof value !== "string" || !definition.enumType) return false;
101
+ return schema?.enums?.[definition.enumType]?.values.some((candidate) => candidate.name === value) ?? false;
102
+ }
103
+ if (definition.type === "SCALAR") return validateComponentNumber(value, definition);
104
+
105
+ const expectedLength = VECTOR_LENGTHS[definition.type];
106
+ return (
107
+ expectedLength !== undefined &&
108
+ Array.isArray(value) &&
109
+ value.length === expectedLength &&
110
+ value.every((item) => validateComponentNumber(item, definition))
111
+ );
112
+ }
113
+
114
+ export class MetadataResolver {
115
+ public resolve(input: IMetadataResolutionInput): IMetadataSnapshot {
116
+ const scopes: IResolvedMetadataEntity[] = [];
117
+ const diagnostics: IMetadataDiagnostic[] = [...input.document.diagnostics];
118
+ const append = (
119
+ scope: MetadataScopeKind,
120
+ ownerId: string,
121
+ entity: IMetadataEntity | undefined,
122
+ path: string,
123
+ featureId?: string | number,
124
+ ): void => {
125
+ if (!entity) return;
126
+ const resolved = this.resolveEntity(input.document.uri, input.document.schema, scope, ownerId, entity, path, featureId);
127
+ scopes.push(resolved);
128
+ diagnostics.push(...resolved.diagnostics);
129
+ };
130
+
131
+ append("tileset", input.document.uri, input.document.tileset.metadata, "$.metadata");
132
+ if (input.subtree) {
133
+ const resolved = this.resolveEntity(
134
+ input.subtree.documentUri,
135
+ input.document.schema,
136
+ "subtree",
137
+ input.subtree.id,
138
+ input.subtree.entity,
139
+ `${input.subtree.id}.subtreeMetadata`,
140
+ );
141
+ scopes.push(resolved);
142
+ diagnostics.push(...resolved.diagnostics);
143
+ }
144
+ for (const ancestor of input.ancestors) {
145
+ diagnostics.push(...ancestor.document.diagnostics);
146
+ if (ancestor.tile.metadata) {
147
+ const resolved = this.resolveEntity(
148
+ ancestor.document.uri,
149
+ ancestor.document.schema,
150
+ "ancestor-tile",
151
+ ancestor.id,
152
+ ancestor.tile.metadata,
153
+ `${ancestor.id}.metadata`,
154
+ );
155
+ scopes.push(resolved);
156
+ diagnostics.push(...resolved.diagnostics);
157
+ }
158
+ }
159
+ append("tile", input.tileId, input.tile.metadata, `${input.tileId}.metadata`);
160
+
161
+ if (input.content?.group !== undefined) {
162
+ const group = input.document.tileset.groups?.[input.content.group];
163
+ if (group) {
164
+ append("group", `${input.document.uri}#group/${input.content.group}`, group, `$.groups[${input.content.group}]`);
165
+ } else {
166
+ diagnostics.push({
167
+ code: "METADATA_GROUP_OUT_OF_RANGE",
168
+ severity: "error",
169
+ message: `Content references missing group ${input.content.group}.`,
170
+ path: `${input.tileId}.content.group`,
171
+ documentUri: input.document.uri,
172
+ });
173
+ }
174
+ }
175
+
176
+ append("content", `${input.tileId}.content`, input.content?.metadata, `${input.tileId}.content.metadata`);
177
+ for (const feature of input.features ?? []) {
178
+ const resolved = this.resolveEntity(
179
+ feature.sourceUri ?? input.document.uri,
180
+ feature.schema ?? input.document.schema,
181
+ "feature",
182
+ `${input.tileId}.feature/${feature.id ?? scopes.length}`,
183
+ feature.entity,
184
+ `${input.tileId}.features[${String(feature.id ?? scopes.length)}]`,
185
+ feature.id,
186
+ );
187
+ scopes.push(resolved);
188
+ diagnostics.push(...resolved.diagnostics);
189
+ }
190
+
191
+ return {
192
+ document: input.document,
193
+ tileId: input.tileId,
194
+ tile: input.tile,
195
+ ...(input.content ? { content: input.content } : {}),
196
+ scopes,
197
+ diagnostics,
198
+ };
199
+ }
200
+
201
+ public findBySemantic(
202
+ snapshot: IMetadataSnapshot,
203
+ semantic: string,
204
+ order: MetadataScopeOrder = DEFAULT_METADATA_SCOPE_ORDER,
205
+ ): IResolvedMetadataProperty | undefined {
206
+ for (const scopeKind of order) {
207
+ for (let index = snapshot.scopes.length - 1; index >= 0; index--) {
208
+ const scope = snapshot.scopes[index];
209
+ if (scope?.scope !== scopeKind) continue;
210
+ const property = Object.values(scope.properties).find((candidate) => candidate.semantic === semantic);
211
+ if (property) return property;
212
+ }
213
+ }
214
+ return undefined;
215
+ }
216
+
217
+ private resolveEntity(
218
+ documentUri: string,
219
+ schema: IMetadataSchema | undefined,
220
+ scope: MetadataScopeKind,
221
+ ownerId: string,
222
+ entity: IMetadataEntity,
223
+ path: string,
224
+ featureId?: string | number,
225
+ ): IResolvedMetadataEntity {
226
+ const diagnostics: IMetadataDiagnostic[] = [];
227
+ const classDefinition = schema?.classes?.[entity.class];
228
+ if (!schema) {
229
+ diagnostics.push({
230
+ code: "METADATA_SCHEMA_UNAVAILABLE",
231
+ severity: "warning",
232
+ message: `Cannot validate class "${entity.class}" because its schema is unavailable.`,
233
+ path,
234
+ documentUri,
235
+ });
236
+ } else if (!classDefinition) {
237
+ diagnostics.push({
238
+ code: "METADATA_CLASS_UNKNOWN",
239
+ severity: "error",
240
+ message: `Class "${entity.class}" is not declared by schema "${schema.id}".`,
241
+ path: `${path}.class`,
242
+ documentUri,
243
+ });
244
+ }
245
+
246
+ const propertyIds = new Set([...Object.keys(classDefinition?.properties ?? {}), ...Object.keys(entity.properties ?? {})]);
247
+ const properties: Record<string, IResolvedMetadataProperty> = {};
248
+
249
+ for (const propertyId of propertyIds) {
250
+ const definition = classDefinition?.properties?.[propertyId];
251
+ const rawValue = entity.properties?.[propertyId];
252
+ const isNoData = definition?.noData !== undefined && rawValue !== undefined && valuesEqual(rawValue, definition.noData);
253
+ const fromDefault = (rawValue === undefined || isNoData) && definition?.default !== undefined;
254
+ const sourceValue = fromDefault ? definition?.default : isNoData ? undefined : rawValue;
255
+ const value = sourceValue !== undefined && definition ? transformValue(sourceValue, definition) : sourceValue;
256
+
257
+ if (!definition) {
258
+ diagnostics.push({
259
+ code: "METADATA_PROPERTY_UNKNOWN",
260
+ severity: "warning",
261
+ message: `Property "${propertyId}" is not declared by class "${entity.class}".`,
262
+ path: `${path}.properties.${propertyId}`,
263
+ documentUri,
264
+ });
265
+ } else {
266
+ if (definition.required && sourceValue === undefined) {
267
+ diagnostics.push({
268
+ code: "METADATA_PROPERTY_REQUIRED",
269
+ severity: "error",
270
+ message: `Required property "${propertyId}" is missing.`,
271
+ path: `${path}.properties.${propertyId}`,
272
+ documentUri,
273
+ });
274
+ }
275
+ if (sourceValue !== undefined && !isValueValid(sourceValue, definition, schema)) {
276
+ diagnostics.push({
277
+ code: "METADATA_PROPERTY_TYPE",
278
+ severity: "error",
279
+ message: `Property "${propertyId}" does not conform to its ${definition.type} definition.`,
280
+ path: `${path}.properties.${propertyId}`,
281
+ documentUri,
282
+ });
283
+ }
284
+ }
285
+
286
+ properties[propertyId] = {
287
+ id: propertyId,
288
+ ...(definition ? { definition, semantic: definition.semantic } : {}),
289
+ ...(rawValue !== undefined ? { rawValue } : {}),
290
+ ...(value !== undefined ? { value } : {}),
291
+ fromDefault,
292
+ isNoData,
293
+ };
294
+ }
295
+
296
+ return {
297
+ scope,
298
+ ownerId,
299
+ documentUri,
300
+ ...(featureId !== undefined ? { featureId } : {}),
301
+ entity,
302
+ classId: entity.class,
303
+ ...(classDefinition ? { classDefinition } : {}),
304
+ properties,
305
+ diagnostics,
306
+ };
307
+ }
308
+ }