Run the Navara paths without the Cesium SDK, and load it on demand for the features that still build on it

Every Cesium read that a Navara page made was surveyed with the strict acceptance (GEV_QA_CESIUM_TRAP=record). Math on those paths now uses src/geo: screen annotations, weather and wind center readings, cyclone picks, scene data pack polygons and images (new navaraGeometry.js), the awareness subject, the orbit offset of camera verbs, voice frame_overhead, the agent world packet and Directions colours and ground picks. The celestial ring's Sun and Moon come from a bit-identical port of Cesium's Simon1994 model, JulianDate and TEME rotation (src/geo/simon1994.js, julianDate.js, transforms.js); a Cesium globe still applies its ICRF rotation once loaded.

Traffic, Street Level, the Nepal event and locator and geo import build on Cesium's math or entity model on either globe; their enable (or the import) now loads the SDK first through src/app/loadCesium.js, synchronously when it is already there. A production page guards the global so a missed read is reported and starts the load. No module reads Cesium while it loads (scripts/check-cesium-load-time.mjs, run by npm test). Cesium.js is still loaded by index.html here.
This commit is contained in:
German Khokhlov committed 2026-11-04 17:15:21 +04:00
1 parent f87da8523e
commit b8305de14b
58 files changed
+2130 -325

No files matched your search

