space-data-module-sdk 0.10.4 → 0.12.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.
@@ -0,0 +1,1688 @@
1
+ import * as flatbuffers from "flatbuffers";
2
+ import { SCR } from "spacedatastandards.org/lib/js/SCR/SCR.js";
3
+ import { SCRGrid } from "spacedatastandards.org/lib/js/SCR/SCRGrid.js";
4
+ import { BufferMutability } from "../generated/orbpro/stream/buffer-mutability.js";
5
+ import { BufferOwnership } from "../generated/orbpro/stream/buffer-ownership.js";
6
+ import { createRuntimeRegionStore } from "./runtimeRegionStore.js";
7
+
8
+ export const SCR_GRID_STATE_FLOATS = 8;
9
+ export const SCR_GRID_STATE_BYTES = 32;
10
+ export const SCR_RADIUS_BAND_FLOATS = 2;
11
+ export const SCR_RADIUS_BAND_BYTES = 8;
12
+ export const SCR_ROLE = Object.freeze({
13
+ SECONDARY: 0,
14
+ PRIMARY: 1,
15
+ SKIP: 2,
16
+ });
17
+ export const SCR_ROLE_MASK_ALL = 0x7;
18
+ export const SCR_GRID_LAYOUT_ID = "SCR.GRID.ALIGNED";
19
+
20
+ export const DEFAULT_PROPAGATOR_ID = "propagator/sdn-ap";
21
+ export const SUPPORTED_PROPAGATOR_IDS = Object.freeze([
22
+ "propagator/sdn-ap",
23
+ "propagator/sgp4-xp",
24
+ "propagator/sgp4",
25
+ ]);
26
+ export const DECLARED_ORBIT_THEORIES = Object.freeze([
27
+ "SGP4",
28
+ "SGP4XP",
29
+ "AP",
30
+ ]);
31
+
32
+ const DEFAULT_THEORY_SUPPORT = Object.freeze({
33
+ "propagator/sdn-ap": Object.freeze(["AP", "SGP4XP", "SGP4"]),
34
+ "propagator/sgp4-xp": Object.freeze(["SGP4XP", "SGP4"]),
35
+ "propagator/sgp4": Object.freeze(["SGP4"]),
36
+ });
37
+
38
+ const PREFERRED_PROPAGATOR_BY_THEORY = Object.freeze({
39
+ AP: "propagator/sdn-ap",
40
+ SGP4XP: "propagator/sgp4-xp",
41
+ SGP4: "propagator/sgp4",
42
+ });
43
+
44
+ const PROPAGATOR_ALIASES = Object.freeze({
45
+ "sdn-ap": "propagator/sdn-ap",
46
+ sdn_ap: "propagator/sdn-ap",
47
+ sdnap: "propagator/sdn-ap",
48
+ "propagator/sdn-ap": "propagator/sdn-ap",
49
+ "com.digitalarsenal.propagator.sdn-ap": "propagator/sdn-ap",
50
+ "sgp4-xp": "propagator/sgp4-xp",
51
+ sgp4_xp: "propagator/sgp4-xp",
52
+ sgp4xp: "propagator/sgp4-xp",
53
+ "propagator/sgp4-xp": "propagator/sgp4-xp",
54
+ "com.digitalarsenal.propagator.sgp4-xp": "propagator/sgp4-xp",
55
+ sgp4: "propagator/sgp4",
56
+ "propagator/sgp4": "propagator/sgp4",
57
+ "com.orbpro.sgp4": "propagator/sgp4",
58
+ });
59
+
60
+ const MUTATING_TYPED_ARRAY_METHODS = new Set([
61
+ "set",
62
+ "fill",
63
+ "copyWithin",
64
+ "reverse",
65
+ "sort",
66
+ ]);
67
+
68
+ const HOST_IS_LITTLE_ENDIAN =
69
+ new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;
70
+
71
+ export class TheoryMismatchError extends Error {
72
+ constructor(
73
+ message,
74
+ { recordId = null, declaredTheory = null, propagatorId = null } = {},
75
+ ) {
76
+ super(message);
77
+ this.name = "TheoryMismatchError";
78
+ this.code = "ERR_DECLARED_THEORY_MISMATCH";
79
+ this.recordId = recordId;
80
+ this.declaredTheory = declaredTheory;
81
+ this.propagatorId = propagatorId;
82
+ }
83
+ }
84
+
85
+ export class StaleGridLeaseError extends Error {
86
+ constructor(
87
+ message,
88
+ {
89
+ regionId = null,
90
+ moduleId = null,
91
+ attachedGeneration = null,
92
+ currentGeneration = null,
93
+ } = {},
94
+ ) {
95
+ super(message);
96
+ this.name = "StaleGridLeaseError";
97
+ this.code = "ERR_STALE_GRID_LEASE";
98
+ this.regionId = regionId;
99
+ this.moduleId = moduleId;
100
+ this.attachedGeneration = attachedGeneration;
101
+ this.currentGeneration = currentGeneration;
102
+ }
103
+ }
104
+
105
+ function normalizeNonEmptyString(value, label) {
106
+ if (typeof value === "number" && Number.isFinite(value)) {
107
+ return String(value);
108
+ }
109
+ if (typeof value !== "string" || value.trim().length === 0) {
110
+ throw new TypeError(`${label} must be a non-empty string.`);
111
+ }
112
+ return value.trim();
113
+ }
114
+
115
+ function normalizeFiniteNumber(value, label) {
116
+ const num = Number(value);
117
+ if (!Number.isFinite(num)) {
118
+ throw new TypeError(`${label} must be a finite number.`);
119
+ }
120
+ return num;
121
+ }
122
+
123
+ function normalizePositiveNumber(value, label) {
124
+ const num = normalizeFiniteNumber(value, label);
125
+ if (num <= 0) {
126
+ throw new RangeError(`${label} must be greater than 0.`);
127
+ }
128
+ return num;
129
+ }
130
+
131
+ function normalizeNonNegativeInteger(value, label) {
132
+ const num = Number(value);
133
+ if (!Number.isInteger(num) || num < 0) {
134
+ throw new TypeError(`${label} must be a non-negative integer.`);
135
+ }
136
+ return num;
137
+ }
138
+
139
+ function normalizePositiveInteger(value, label) {
140
+ const num = Number(value);
141
+ if (!Number.isInteger(num) || num <= 0) {
142
+ throw new TypeError(`${label} must be a positive integer.`);
143
+ }
144
+ return num;
145
+ }
146
+
147
+ function normalizeRoleMask(roleMask = SCR_ROLE_MASK_ALL) {
148
+ if (roleMask === null || roleMask === undefined) {
149
+ return SCR_ROLE_MASK_ALL;
150
+ }
151
+ const num = Number(roleMask);
152
+ if (!Number.isInteger(num) || num < 0 || num > 0xffffffff) {
153
+ throw new TypeError("roleMask must be an unsigned 32-bit integer.");
154
+ }
155
+ return num >>> 0;
156
+ }
157
+
158
+ function normalizeRolesArray(roles, objectCount) {
159
+ if (roles === null || roles === undefined) {
160
+ return null;
161
+ }
162
+ const arr =
163
+ roles instanceof Uint8Array
164
+ ? new Uint8Array(roles)
165
+ : Uint8Array.from(roles, (value) => Number(value));
166
+ if (arr.length !== objectCount) {
167
+ throw new RangeError(
168
+ `roles length (${arr.length}) must match objectCount (${objectCount}).`,
169
+ );
170
+ }
171
+ for (let i = 0; i < arr.length; i += 1) {
172
+ if (
173
+ arr[i] !== SCR_ROLE.SECONDARY &&
174
+ arr[i] !== SCR_ROLE.PRIMARY &&
175
+ arr[i] !== SCR_ROLE.SKIP
176
+ ) {
177
+ throw new RangeError(
178
+ `Invalid SCR role ${arr[i]} at index ${i}; expected 0 (SECONDARY), 1 (PRIMARY), or 2 (SKIP).`,
179
+ );
180
+ }
181
+ }
182
+ return arr;
183
+ }
184
+
185
+ export function resolvePropagatorId(id = DEFAULT_PROPAGATOR_ID) {
186
+ if (id === null || id === undefined || String(id).trim() === "") {
187
+ return DEFAULT_PROPAGATOR_ID;
188
+ }
189
+ const raw = String(id).trim();
190
+ const alias = PROPAGATOR_ALIASES[raw.toLowerCase()];
191
+ return alias ?? raw;
192
+ }
193
+
194
+ export function normalizeDeclaredTheory(value, recordLabel = "record") {
195
+ if (value === null || value === undefined || String(value).trim() === "") {
196
+ throw new TypeError(
197
+ `Catalog record ${recordLabel} must declare its orbit theory (declaredTheory: SGP4 | SGP4XP | AP).`,
198
+ );
199
+ }
200
+ const token = String(value)
201
+ .trim()
202
+ .toUpperCase()
203
+ .replace(/[\s_-]+/g, "");
204
+ if (token === "SGP4") return "SGP4";
205
+ if (token === "SGP4XP") return "SGP4XP";
206
+ if (token === "AP" || token === "SDNAP") return "AP";
207
+ throw new TypeError(
208
+ `Unsupported declaredTheory "${String(value)}" on catalog record ${recordLabel}.`,
209
+ );
210
+ }
211
+
212
+ function extractRecordId(record, index) {
213
+ if (record && typeof record === "object") {
214
+ return (
215
+ record.id ??
216
+ record.ID ??
217
+ record.OBJECT_ID ??
218
+ record.objectId ??
219
+ record.NORAD_CAT_ID ??
220
+ record.noradCatId ??
221
+ `record[${index}]`
222
+ );
223
+ }
224
+ return `record[${index}]`;
225
+ }
226
+
227
+ function extractDeclaredTheory(record, index) {
228
+ const recordId = extractRecordId(record, index);
229
+ const raw =
230
+ record?.declaredTheory ??
231
+ record?.MEAN_ELEMENT_THEORY ??
232
+ record?.meanElementTheory ??
233
+ record?.theory ??
234
+ record?.THEORY;
235
+ return {
236
+ recordId: String(recordId),
237
+ declaredTheory: normalizeDeclaredTheory(raw, String(recordId)),
238
+ };
239
+ }
240
+
241
+ function createReadOnlyTypedArrayView(target, label) {
242
+ return new Proxy(target, {
243
+ get(obj, prop) {
244
+ if (typeof prop === "string" && MUTATING_TYPED_ARRAY_METHODS.has(prop)) {
245
+ return () => {
246
+ throw new TypeError(`Cannot mutate read-only ${label}.`);
247
+ };
248
+ }
249
+ if (prop === "subarray") {
250
+ return (...args) =>
251
+ createReadOnlyTypedArrayView(obj.subarray(...args), label);
252
+ }
253
+ const value = Reflect.get(obj, prop, obj);
254
+ return typeof value === "function" ? value.bind(obj) : value;
255
+ },
256
+ set() {
257
+ throw new TypeError(`Cannot write to read-only ${label}.`);
258
+ },
259
+ defineProperty() {
260
+ throw new TypeError(`Cannot define property on read-only ${label}.`);
261
+ },
262
+ deleteProperty() {
263
+ throw new TypeError(`Cannot delete property on read-only ${label}.`);
264
+ },
265
+ setPrototypeOf() {
266
+ throw new TypeError(`Cannot change prototype of read-only ${label}.`);
267
+ },
268
+ });
269
+ }
270
+
271
+ function adapterSupportsTheory(adapter, theory, fallbackId) {
272
+ if (adapter && typeof adapter.supportsTheory === "function") {
273
+ return Boolean(adapter.supportsTheory(theory));
274
+ }
275
+ if (adapter?.supportedTheories) {
276
+ return adapter.supportedTheories.has(theory);
277
+ }
278
+ const defaults = DEFAULT_THEORY_SUPPORT[fallbackId];
279
+ return defaults ? defaults.includes(theory) : false;
280
+ }
281
+
282
+ export function createPropagatorRegistry(initialAdapters = {}) {
283
+ const adapters = new Map();
284
+
285
+ function registerPropagator(id, adapter) {
286
+ const canonicalId = resolvePropagatorId(id);
287
+ if (!adapter || typeof adapter !== "object") {
288
+ throw new TypeError(
289
+ `Propagator adapter for "${canonicalId}" must be an object.`,
290
+ );
291
+ }
292
+ const rawTheories =
293
+ adapter.supportedTheories ??
294
+ (adapter.strict === true && canonicalId === DEFAULT_PROPAGATOR_ID
295
+ ? ["AP"]
296
+ : DEFAULT_THEORY_SUPPORT[canonicalId]);
297
+ const supportedTheories = rawTheories
298
+ ? new Set(
299
+ Array.from(rawTheories, (theory) =>
300
+ normalizeDeclaredTheory(theory, canonicalId),
301
+ ),
302
+ )
303
+ : null;
304
+
305
+ const normalizedAdapter = {
306
+ ...adapter,
307
+ propagatorId: canonicalId,
308
+ supportedTheories,
309
+ supportsTheory(theory) {
310
+ const normalizedTheory = normalizeDeclaredTheory(theory, canonicalId);
311
+ if (typeof adapter.supportsTheory === "function") {
312
+ return Boolean(adapter.supportsTheory(normalizedTheory));
313
+ }
314
+ return supportedTheories ? supportedTheories.has(normalizedTheory) : false;
315
+ },
316
+ };
317
+ adapters.set(canonicalId, normalizedAdapter);
318
+ return normalizedAdapter;
319
+ }
320
+
321
+ function getPropagator(id = DEFAULT_PROPAGATOR_ID) {
322
+ return adapters.get(resolvePropagatorId(id)) ?? null;
323
+ }
324
+
325
+ function hasPropagator(id = DEFAULT_PROPAGATOR_ID) {
326
+ return adapters.has(resolvePropagatorId(id));
327
+ }
328
+
329
+ function listPropagators() {
330
+ return Array.from(adapters.keys()).sort();
331
+ }
332
+
333
+ function unregisterPropagator(id) {
334
+ return adapters.delete(resolvePropagatorId(id));
335
+ }
336
+
337
+ if (initialAdapters instanceof Map) {
338
+ for (const [id, adapter] of initialAdapters.entries()) {
339
+ registerPropagator(id, adapter);
340
+ }
341
+ } else if (initialAdapters && typeof initialAdapters === "object") {
342
+ for (const [id, adapter] of Object.entries(initialAdapters)) {
343
+ registerPropagator(id, adapter);
344
+ }
345
+ }
346
+
347
+ return {
348
+ defaultPropagatorId: DEFAULT_PROPAGATOR_ID,
349
+ supportedPropagatorIds: SUPPORTED_PROPAGATOR_IDS,
350
+ registerPropagator,
351
+ getPropagator,
352
+ hasPropagator,
353
+ listPropagators,
354
+ unregisterPropagator,
355
+ };
356
+ }
357
+
358
+ export function routeCatalogRecordsByTheory(
359
+ records = [],
360
+ {
361
+ propagatorId = DEFAULT_PROPAGATOR_ID,
362
+ registry = null,
363
+ allowMixedRouting = undefined,
364
+ } = {},
365
+ ) {
366
+ if (!Array.isArray(records)) {
367
+ throw new TypeError("Catalog records must be an array.");
368
+ }
369
+ const canonicalPropagatorId = resolvePropagatorId(propagatorId);
370
+ const mixedEnabled =
371
+ allowMixedRouting === undefined
372
+ ? canonicalPropagatorId === DEFAULT_PROPAGATOR_ID
373
+ : Boolean(allowMixedRouting);
374
+ const selectedAdapter = registry?.getPropagator(canonicalPropagatorId) ?? null;
375
+
376
+ return records.map((record, index) => {
377
+ const { recordId, declaredTheory } = extractDeclaredTheory(record, index);
378
+ const explicitRecordPropagator = record?.propagatorId
379
+ ? resolvePropagatorId(record.propagatorId)
380
+ : null;
381
+
382
+ if (explicitRecordPropagator) {
383
+ const recordAdapter =
384
+ registry?.getPropagator(explicitRecordPropagator) ?? null;
385
+ if (
386
+ !adapterSupportsTheory(
387
+ recordAdapter,
388
+ declaredTheory,
389
+ explicitRecordPropagator,
390
+ )
391
+ ) {
392
+ throw new TheoryMismatchError(
393
+ `Catalog record "${recordId}" declares theory "${declaredTheory}", which is incompatible with assigned propagator "${explicitRecordPropagator}".`,
394
+ {
395
+ recordId,
396
+ declaredTheory,
397
+ propagatorId: explicitRecordPropagator,
398
+ },
399
+ );
400
+ }
401
+ if (!mixedEnabled && explicitRecordPropagator !== canonicalPropagatorId) {
402
+ throw new TheoryMismatchError(
403
+ `Catalog record "${recordId}" requests propagator "${explicitRecordPropagator}" (theory "${declaredTheory}"), which cannot run under strict propagator "${canonicalPropagatorId}".`,
404
+ {
405
+ recordId,
406
+ declaredTheory,
407
+ propagatorId: canonicalPropagatorId,
408
+ },
409
+ );
410
+ }
411
+ return {
412
+ index,
413
+ recordId,
414
+ declaredTheory,
415
+ propagatorId: explicitRecordPropagator,
416
+ record,
417
+ };
418
+ }
419
+
420
+ if (
421
+ adapterSupportsTheory(
422
+ selectedAdapter,
423
+ declaredTheory,
424
+ canonicalPropagatorId,
425
+ )
426
+ ) {
427
+ return {
428
+ index,
429
+ recordId,
430
+ declaredTheory,
431
+ propagatorId: canonicalPropagatorId,
432
+ record,
433
+ };
434
+ }
435
+
436
+ if (!mixedEnabled) {
437
+ throw new TheoryMismatchError(
438
+ `Catalog record "${recordId}" declares theory "${declaredTheory}", which is rejected by propagator "${canonicalPropagatorId}" (every record must fly on the theory it declares).`,
439
+ {
440
+ recordId,
441
+ declaredTheory,
442
+ propagatorId: canonicalPropagatorId,
443
+ },
444
+ );
445
+ }
446
+
447
+ const preferredId = PREFERRED_PROPAGATOR_BY_THEORY[declaredTheory];
448
+ const preferredAdapter = preferredId
449
+ ? registry?.getPropagator(preferredId)
450
+ : null;
451
+ if (
452
+ preferredId &&
453
+ preferredAdapter &&
454
+ adapterSupportsTheory(preferredAdapter, declaredTheory, preferredId)
455
+ ) {
456
+ return {
457
+ index,
458
+ recordId,
459
+ declaredTheory,
460
+ propagatorId: preferredId,
461
+ record,
462
+ };
463
+ }
464
+
465
+ if (registry) {
466
+ for (const candidateId of registry.listPropagators()) {
467
+ const candidate = registry.getPropagator(candidateId);
468
+ if (adapterSupportsTheory(candidate, declaredTheory, candidateId)) {
469
+ return {
470
+ index,
471
+ recordId,
472
+ declaredTheory,
473
+ propagatorId: candidateId,
474
+ record,
475
+ };
476
+ }
477
+ }
478
+ }
479
+
480
+ throw new TheoryMismatchError(
481
+ `Catalog record "${recordId}" declares theory "${declaredTheory}", which has no compatible propagator registered (requested "${canonicalPropagatorId}").`,
482
+ {
483
+ recordId,
484
+ declaredTheory,
485
+ propagatorId: canonicalPropagatorId,
486
+ },
487
+ );
488
+ });
489
+ }
490
+
491
+ export function gridCacheKey({
492
+ propagatorId = DEFAULT_PROPAGATOR_ID,
493
+ catalogRevision,
494
+ windowStart,
495
+ windowEnd,
496
+ stepS,
497
+ frame = "TEME",
498
+ }) {
499
+ const canonicalPropagatorId = resolvePropagatorId(propagatorId);
500
+ const revision = normalizeNonEmptyString(catalogRevision, "catalogRevision");
501
+ const start = normalizeFiniteNumber(windowStart, "windowStart");
502
+ const end = normalizeFiniteNumber(windowEnd, "windowEnd");
503
+ const step = normalizePositiveNumber(stepS, "stepS");
504
+ const normalizedFrame = normalizeNonEmptyString(frame, "frame").toUpperCase();
505
+ return `${canonicalPropagatorId}|${revision}|${start}|${end}|${step}|${normalizedFrame}`;
506
+ }
507
+
508
+ export function encodeScrGridFlatBuffer({
509
+ firstStep = 0,
510
+ stepCount,
511
+ objectCount,
512
+ frame = "TEME",
513
+ stepS = 0,
514
+ statesView,
515
+ bandsView,
516
+ }) {
517
+ const normalizedFirstStep = normalizeNonNegativeInteger(firstStep, "firstStep");
518
+ const normalizedStepCount = normalizePositiveInteger(stepCount, "stepCount");
519
+ const normalizedObjectCount = normalizeNonNegativeInteger(
520
+ objectCount,
521
+ "objectCount",
522
+ );
523
+ const expectedStateFloats =
524
+ normalizedStepCount * normalizedObjectCount * SCR_GRID_STATE_FLOATS;
525
+ const expectedBandFloats = normalizedObjectCount * SCR_RADIUS_BAND_FLOATS;
526
+ if (!(statesView instanceof Float32Array) || statesView.length !== expectedStateFloats) {
527
+ throw new RangeError(
528
+ `statesView must be a Float32Array of length ${expectedStateFloats}.`,
529
+ );
530
+ }
531
+ if (!(bandsView instanceof Float32Array) || bandsView.length !== expectedBandFloats) {
532
+ throw new RangeError(
533
+ `bandsView must be a Float32Array of length ${expectedBandFloats}.`,
534
+ );
535
+ }
536
+
537
+ const builder = new flatbuffers.Builder(
538
+ 256 + statesView.byteLength + bandsView.byteLength,
539
+ );
540
+ const frameOffset = frame ? builder.createString(String(frame)) : 0;
541
+
542
+ let statesOffset = 0;
543
+ const stateCount = normalizedStepCount * normalizedObjectCount;
544
+ if (HOST_IS_LITTLE_ENDIAN) {
545
+ const raw = new Uint8Array(
546
+ statesView.buffer,
547
+ statesView.byteOffset,
548
+ statesView.byteLength,
549
+ );
550
+ SCRGrid.startStatesVector(builder, stateCount);
551
+ if (raw.byteLength > 0) {
552
+ builder.prep(4, raw.byteLength);
553
+ builder.space -= raw.byteLength;
554
+ builder.bb.bytes().set(raw, builder.space);
555
+ }
556
+ statesOffset = builder.endVector();
557
+ } else {
558
+ SCRGrid.startStatesVector(builder, stateCount);
559
+ for (let i = stateCount - 1; i >= 0; i -= 1) {
560
+ const base = i * SCR_GRID_STATE_FLOATS;
561
+ builder.prep(4, SCR_GRID_STATE_BYTES);
562
+ builder.writeFloat32(statesView[base + 7]);
563
+ builder.writeFloat32(statesView[base + 6]);
564
+ builder.writeFloat32(statesView[base + 5]);
565
+ builder.writeFloat32(statesView[base + 4]);
566
+ builder.writeFloat32(statesView[base + 3]);
567
+ builder.writeFloat32(statesView[base + 2]);
568
+ builder.writeFloat32(statesView[base + 1]);
569
+ builder.writeFloat32(statesView[base]);
570
+ }
571
+ statesOffset = builder.endVector();
572
+ }
573
+
574
+ let bandsOffset = 0;
575
+ if (HOST_IS_LITTLE_ENDIAN) {
576
+ const raw = new Uint8Array(
577
+ bandsView.buffer,
578
+ bandsView.byteOffset,
579
+ bandsView.byteLength,
580
+ );
581
+ SCRGrid.startBandsVector(builder, normalizedObjectCount);
582
+ if (raw.byteLength > 0) {
583
+ builder.prep(4, raw.byteLength);
584
+ builder.space -= raw.byteLength;
585
+ builder.bb.bytes().set(raw, builder.space);
586
+ }
587
+ bandsOffset = builder.endVector();
588
+ } else {
589
+ SCRGrid.startBandsVector(builder, normalizedObjectCount);
590
+ for (let i = normalizedObjectCount - 1; i >= 0; i -= 1) {
591
+ const base = i * SCR_RADIUS_BAND_FLOATS;
592
+ builder.prep(4, SCR_RADIUS_BAND_BYTES);
593
+ builder.writeFloat32(bandsView[base + 1]);
594
+ builder.writeFloat32(bandsView[base]);
595
+ }
596
+ bandsOffset = builder.endVector();
597
+ }
598
+
599
+ const gridOffset = SCRGrid.createSCRGrid(
600
+ builder,
601
+ normalizedFirstStep,
602
+ normalizedStepCount,
603
+ normalizedObjectCount,
604
+ frameOffset,
605
+ Number(stepS),
606
+ statesOffset,
607
+ bandsOffset,
608
+ );
609
+ SCR.startSCR(builder);
610
+ SCR.addGrid(builder, gridOffset);
611
+ const scrOffset = SCR.endSCR(builder);
612
+ SCR.finishSCRBuffer(builder, scrOffset);
613
+ return builder.asUint8Array().slice();
614
+ }
615
+
616
+ export function decodeScrGridFlatBuffer(bytes) {
617
+ const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
618
+ const bb = new flatbuffers.ByteBuffer(u8);
619
+ if (!SCR.bufferHasIdentifier(bb)) {
620
+ throw new Error("Expected a $SCR FlatBuffer payload.");
621
+ }
622
+ const scr = SCR.getRootAsSCR(bb);
623
+ const grid = scr.GRID();
624
+ if (!grid) {
625
+ throw new Error("Expected a $SCR GRID table.");
626
+ }
627
+ const firstStep = grid.FIRST_STEP();
628
+ const stepCount = grid.STEP_COUNT();
629
+ const objectCount = grid.OBJECTS();
630
+ const frame = grid.FRAME() ?? "TEME";
631
+ const stepS = grid.STEP_S();
632
+ const statesLen = grid.statesLength();
633
+ const bandsLen = grid.bandsLength();
634
+ const statesView = new Float32Array(statesLen * SCR_GRID_STATE_FLOATS);
635
+ for (let i = 0; i < statesLen; i += 1) {
636
+ const row = grid.STATES(i);
637
+ const base = i * SCR_GRID_STATE_FLOATS;
638
+ statesView[base] = row.X_KM();
639
+ statesView[base + 1] = row.Y_KM();
640
+ statesView[base + 2] = row.Z_KM();
641
+ statesView[base + 3] = row.DEVIATION_KM();
642
+ statesView[base + 4] = row.VX_KM_S();
643
+ statesView[base + 5] = row.VY_KM_S();
644
+ statesView[base + 6] = row.VZ_KM_S();
645
+ statesView[base + 7] = row.RESERVED();
646
+ }
647
+ const bandsView = new Float32Array(bandsLen * SCR_RADIUS_BAND_FLOATS);
648
+ for (let i = 0; i < bandsLen; i += 1) {
649
+ const band = grid.BANDS(i);
650
+ const base = i * SCR_RADIUS_BAND_FLOATS;
651
+ bandsView[base] = band.LOW_KM();
652
+ bandsView[base + 1] = band.HIGH_KM();
653
+ }
654
+ return {
655
+ firstStep,
656
+ stepCount,
657
+ objectCount,
658
+ frame,
659
+ stepS,
660
+ statesView,
661
+ bandsView,
662
+ };
663
+ }
664
+
665
+ function markExcludedObjectRows(statesView, bandsView, stepCount, objectCount, index) {
666
+ for (let step = 0; step < stepCount; step += 1) {
667
+ const offset = (step * objectCount + index) * SCR_GRID_STATE_FLOATS;
668
+ for (let k = 0; k < SCR_GRID_STATE_FLOATS; k += 1) {
669
+ statesView[offset + k] = Number.NaN;
670
+ }
671
+ }
672
+ const bandOffset = index * SCR_RADIUS_BAND_FLOATS;
673
+ bandsView[bandOffset] = Number.NaN;
674
+ bandsView[bandOffset + 1] = Number.NaN;
675
+ }
676
+
677
+ export function createSharedEphemerisGridManager({
678
+ regions = createRuntimeRegionStore(),
679
+ propagators = createPropagatorRegistry(),
680
+ } = {}) {
681
+ const entriesByRegionId = new Map();
682
+ const cacheByKey = new Map();
683
+
684
+ function syncEntryWithRegion(entry) {
685
+ if (!entry) {
686
+ return null;
687
+ }
688
+ const regionDesc = regions.describeRegion(entry.regionId);
689
+ const arena =
690
+ regionDesc && !regionDesc.invalidated
691
+ ? regions.getRegionArena(entry.regionId)
692
+ : null;
693
+ if (!regionDesc || regionDesc.invalidated || !arena) {
694
+ if (!entry.invalidated) {
695
+ entry.invalidated = true;
696
+ cacheByKey.delete(entry.cacheKey);
697
+ }
698
+ if (regionDesc && typeof regionDesc.generation === "number") {
699
+ entry.generation = Math.max(entry.generation, regionDesc.generation);
700
+ }
701
+ return regionDesc;
702
+ }
703
+ if (
704
+ typeof regionDesc.generation === "number" &&
705
+ regionDesc.generation > entry.generation
706
+ ) {
707
+ entry.generation = regionDesc.generation;
708
+ }
709
+ return regionDesc;
710
+ }
711
+
712
+ function buildDescriptor(entry, { roleMask } = {}) {
713
+ return Object.freeze({
714
+ regionId: entry.regionId,
715
+ roleMask:
716
+ roleMask === undefined ? entry.roleMask : normalizeRoleMask(roleMask),
717
+ propagatorId: entry.propagatorId,
718
+ catalogRevision: entry.catalogRevision,
719
+ windowStart: entry.windowStart,
720
+ windowEnd: entry.windowEnd,
721
+ stepS: entry.stepS,
722
+ frame: entry.frame,
723
+ firstStep: entry.firstStep,
724
+ stepCount: entry.stepCount,
725
+ objectCount: entry.objectCount,
726
+ generation: entry.generation,
727
+ });
728
+ }
729
+
730
+ function runPropagation({
731
+ canonicalPropagatorId,
732
+ routedRecords,
733
+ records,
734
+ populateFn,
735
+ statesView,
736
+ bandsView,
737
+ firstStep,
738
+ stepCount,
739
+ objectCount,
740
+ windowStart,
741
+ windowEnd,
742
+ stepS,
743
+ frame,
744
+ }) {
745
+ if (typeof populateFn === "function") {
746
+ return populateFn({
747
+ records,
748
+ routedRecords,
749
+ statesView,
750
+ bandsView,
751
+ firstStep,
752
+ stepCount,
753
+ objectCount,
754
+ windowStart,
755
+ windowEnd,
756
+ stepS,
757
+ frame,
758
+ propagatorId: canonicalPropagatorId,
759
+ });
760
+ }
761
+
762
+ const excluded = [];
763
+ const byPropagator = new Map();
764
+ for (const routed of routedRecords) {
765
+ let group = byPropagator.get(routed.propagatorId);
766
+ if (!group) {
767
+ group = [];
768
+ byPropagator.set(routed.propagatorId, group);
769
+ }
770
+ group.push(routed);
771
+ }
772
+
773
+ if (routedRecords.length === 0) {
774
+ const primaryAdapter = propagators.getPropagator(canonicalPropagatorId);
775
+ if (!primaryAdapter) {
776
+ throw new Error(
777
+ `Propagator "${canonicalPropagatorId}" is not registered on this runtime host.`,
778
+ );
779
+ }
780
+ if (typeof primaryAdapter.propagateGrid === "function") {
781
+ return primaryAdapter.propagateGrid({
782
+ records,
783
+ routedRecords,
784
+ statesView,
785
+ bandsView,
786
+ firstStep,
787
+ stepCount,
788
+ objectCount,
789
+ windowStart,
790
+ windowEnd,
791
+ stepS,
792
+ frame,
793
+ propagatorId: canonicalPropagatorId,
794
+ });
795
+ }
796
+ return { excludedIndices: [] };
797
+ }
798
+
799
+ for (const [targetId, group] of byPropagator.entries()) {
800
+ const adapter = propagators.getPropagator(targetId);
801
+ if (!adapter) {
802
+ throw new Error(
803
+ `Propagator "${targetId}" is not registered on this runtime host.`,
804
+ );
805
+ }
806
+ if (
807
+ byPropagator.size === 1 &&
808
+ typeof adapter.propagateGrid === "function" &&
809
+ group.length === objectCount
810
+ ) {
811
+ const res = adapter.propagateGrid({
812
+ records,
813
+ routedRecords: group,
814
+ statesView,
815
+ bandsView,
816
+ firstStep,
817
+ stepCount,
818
+ objectCount,
819
+ windowStart,
820
+ windowEnd,
821
+ stepS,
822
+ frame,
823
+ propagatorId: targetId,
824
+ });
825
+ if (Array.isArray(res?.excludedIndices)) {
826
+ excluded.push(...res.excludedIndices);
827
+ }
828
+ continue;
829
+ }
830
+
831
+ if (typeof adapter.propagateRecord === "function") {
832
+ for (const routed of group) {
833
+ const res = adapter.propagateRecord({
834
+ record: routed.record,
835
+ objectIndex: routed.index,
836
+ declaredTheory: routed.declaredTheory,
837
+ propagatorId: targetId,
838
+ statesView,
839
+ bandsView,
840
+ firstStep,
841
+ stepCount,
842
+ objectCount,
843
+ windowStart,
844
+ windowEnd,
845
+ stepS,
846
+ frame,
847
+ });
848
+ if (res?.excluded === true) {
849
+ excluded.push(routed.index);
850
+ }
851
+ }
852
+ continue;
853
+ }
854
+
855
+ if (typeof adapter.propagateGrid === "function") {
856
+ const res = adapter.propagateGrid({
857
+ records: group.map((item) => item.record),
858
+ routedRecords: group,
859
+ statesView,
860
+ bandsView,
861
+ firstStep,
862
+ stepCount,
863
+ objectCount,
864
+ windowStart,
865
+ windowEnd,
866
+ stepS,
867
+ frame,
868
+ propagatorId: targetId,
869
+ });
870
+ if (Array.isArray(res?.excludedIndices)) {
871
+ excluded.push(...res.excludedIndices);
872
+ }
873
+ continue;
874
+ }
875
+
876
+ throw new Error(
877
+ `Propagator "${targetId}" must implement propagateGrid() or propagateRecord().`,
878
+ );
879
+ }
880
+
881
+ return { excludedIndices: excluded };
882
+ }
883
+
884
+ function populateGrid(spec = {}) {
885
+ const canonicalPropagatorId = resolvePropagatorId(
886
+ spec.propagatorId ?? DEFAULT_PROPAGATOR_ID,
887
+ );
888
+ const catalogRevision = normalizeNonEmptyString(
889
+ spec.catalogRevision,
890
+ "catalogRevision",
891
+ );
892
+ const windowStart = normalizeFiniteNumber(spec.windowStart, "windowStart");
893
+ const windowEnd = normalizeFiniteNumber(spec.windowEnd, "windowEnd");
894
+ if (windowEnd <= windowStart) {
895
+ throw new RangeError(
896
+ `windowEnd (${windowEnd}) must be greater than windowStart (${windowStart}).`,
897
+ );
898
+ }
899
+ const stepS = normalizePositiveNumber(spec.stepS, "stepS");
900
+ const frame = normalizeNonEmptyString(spec.frame ?? "TEME", "frame");
901
+ const firstStep = normalizeNonNegativeInteger(
902
+ spec.firstStep ?? 0,
903
+ "firstStep",
904
+ );
905
+ const computedSteps = Math.max(
906
+ 1,
907
+ Math.ceil((windowEnd - windowStart) / stepS) + 1,
908
+ );
909
+ const stepCount =
910
+ spec.stepCount === undefined
911
+ ? computedSteps
912
+ : normalizePositiveInteger(spec.stepCount, "stepCount");
913
+
914
+ const records = Array.isArray(spec.records) ? spec.records : [];
915
+ const objectCount =
916
+ spec.objectCount === undefined
917
+ ? records.length
918
+ : normalizeNonNegativeInteger(spec.objectCount, "objectCount");
919
+ if (records.length > 0 && records.length !== objectCount) {
920
+ throw new RangeError(
921
+ `records.length (${records.length}) must match objectCount (${objectCount}).`,
922
+ );
923
+ }
924
+ const roleMask = normalizeRoleMask(spec.roleMask);
925
+ const roles = normalizeRolesArray(spec.roles, objectCount);
926
+ const shared = spec.shared === undefined ? true : Boolean(spec.shared);
927
+
928
+ const key = gridCacheKey({
929
+ propagatorId: canonicalPropagatorId,
930
+ catalogRevision,
931
+ windowStart,
932
+ windowEnd,
933
+ stepS,
934
+ frame,
935
+ });
936
+
937
+ const cached = cacheByKey.get(key);
938
+ if (cached) {
939
+ syncEntryWithRegion(cached);
940
+ }
941
+ if (cached && !cached.invalidated) {
942
+ if (
943
+ cached.firstStep !== firstStep ||
944
+ cached.stepCount !== stepCount ||
945
+ cached.objectCount !== objectCount
946
+ ) {
947
+ throw new Error(
948
+ `Cached ephemeris grid shape mismatch for ${key}: cached (${cached.firstStep}, ${cached.stepCount}, ${cached.objectCount}) vs requested (${firstStep}, ${stepCount}, ${objectCount}).`,
949
+ );
950
+ }
951
+ return {
952
+ descriptor: buildDescriptor(cached, { roleMask }),
953
+ regionId: cached.regionId,
954
+ cacheHit: true,
955
+ propagationCount: cached.propagationCount,
956
+ propagatedObjectCount: cached.propagatedObjectCount,
957
+ excludedIndices: Array.from(cached.excludedIndices),
958
+ };
959
+ }
960
+
961
+ const allowMixedRouting =
962
+ spec.allowMixedRouting === undefined
963
+ ? spec.propagatorId === undefined ||
964
+ canonicalPropagatorId === DEFAULT_PROPAGATOR_ID
965
+ : Boolean(spec.allowMixedRouting);
966
+ const routedRecords = routeCatalogRecordsByTheory(records, {
967
+ propagatorId: canonicalPropagatorId,
968
+ registry: propagators,
969
+ allowMixedRouting,
970
+ });
971
+
972
+ const statesFloatCount =
973
+ stepCount * objectCount * SCR_GRID_STATE_FLOATS;
974
+ const statesByteLength = stepCount * objectCount * SCR_GRID_STATE_BYTES;
975
+ const bandsFloatCount = objectCount * SCR_RADIUS_BAND_FLOATS;
976
+ const bandsByteLength = objectCount * SCR_RADIUS_BAND_BYTES;
977
+ const totalBytes = statesByteLength + bandsByteLength;
978
+
979
+ const regionDesc = regions.allocateContiguousRegion({
980
+ layoutId: SCR_GRID_LAYOUT_ID,
981
+ recordByteLength: SCR_RADIUS_BAND_BYTES,
982
+ alignment: 8,
983
+ recordCount: totalBytes / SCR_RADIUS_BAND_BYTES,
984
+ shared,
985
+ metadata: {
986
+ propagatorId: canonicalPropagatorId,
987
+ catalogRevision,
988
+ windowStart,
989
+ windowEnd,
990
+ stepS,
991
+ frame,
992
+ firstStep,
993
+ stepCount,
994
+ objectCount,
995
+ },
996
+ });
997
+ const arena = regions.getRegionArena(regionDesc.regionId);
998
+ const statesView = new Float32Array(
999
+ arena.buffer,
1000
+ arena.byteOffset,
1001
+ statesFloatCount,
1002
+ );
1003
+ const bandsView = new Float32Array(
1004
+ arena.buffer,
1005
+ arena.byteOffset + statesByteLength,
1006
+ bandsFloatCount,
1007
+ );
1008
+
1009
+ let excludedSet;
1010
+ try {
1011
+ const outcome = runPropagation({
1012
+ canonicalPropagatorId,
1013
+ routedRecords,
1014
+ records,
1015
+ populateFn: spec.populateFn,
1016
+ statesView,
1017
+ bandsView,
1018
+ firstStep,
1019
+ stepCount,
1020
+ objectCount,
1021
+ windowStart,
1022
+ windowEnd,
1023
+ stepS,
1024
+ frame,
1025
+ });
1026
+
1027
+ excludedSet = new Set(
1028
+ Array.isArray(outcome?.excludedIndices)
1029
+ ? outcome.excludedIndices.map((idx) =>
1030
+ normalizeNonNegativeInteger(idx, "excludedIndex"),
1031
+ )
1032
+ : [],
1033
+ );
1034
+ for (const idx of excludedSet) {
1035
+ if (idx >= objectCount) {
1036
+ throw new RangeError(
1037
+ `excludedIndex ${idx} out of bounds for objectCount ${objectCount}.`,
1038
+ );
1039
+ }
1040
+ markExcludedObjectRows(
1041
+ statesView,
1042
+ bandsView,
1043
+ stepCount,
1044
+ objectCount,
1045
+ idx,
1046
+ );
1047
+ }
1048
+ } catch (error) {
1049
+ regions.invalidateRegion(regionDesc.regionId);
1050
+ throw error;
1051
+ }
1052
+
1053
+ const entry = {
1054
+ regionId: regionDesc.regionId,
1055
+ cacheKey: key,
1056
+ roleMask,
1057
+ roles,
1058
+ propagatorId: canonicalPropagatorId,
1059
+ catalogRevision,
1060
+ windowStart,
1061
+ windowEnd,
1062
+ stepS,
1063
+ frame,
1064
+ firstStep,
1065
+ stepCount,
1066
+ objectCount,
1067
+ generation: regionDesc.generation,
1068
+ shared: regionDesc.shared,
1069
+ statesByteLength,
1070
+ bandsByteLength,
1071
+ statesFloatCount,
1072
+ bandsFloatCount,
1073
+ propagationCount: 1,
1074
+ propagatedObjectCount: objectCount,
1075
+ spliceCount: 0,
1076
+ excludedIndices: excludedSet,
1077
+ invalidated: false,
1078
+ };
1079
+ entriesByRegionId.set(entry.regionId, entry);
1080
+ cacheByKey.set(key, entry);
1081
+
1082
+ return {
1083
+ descriptor: buildDescriptor(entry),
1084
+ regionId: entry.regionId,
1085
+ cacheHit: false,
1086
+ propagationCount: entry.propagationCount,
1087
+ propagatedObjectCount: entry.propagatedObjectCount,
1088
+ excludedIndices: Array.from(excludedSet),
1089
+ };
1090
+ }
1091
+
1092
+ function getGrid(regionId) {
1093
+ const normalizedRegionId = normalizePositiveInteger(regionId, "regionId");
1094
+ const entry = entriesByRegionId.get(normalizedRegionId);
1095
+ if (!entry) {
1096
+ return null;
1097
+ }
1098
+ const regionDesc = syncEntryWithRegion(entry);
1099
+ return {
1100
+ descriptor: buildDescriptor(entry),
1101
+ regionId: entry.regionId,
1102
+ shared: entry.shared,
1103
+ generation: entry.generation,
1104
+ byteLength: entry.statesByteLength + entry.bandsByteLength,
1105
+ statesByteLength: entry.statesByteLength,
1106
+ bandsByteLength: entry.bandsByteLength,
1107
+ propagationCount: entry.propagationCount,
1108
+ propagatedObjectCount: entry.propagatedObjectCount,
1109
+ spliceCount: entry.spliceCount,
1110
+ activeConsumers: regionDesc?.activeConsumers ?? 0,
1111
+ invalidated: entry.invalidated,
1112
+ excludedIndices: Array.from(entry.excludedIndices),
1113
+ };
1114
+ }
1115
+
1116
+ function attachGridModule(
1117
+ regionId,
1118
+ {
1119
+ moduleId,
1120
+ roleMask = undefined,
1121
+ roles = null,
1122
+ mode = "read-only",
1123
+ } = {},
1124
+ ) {
1125
+ const normalizedRegionId = normalizePositiveInteger(regionId, "regionId");
1126
+ const normalizedModuleId = normalizeNonEmptyString(moduleId, "moduleId");
1127
+ if (mode !== "read-only") {
1128
+ throw new Error(
1129
+ `Shared ephemeris grid attach for module "${normalizedModuleId}" must use mode "read-only" (got "${String(mode)}").`,
1130
+ );
1131
+ }
1132
+ const entry = entriesByRegionId.get(normalizedRegionId);
1133
+ if (!entry) {
1134
+ throw new Error(`Unknown ephemeris grid region ${normalizedRegionId}.`);
1135
+ }
1136
+ syncEntryWithRegion(entry);
1137
+ if (entry.invalidated) {
1138
+ throw new StaleGridLeaseError(
1139
+ `Ephemeris grid region ${normalizedRegionId} has been invalidated.`,
1140
+ {
1141
+ regionId: normalizedRegionId,
1142
+ moduleId: normalizedModuleId,
1143
+ currentGeneration: entry.generation,
1144
+ },
1145
+ );
1146
+ }
1147
+
1148
+ const effectiveRoleMask =
1149
+ roleMask === undefined ? entry.roleMask : normalizeRoleMask(roleMask);
1150
+ const effectiveRoles =
1151
+ roles === null || roles === undefined
1152
+ ? entry.roles
1153
+ : normalizeRolesArray(roles, entry.objectCount);
1154
+
1155
+ const regionLease = regions.attachRegionConsumer(normalizedRegionId, {
1156
+ consumerId: normalizedModuleId,
1157
+ mode: "read-only",
1158
+ roleMask: effectiveRoleMask,
1159
+ });
1160
+ const attachedGeneration = entry.generation;
1161
+ const descriptor = buildDescriptor(entry, { roleMask: effectiveRoleMask });
1162
+ let detached = false;
1163
+
1164
+ function assertCurrent() {
1165
+ if (detached) {
1166
+ throw new StaleGridLeaseError(
1167
+ `Ephemeris grid lease for module "${normalizedModuleId}" on region ${normalizedRegionId} is detached.`,
1168
+ {
1169
+ regionId: normalizedRegionId,
1170
+ moduleId: normalizedModuleId,
1171
+ attachedGeneration,
1172
+ currentGeneration: entry.generation,
1173
+ },
1174
+ );
1175
+ }
1176
+ syncEntryWithRegion(entry);
1177
+ if (entry.invalidated) {
1178
+ throw new StaleGridLeaseError(
1179
+ `Ephemeris grid region ${normalizedRegionId} was invalidated; lease for module "${normalizedModuleId}" is stale.`,
1180
+ {
1181
+ regionId: normalizedRegionId,
1182
+ moduleId: normalizedModuleId,
1183
+ attachedGeneration,
1184
+ currentGeneration: entry.generation,
1185
+ },
1186
+ );
1187
+ }
1188
+ if (entry.generation !== attachedGeneration) {
1189
+ throw new StaleGridLeaseError(
1190
+ `Ephemeris grid lease for module "${normalizedModuleId}" on region ${normalizedRegionId} is stale: attached at generation ${attachedGeneration}, current generation is ${entry.generation}.`,
1191
+ {
1192
+ regionId: normalizedRegionId,
1193
+ moduleId: normalizedModuleId,
1194
+ attachedGeneration,
1195
+ currentGeneration: entry.generation,
1196
+ },
1197
+ );
1198
+ }
1199
+ regionLease.assertCurrent();
1200
+ return true;
1201
+ }
1202
+
1203
+ function isCurrent() {
1204
+ syncEntryWithRegion(entry);
1205
+ return (
1206
+ !detached &&
1207
+ !entry.invalidated &&
1208
+ entry.generation === attachedGeneration &&
1209
+ regionLease.isCurrent()
1210
+ );
1211
+ }
1212
+
1213
+ function getRawArena() {
1214
+ assertCurrent();
1215
+ const arena = regions.getRegionArena(normalizedRegionId);
1216
+ if (!arena) {
1217
+ throw new StaleGridLeaseError(
1218
+ `Arena for ephemeris grid region ${normalizedRegionId} is unavailable.`,
1219
+ {
1220
+ regionId: normalizedRegionId,
1221
+ moduleId: normalizedModuleId,
1222
+ attachedGeneration,
1223
+ currentGeneration: entry.generation,
1224
+ },
1225
+ );
1226
+ }
1227
+ return arena;
1228
+ }
1229
+
1230
+ function getStatesView() {
1231
+ const arena = getRawArena();
1232
+ const rawStates = new Float32Array(
1233
+ arena.buffer,
1234
+ arena.byteOffset,
1235
+ entry.statesFloatCount,
1236
+ );
1237
+ return createReadOnlyTypedArrayView(
1238
+ rawStates,
1239
+ `SCR states view (region ${normalizedRegionId}, module ${normalizedModuleId})`,
1240
+ );
1241
+ }
1242
+
1243
+ function getBandsView() {
1244
+ const arena = getRawArena();
1245
+ const rawBands = new Float32Array(
1246
+ arena.buffer,
1247
+ arena.byteOffset + entry.statesByteLength,
1248
+ entry.bandsFloatCount,
1249
+ );
1250
+ return createReadOnlyTypedArrayView(
1251
+ rawBands,
1252
+ `SCR bands view (region ${normalizedRegionId}, module ${normalizedModuleId})`,
1253
+ );
1254
+ }
1255
+
1256
+ function getRolesView() {
1257
+ assertCurrent();
1258
+ const source =
1259
+ effectiveRoles ??
1260
+ new Uint8Array(entry.objectCount).fill(SCR_ROLE.PRIMARY);
1261
+ return createReadOnlyTypedArrayView(
1262
+ new Uint8Array(source),
1263
+ `SCR roles view (region ${normalizedRegionId}, module ${normalizedModuleId})`,
1264
+ );
1265
+ }
1266
+
1267
+ function encodeAlignedExternalFrame({
1268
+ portId = "grid",
1269
+ typeRef = undefined,
1270
+ } = {}) {
1271
+ const arena = getRawArena();
1272
+ return Object.freeze({
1273
+ portId: normalizeNonEmptyString(portId, "portId"),
1274
+ offset: 0,
1275
+ size: arena.byteLength,
1276
+ alignment: arena.alignment,
1277
+ ownership: BufferOwnership.SHARED,
1278
+ mutability: BufferMutability.IMMUTABLE,
1279
+ arenaGeneration: attachedGeneration,
1280
+ generation: attachedGeneration,
1281
+ shared: arena.shared,
1282
+ regionId: normalizedRegionId,
1283
+ typeRef: typeRef ?? {
1284
+ schemaName: "SCR.fbs",
1285
+ fileIdentifier: "$SCR",
1286
+ rootTypeName: "SCR",
1287
+ wireFormat: "aligned-binary",
1288
+ byteLength: arena.byteLength,
1289
+ requiredAlignment: arena.alignment,
1290
+ },
1291
+ });
1292
+ }
1293
+
1294
+ function encodeScrGridFrame() {
1295
+ const arena = getRawArena();
1296
+ const rawStates = new Float32Array(
1297
+ arena.buffer,
1298
+ arena.byteOffset,
1299
+ entry.statesFloatCount,
1300
+ );
1301
+ const rawBands = new Float32Array(
1302
+ arena.buffer,
1303
+ arena.byteOffset + entry.statesByteLength,
1304
+ entry.bandsFloatCount,
1305
+ );
1306
+ return encodeScrGridFlatBuffer({
1307
+ firstStep: entry.firstStep,
1308
+ stepCount: entry.stepCount,
1309
+ objectCount: entry.objectCount,
1310
+ frame: entry.frame,
1311
+ stepS: entry.stepS,
1312
+ statesView: rawStates,
1313
+ bandsView: rawBands,
1314
+ });
1315
+ }
1316
+
1317
+ function detach() {
1318
+ if (detached) {
1319
+ return false;
1320
+ }
1321
+ detached = true;
1322
+ return regionLease.detach();
1323
+ }
1324
+
1325
+ return Object.freeze({
1326
+ leaseId: regionLease.leaseId,
1327
+ regionId: normalizedRegionId,
1328
+ moduleId: normalizedModuleId,
1329
+ mode: "read-only",
1330
+ shared: entry.shared,
1331
+ generation: attachedGeneration,
1332
+ descriptor,
1333
+ get arenaBytes() {
1334
+ const arena = getRawArena();
1335
+ return createReadOnlyTypedArrayView(
1336
+ arena.bytes,
1337
+ `SCR arenaBytes (region ${normalizedRegionId}, module ${normalizedModuleId})`,
1338
+ );
1339
+ },
1340
+ getStatesView,
1341
+ getBandsView,
1342
+ getRolesView,
1343
+ encodeAlignedExternalFrame,
1344
+ encodeScrGridFrame,
1345
+ isCurrent,
1346
+ assertCurrent,
1347
+ detach,
1348
+ });
1349
+ }
1350
+
1351
+ function spliceGridObjects({
1352
+ regionId,
1353
+ newCatalogRevision,
1354
+ updatedIndices = [],
1355
+ records = [],
1356
+ populateFn = null,
1357
+ excludedIndices = [],
1358
+ allowMixedRouting = undefined,
1359
+ }) {
1360
+ const normalizedRegionId = normalizePositiveInteger(regionId, "regionId");
1361
+ const entry = entriesByRegionId.get(normalizedRegionId);
1362
+ if (!entry) {
1363
+ throw new Error(`Unknown ephemeris grid region ${normalizedRegionId}.`);
1364
+ }
1365
+ syncEntryWithRegion(entry);
1366
+ if (entry.invalidated) {
1367
+ throw new Error(
1368
+ `Cannot splice invalidated ephemeris grid region ${normalizedRegionId}.`,
1369
+ );
1370
+ }
1371
+ const nextRevision = normalizeNonEmptyString(
1372
+ newCatalogRevision,
1373
+ "newCatalogRevision",
1374
+ );
1375
+ const nextCacheKey = gridCacheKey({
1376
+ propagatorId: entry.propagatorId,
1377
+ catalogRevision: nextRevision,
1378
+ windowStart: entry.windowStart,
1379
+ windowEnd: entry.windowEnd,
1380
+ stepS: entry.stepS,
1381
+ frame: entry.frame,
1382
+ });
1383
+ const colliding = cacheByKey.get(nextCacheKey);
1384
+ if (colliding) {
1385
+ syncEntryWithRegion(colliding);
1386
+ }
1387
+ if (
1388
+ colliding &&
1389
+ !colliding.invalidated &&
1390
+ colliding.regionId !== entry.regionId
1391
+ ) {
1392
+ throw new Error(
1393
+ `Cannot splice ephemeris grid region ${normalizedRegionId} to catalogRevision "${nextRevision}": cache key "${nextCacheKey}" is already active on region ${colliding.regionId}.`,
1394
+ );
1395
+ }
1396
+ if (!Array.isArray(updatedIndices)) {
1397
+ throw new TypeError("updatedIndices must be an array.");
1398
+ }
1399
+ if (!Array.isArray(records)) {
1400
+ throw new TypeError("Catalog records must be an array.");
1401
+ }
1402
+ if (!Array.isArray(excludedIndices)) {
1403
+ throw new TypeError("excludedIndices must be an array.");
1404
+ }
1405
+ const indices = updatedIndices.map((idx) => {
1406
+ const n = normalizeNonNegativeInteger(idx, "updatedIndex");
1407
+ if (n >= entry.objectCount) {
1408
+ throw new RangeError(
1409
+ `updatedIndex ${n} out of bounds for objectCount ${entry.objectCount}.`,
1410
+ );
1411
+ }
1412
+ return n;
1413
+ });
1414
+ const explicitExcludedIndices = excludedIndices.map((idx) => {
1415
+ const n = normalizeNonNegativeInteger(idx, "excludedIndex");
1416
+ if (n >= entry.objectCount) {
1417
+ throw new RangeError(
1418
+ `excludedIndex ${n} out of bounds for objectCount ${entry.objectCount}.`,
1419
+ );
1420
+ }
1421
+ return n;
1422
+ });
1423
+
1424
+ if (records.length > 0 && records.length !== indices.length) {
1425
+ throw new RangeError(
1426
+ `spliceGridObjects records.length (${records.length}) must match updatedIndices.length (${indices.length}).`,
1427
+ );
1428
+ }
1429
+ if (
1430
+ typeof populateFn !== "function" &&
1431
+ indices.length > 0 &&
1432
+ records.length === 0
1433
+ ) {
1434
+ throw new RangeError(
1435
+ `spliceGridObjects requires records (length ${indices.length}) or populateFn when updatedIndices is non-empty.`,
1436
+ );
1437
+ }
1438
+
1439
+ const mixedEnabled =
1440
+ allowMixedRouting === undefined
1441
+ ? entry.propagatorId === DEFAULT_PROPAGATOR_ID
1442
+ : Boolean(allowMixedRouting);
1443
+ const routedUpdates = routeCatalogRecordsByTheory(records, {
1444
+ propagatorId: entry.propagatorId,
1445
+ registry: propagators,
1446
+ allowMixedRouting: mixedEnabled,
1447
+ }).map((item, pos) => ({
1448
+ ...item,
1449
+ index: indices[pos],
1450
+ }));
1451
+
1452
+ const arena = regions.getRegionArena(normalizedRegionId);
1453
+ const statesView = new Float32Array(
1454
+ arena.buffer,
1455
+ arena.byteOffset,
1456
+ entry.statesFloatCount,
1457
+ );
1458
+ const bandsView = new Float32Array(
1459
+ arena.buffer,
1460
+ arena.byteOffset + entry.statesByteLength,
1461
+ entry.bandsFloatCount,
1462
+ );
1463
+ const arenaBackup = new Uint8Array(arena.bytes);
1464
+ const nextExcludedIndices = new Set(entry.excludedIndices);
1465
+
1466
+ try {
1467
+ if (typeof populateFn === "function") {
1468
+ for (const idx of indices) {
1469
+ nextExcludedIndices.delete(idx);
1470
+ }
1471
+ const outcome = populateFn({
1472
+ updatedIndices: indices,
1473
+ records,
1474
+ routedRecords: routedUpdates,
1475
+ statesView,
1476
+ bandsView,
1477
+ firstStep: entry.firstStep,
1478
+ stepCount: entry.stepCount,
1479
+ objectCount: entry.objectCount,
1480
+ windowStart: entry.windowStart,
1481
+ windowEnd: entry.windowEnd,
1482
+ stepS: entry.stepS,
1483
+ frame: entry.frame,
1484
+ propagatorId: entry.propagatorId,
1485
+ });
1486
+ if (Array.isArray(outcome?.excludedIndices)) {
1487
+ for (const idx of outcome.excludedIndices) {
1488
+ const n = normalizeNonNegativeInteger(idx, "excludedIndex");
1489
+ if (n >= entry.objectCount) {
1490
+ throw new RangeError(
1491
+ `excludedIndex ${n} out of bounds for objectCount ${entry.objectCount}.`,
1492
+ );
1493
+ }
1494
+ nextExcludedIndices.add(n);
1495
+ }
1496
+ }
1497
+ } else if (indices.length > 0) {
1498
+ for (const routed of routedUpdates) {
1499
+ const adapter = propagators.getPropagator(routed.propagatorId);
1500
+ if (!adapter) {
1501
+ throw new Error(
1502
+ `Propagator "${routed.propagatorId}" is not registered on this runtime host.`,
1503
+ );
1504
+ }
1505
+ if (typeof adapter.propagateRecord === "function") {
1506
+ const res = adapter.propagateRecord({
1507
+ record: routed.record,
1508
+ objectIndex: routed.index,
1509
+ declaredTheory: routed.declaredTheory,
1510
+ propagatorId: routed.propagatorId,
1511
+ statesView,
1512
+ bandsView,
1513
+ firstStep: entry.firstStep,
1514
+ stepCount: entry.stepCount,
1515
+ objectCount: entry.objectCount,
1516
+ windowStart: entry.windowStart,
1517
+ windowEnd: entry.windowEnd,
1518
+ stepS: entry.stepS,
1519
+ frame: entry.frame,
1520
+ });
1521
+ if (res?.excluded === true) {
1522
+ nextExcludedIndices.add(routed.index);
1523
+ } else {
1524
+ nextExcludedIndices.delete(routed.index);
1525
+ }
1526
+ } else if (typeof adapter.propagateGrid === "function") {
1527
+ nextExcludedIndices.delete(routed.index);
1528
+ const res = adapter.propagateGrid({
1529
+ records: [routed.record],
1530
+ routedRecords: [routed],
1531
+ updatedIndices: [routed.index],
1532
+ statesView,
1533
+ bandsView,
1534
+ firstStep: entry.firstStep,
1535
+ stepCount: entry.stepCount,
1536
+ objectCount: entry.objectCount,
1537
+ windowStart: entry.windowStart,
1538
+ windowEnd: entry.windowEnd,
1539
+ stepS: entry.stepS,
1540
+ frame: entry.frame,
1541
+ propagatorId: routed.propagatorId,
1542
+ });
1543
+ if (Array.isArray(res?.excludedIndices)) {
1544
+ for (const idx of res.excludedIndices) {
1545
+ const n = normalizeNonNegativeInteger(idx, "excludedIndex");
1546
+ if (n >= entry.objectCount) {
1547
+ throw new RangeError(
1548
+ `excludedIndex ${n} out of bounds for objectCount ${entry.objectCount}.`,
1549
+ );
1550
+ }
1551
+ nextExcludedIndices.add(n);
1552
+ }
1553
+ }
1554
+ } else {
1555
+ throw new Error(
1556
+ `Propagator "${routed.propagatorId}" must implement propagateRecord() or propagateGrid().`,
1557
+ );
1558
+ }
1559
+ }
1560
+ }
1561
+
1562
+ for (const n of explicitExcludedIndices) {
1563
+ nextExcludedIndices.add(n);
1564
+ }
1565
+ for (const idx of nextExcludedIndices) {
1566
+ markExcludedObjectRows(
1567
+ statesView,
1568
+ bandsView,
1569
+ entry.stepCount,
1570
+ entry.objectCount,
1571
+ idx,
1572
+ );
1573
+ }
1574
+ } catch (error) {
1575
+ arena.bytes.set(arenaBackup);
1576
+ throw error;
1577
+ }
1578
+ entry.excludedIndices = nextExcludedIndices;
1579
+
1580
+ if (entry.cacheKey !== nextCacheKey) {
1581
+ cacheByKey.delete(entry.cacheKey);
1582
+ }
1583
+ entry.catalogRevision = nextRevision;
1584
+ entry.cacheKey = nextCacheKey;
1585
+ cacheByKey.set(entry.cacheKey, entry);
1586
+
1587
+ const nextGeneration = regions.bumpRegionGeneration(normalizedRegionId);
1588
+ entry.generation = nextGeneration ?? entry.generation + 1;
1589
+ entry.spliceCount += 1;
1590
+ entry.propagatedObjectCount += indices.length;
1591
+
1592
+ return {
1593
+ descriptor: buildDescriptor(entry),
1594
+ regionId: entry.regionId,
1595
+ generation: entry.generation,
1596
+ updatedIndices: indices,
1597
+ propagatedObjectCount: indices.length,
1598
+ };
1599
+ }
1600
+
1601
+ function invalidateGrid(filter = {}) {
1602
+ const normalizedFilter =
1603
+ typeof filter === "number" ? { regionId: filter } : filter ?? {};
1604
+ const hasRegionId = normalizedFilter.regionId !== undefined;
1605
+ const hasPropagatorId = normalizedFilter.propagatorId !== undefined;
1606
+ const hasRevision = normalizedFilter.catalogRevision !== undefined;
1607
+ const hasWindowStart = normalizedFilter.windowStart !== undefined;
1608
+ const hasWindowEnd = normalizedFilter.windowEnd !== undefined;
1609
+ const hasStepS = normalizedFilter.stepS !== undefined;
1610
+ const hasFrame = normalizedFilter.frame !== undefined;
1611
+ const matchAll = normalizedFilter.all === true;
1612
+
1613
+ if (
1614
+ !matchAll &&
1615
+ !hasRegionId &&
1616
+ !hasPropagatorId &&
1617
+ !hasRevision &&
1618
+ !hasWindowStart &&
1619
+ !hasWindowEnd &&
1620
+ !hasStepS &&
1621
+ !hasFrame
1622
+ ) {
1623
+ throw new TypeError(
1624
+ "invalidateGrid requires at least one filter criterion or { all: true }.",
1625
+ );
1626
+ }
1627
+
1628
+ const targetPropagatorId = hasPropagatorId
1629
+ ? resolvePropagatorId(normalizedFilter.propagatorId)
1630
+ : null;
1631
+ const targetRevision = hasRevision
1632
+ ? normalizeNonEmptyString(
1633
+ normalizedFilter.catalogRevision,
1634
+ "catalogRevision",
1635
+ )
1636
+ : null;
1637
+ const targetFrame = hasFrame
1638
+ ? normalizeNonEmptyString(normalizedFilter.frame, "frame").toUpperCase()
1639
+ : null;
1640
+
1641
+ const invalidatedRegionIds = [];
1642
+ for (const entry of entriesByRegionId.values()) {
1643
+ syncEntryWithRegion(entry);
1644
+ if (entry.invalidated) continue;
1645
+ if (!matchAll) {
1646
+ if (hasRegionId && entry.regionId !== Number(normalizedFilter.regionId)) {
1647
+ continue;
1648
+ }
1649
+ if (hasPropagatorId && entry.propagatorId !== targetPropagatorId) {
1650
+ continue;
1651
+ }
1652
+ if (hasRevision && entry.catalogRevision !== targetRevision) {
1653
+ continue;
1654
+ }
1655
+ if (hasWindowStart && entry.windowStart !== Number(normalizedFilter.windowStart)) {
1656
+ continue;
1657
+ }
1658
+ if (hasWindowEnd && entry.windowEnd !== Number(normalizedFilter.windowEnd)) {
1659
+ continue;
1660
+ }
1661
+ if (hasStepS && entry.stepS !== Number(normalizedFilter.stepS)) {
1662
+ continue;
1663
+ }
1664
+ if (hasFrame && entry.frame.toUpperCase() !== targetFrame) {
1665
+ continue;
1666
+ }
1667
+ }
1668
+ entry.invalidated = true;
1669
+ entry.generation += 1;
1670
+ cacheByKey.delete(entry.cacheKey);
1671
+ regions.invalidateRegion(entry.regionId);
1672
+ invalidatedRegionIds.push(entry.regionId);
1673
+ }
1674
+
1675
+ return {
1676
+ invalidatedRegionIds,
1677
+ count: invalidatedRegionIds.length,
1678
+ };
1679
+ }
1680
+
1681
+ return {
1682
+ populateGrid,
1683
+ getGrid,
1684
+ attachGridModule,
1685
+ spliceGridObjects,
1686
+ invalidateGrid,
1687
+ };
1688
+ }