+134
View File
@@ -0,0 +1,134 @@
// The production build externalizes Cesium: every `cesium` import reads the
// global that /cesium/Cesium.js defines, and the page loads that script only
// when something needs it. The dev server and Node import Cesium's ES module
// package instead, so there the SDK is always there and only the widget
// styles load. A Navara page that never needs Cesium never loads either.
//
// - `viewer()`: a Cesium globe is about to start: the SDK and the widget
// styles;
// - `sdk()`: a feature that still builds on Cesium's entity model (the Nepal
// event and locator, imported KML) is used on Navara: the SDK alone.
export function createCesiumLoader({
document = globalThis.document,
globals = globalThis,
base = `${import.meta.env?.BASE_URL ?? '/'}cesium/`,
script = import.meta.env?.PROD === true,
} = {}) {
let sdkPending = null;
let stylesPending = null;
const root = () => {
globals.CESIUM_BASE_URL ??= base;
return globals.CESIUM_BASE_URL.replace(/\/?$/, '/');
};
// A failed load leaves no element behind and can be retried.
const load = (tag, url) => {
const element = document.createElement(tag);
if (tag === 'script') element.src = url;
else {
element.rel = 'stylesheet';
element.href = url;
}
return new Promise((resolve, reject) => {
element.onload = () => {
element.onload = element.onerror = null;
resolve();
};
element.onerror = () => {
element.onload = element.onerror = null;
element.remove();
reject(new Error(`Could not load ${url}`));
};
document.head.append(element);
});
};
// Read without running a getter: a page may define the global as one.
const ready = () =>
!script ||
Object.getOwnPropertyDescriptor(globals, 'Cesium')?.value != null;
const sdk = () => {
if (ready()) return Promise.resolve();
sdkPending ??= load('script', `${root()}Cesium.js`).catch((error) => {
sdkPending = null;
throw error;
});
return sdkPending;
};
const styles = () => {
stylesPending ??= load('link', `${root()}Widgets/widgets.css`).catch(
(error) => {
stylesPending = null;
throw error;
},
);
return stylesPending;
};
return {
ready,
sdk,
viewer: () => Promise.all([styles(), sdk()]).then(() => undefined),
};
}
let loader;
const shared = () => (loader ??= createCesiumLoader());
/** Before a Cesium globe starts: the SDK and its widget styles. */
export function loadCesium() {
return shared().viewer();
}
/** Before a feature that still builds on Cesium's entity model runs on Navara. */
export function loadCesiumSdk() {
return shared().sdk();
}
/** Whether `cesium` imports can be read now, without waiting. */
export function cesiumSdkReady() {
return shared().ready();
}
/**
* Run `start` now when the SDK is there, else once it has loaded (a promise,
* nothing when `signal` aborted meanwhile): a layer enable that is
* synchronous everywhere but on a Navara page without the SDK yet.
*/
export function whenCesiumSdk(start, signal) {
if (cesiumSdkReady()) return start();
return loadCesiumSdk().then(() => (signal?.aborted ? undefined : start()));
}
/**
* Production page, once at boot: until Cesium.js has run, a read of the
* `Cesium` global (what every `cesium` import reads in this build) logs where
* it came from and starts loading the SDK. A path that still needs Cesium on
* a Navara page then fails once, visibly, and works when it runs again,
* instead of failing for the rest of the session. Cesium.js's own assignment
* turns the global back into a plain value. A global the page already has
* (the strict QA trap, a host's own SDK) is left alone.
*/
export function guardCesiumGlobal({
globals = globalThis,
script = import.meta.env?.PROD === true,
report = (stack) =>
console.error('[Cesium] read before the SDK loaded', stack),
load = loadCesiumSdk,
} = {}) {
if (!script || Object.getOwnPropertyDescriptor(globals, 'Cesium')) return;
let reports = 0;
Object.defineProperty(globals, 'Cesium', {
configurable: true,
get() {
if (reports++ < 10) report(new Error('Cesium read').stack);
load().catch(() => {});
return undefined;
},
set(value) {
Object.defineProperty(globals, 'Cesium', {
value,
writable: true,
configurable: true,
enumerable: true,
});
},
});
}
+151
View File
@@ -0,0 +1,151 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { spawnSync } from 'node:child_process';
import { createCesiumLoader } from './loadCesium.js';
function fixture(globals = {}, { script = true } = {}) {
const elements = [];
const document = {
createElement: (tag) => ({
tag,
remove() {
elements.splice(elements.indexOf(this), 1);
},
}),
head: { append: (element) => elements.push(element) },
};
return {
elements,
globals,
loader: createCesiumLoader({
document,
globals,
base: '/app/cesium/',
script,
}),
};
}
test('a Cesium globe loads the SDK and its styles together, once, on demand', async () => {
const { elements, globals, loader } = fixture();
assert.equal(elements.length, 0);
const first = loader.viewer();
assert.equal(globals.CESIUM_BASE_URL, '/app/cesium/');
assert.deepEqual(
elements.map((e) => e.href ?? e.src),
['/app/cesium/Widgets/widgets.css', '/app/cesium/Cesium.js'],
);
const again = loader.viewer();
assert.equal(elements.length, 2, 'a second request shares the first');
elements.forEach((e) => e.onload());
await first;
await again;
await loader.viewer();
assert.equal(elements.length, 2);
});
test('a feature on Navara loads the SDK alone, and a later globe adds only the styles', async () => {
const { elements, loader } = fixture();
const sdk = loader.sdk();
assert.deepEqual(
elements.map((e) => e.src ?? e.href),
['/app/cesium/Cesium.js'],
);
elements[0].onload();
await sdk;
const viewer = loader.viewer();
assert.deepEqual(
elements.map((e) => e.src ?? e.href),
['/app/cesium/Cesium.js', '/app/cesium/Widgets/widgets.css'],
);
elements[1].onload();
await viewer;
});
test('the SDK is not loaded where the page already has it or imports its module', async () => {
const present = fixture({ Cesium: {} });
await present.loader.sdk();
assert.equal(present.elements.length, 0);
const getter = {};
Object.defineProperty(getter, 'Cesium', { get: () => ({}) });
const trapped = fixture(getter);
trapped.loader.sdk();
assert.equal(trapped.elements.length, 1, 'a getter is not read as the SDK');
const dev = fixture({}, { script: false });
await dev.loader.sdk();
assert.equal(dev.elements.length, 0);
});
test('a failed Cesium asset load can be retried and preserves the configured base', async () => {
const { elements, globals, loader } = fixture({
CESIUM_BASE_URL: '/custom/',
});
const failed = loader.viewer();
elements[1].onerror();
await assert.rejects(failed, /Could not load/);
assert.deepEqual(
elements.map((e) => e.href),
['/custom/Widgets/widgets.css'],
'the failed script is removed',
);
const retried = loader.viewer();
assert.equal(globals.CESIUM_BASE_URL, '/custom/');
assert.equal(elements[1].src, '/custom/Cesium.js');
elements.forEach((e) => e.onload());
await retried;
});
test('the standalone startup graph can be imported before the Cesium SDK exists', () => {
// Empty SDK exports make any boot-time native constructor or enum read fail.
// mgrs is CJS in Node; its browser named export is unrelated to this gate.
const script = `
import { registerHooks } from 'node:module';
registerHooks({ resolve(specifier, context, next) {
const code = specifier === 'cesium'
? 'export const Axis=undefined,ScreenSpaceEventType=undefined,BoundingSphere=undefined,Color=undefined,PostProcessStage=undefined;'
: specifier === 'mgrs' ? 'export function forward() {}' : null;
return code ? { url: 'data:text/javascript,' + encodeURIComponent(code), shortCircuit: true } : next(specifier, context);
}});
await import('./src/standalone/application.js');
const { registerNavaraLayerRenderers } = await import('./src/app/navaraMode.js');
await registerNavaraLayerRenderers();
const { createStandaloneCatalog } = await import('./src/standalone/catalog.js');
const lifetime = new AbortController();
const catalog = createStandaloneCatalog({ engineKind: 'navara', signal: lifetime.signal });
if (catalog.layers.length !== 33) throw new Error('Incomplete cold Navara catalog');
lifetime.abort();
`;
const result = spawnSync(
process.execPath,
['--import=./build/registerVue.js', '--input-type=module', '-e', script],
{ encoding: 'utf8' },
);
assert.equal(result.status, 0, result.stderr);
});
test('a read before the SDK loads is reported and starts the load; the SDK then reads plainly', async () => {
const { guardCesiumGlobal } = await import('./loadCesium.js');
const globals = {};
const reports = [];
let loads = 0;
guardCesiumGlobal({
globals,
script: true,
report: (stack) => reports.push(stack),
load: async () => loads++,
});
assert.equal(globals.Cesium, undefined);
assert.equal(reports.length, 1);
assert.equal(loads, 1);
const sdk = { Cartesian3: {} };
globals.Cesium = sdk;
assert.equal(globals.Cesium, sdk);
assert.equal(Object.getOwnPropertyDescriptor(globals, 'Cesium').value, sdk);
assert.equal(reports.length, 1);
const trapped = { Cesium: 'host' };
guardCesiumGlobal({ globals: trapped, script: true });
assert.equal(trapped.Cesium, 'host', 'an existing global is left alone');
const dev = {};
guardCesiumGlobal({ globals: dev, script: false });
assert.equal(Object.getOwnPropertyDescriptor(dev, 'Cesium'), undefined);
});