Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 | // The runtime-loading gate logic lives in
// runtimeExtensionLoader.ts and is tested directly (no string-eval of emitted
// code). Runs under jsdom, origin http://localhost. Later sections cover the
// descriptor/cache/audit behaviors.
import { isUrlLike, loadExternalModule, loadInPhases, sharePlugin } from './runtimeExtensionLoader';
// runtimeShared.ts pulls in the cornerstone extension and libraries; the tests
// only need to know it ran before a bundle was imported. (globalThis: jest's
// mock factories may not reference window.)
jest.mock('./runtimeShared', () => {
globalThis.__hostSharedLoaded = true;
return {};
});
describe('isUrlLike', () => {
test.each([
'https://x.example.com/y.js',
'http://x.example.com/y.js',
'/plugins/a.js',
'./a.js',
'../a.js',
'//host/x.js',
])('URL-shaped: %s', s => expect(isUrlLike(s)).toBe(true));
test.each([
'@ohif/extension-foo',
'dicom-microscopy-viewer',
'data:text/javascript,alert(1)',
'blob:http://localhost/x',
])('not URL-shaped: %s', s => expect(isUrlLike(s)).toBe(false));
});
describe('loadExternalModule', () => {
const loadedModule = { default: { id: 'loaded-plugin' } };
beforeEach(() => {
window.browserImportFunction = jest.fn().mockResolvedValue(loadedModule);
});
afterEach(() => {
delete window.browserImportFunction;
delete window.config;
delete window.__ohif;
});
test('unknown bare names throw a descriptive error naming pluginConfig.json without importing', async () => {
await expect(loadExternalModule('@typo/extension-name')).rejects.toThrow(
/unknown module "@typo\/extension-name".*pluginConfig\.json/s
);
expect(window.browserImportFunction).not.toHaveBeenCalled();
});
test('the audit record for an unknown name says how to fix it (the notification shows it)', async () => {
await expect(loadExternalModule('ohif-extension-missing')).rejects.toThrow();
const record = window.__ohif.runtimePlugins.find(
r => r.packageName === 'ohif-extension-missing'
);
expect(record.error).toMatch(/add it to pluginConfig\.json and rebuild/);
expect(record.error).toMatch(/window\.config\.extensions \/ window\.config\.modes/);
});
test('data: and blob: URIs are refused by the bare-name throw', async () => {
await expect(loadExternalModule('data:text/javascript,alert(1)')).rejects.toThrow(
/unknown module/
);
await expect(loadExternalModule('blob:http://localhost/x')).rejects.toThrow(/unknown module/);
expect(window.browserImportFunction).not.toHaveBeenCalled();
});
test('same-origin path, relative path, and absolute URL are allowed', async () => {
await expect(loadExternalModule('/plugins/a.js')).resolves.toBe(loadedModule.default);
await expect(loadExternalModule('./plugins/a.js')).resolves.toBe(loadedModule.default);
await expect(loadExternalModule('http://localhost/deep/b.js')).resolves.toBe(
loadedModule.default
);
expect(window.browserImportFunction).toHaveBeenCalledTimes(3);
expect(window.browserImportFunction).toHaveBeenCalledWith('/plugins/a.js');
});
test('cross-origin is denied by default with an actionable message', async () => {
await expect(loadExternalModule('https://evil.example.com/x.js')).rejects.toThrow(
/refusing to load plugin code .* runtimePluginOrigins/s
);
expect(window.browserImportFunction).not.toHaveBeenCalled();
});
test('protocol-relative URLs resolve cross-origin and are denied', async () => {
await expect(loadExternalModule('//evil.example.com/x.js')).rejects.toThrow(/not allowlisted/);
});
test('different port is a different origin', async () => {
await expect(loadExternalModule('http://localhost:8080/x.js')).rejects.toThrow(
/not allowlisted/
);
});
test('window.config.runtimePluginOrigins allowlists an origin (with normalization)', async () => {
window.config = { runtimePluginOrigins: ['https://cdn.example.com/any/path'] };
await expect(loadExternalModule('https://cdn.example.com/plugins/ext.js')).resolves.toBe(
loadedModule.default
);
await expect(loadExternalModule('https://other.example.com/ext.js')).rejects.toThrow(
/not allowlisted/
);
});
test('window.__ohif.runtimePluginOrigins is the canonical stash and takes precedence over window.config', async () => {
// Function-style app configs cannot carry the array on window.config, so
// the loader reads the __ohif stash first.
window.__ohif = { runtimePluginOrigins: ['https://cdn.example.com'] };
await expect(loadExternalModule('https://cdn.example.com/plugins/ext.js')).resolves.toBe(
loadedModule.default
);
// When the stash exists, window.config's list is not consulted.
window.__ohif = { runtimePluginOrigins: [] };
window.config = { runtimePluginOrigins: ['https://cdn.example.com'] };
await expect(loadExternalModule('https://cdn.example.com/plugins/ext.js')).rejects.toThrow(
/not allowlisted/
);
});
test('malformed allowlist entries are ignored, not fatal', async () => {
window.config = { runtimePluginOrigins: [null, 42, '%%%'] };
await expect(loadExternalModule('https://cdn.example.com/x.js')).rejects.toThrow(
/not allowlisted/
);
});
});
// ---------------------------------------------------------------------------
// Descriptor loader behaviors (the strict globalName format discriminator, RP-DESC-4 in
// platform/docs/docs/development/specs/runtime-plugins/implementation.md: globalName
// present = UMD global lookup, absent = ESM
// .default, no fallback chain in either direction), Mode bare-name cache
// resolution, audit records, integrity, styles, and failure surfacing.
//
// The runtimeModules cache is module-scope state, so each test re-requires the
// loader through jest.resetModules() and starts from a fresh window.__ohif.
// ---------------------------------------------------------------------------
const nodeCrypto = require('crypto');
const HOST_VERSION = '3.13.0-beta.89';
const PKG = '@test/runtime-ext';
const ORIGINAL_VERSION_NUMBER = process.env.VERSION_NUMBER;
describe('loadRuntimeDescriptor', () => {
let loader;
let extModule; // fresh per test so toBe assertions prove identity, not equality
const audit = () => (window.__ohif && window.__ohif.runtimePlugins) || [];
const lastRecord = () => audit()[audit().length - 1];
// UMD contract: dynamic import of the script has the side effect of assigning
// the library global; the import() namespace itself carries nothing useful.
const mockUmdImport = (globalName = PKG) => {
window.browserImportFunction.mockImplementation(async () => {
window[globalName] = extModule;
return {};
});
};
// ESM contract: the import() namespace default-exports the extension/mode.
const mockEsmImport = (ns = undefined) => {
window.browserImportFunction.mockResolvedValue(ns ?? { default: extModule });
};
const umdDescriptor = overrides => ({
packageName: PKG,
importPath: '/plugins/t.umd.js',
globalName: PKG,
...overrides,
});
const esmDescriptor = overrides => ({
packageName: PKG,
importPath: '/plugins/t.mjs',
...overrides,
});
beforeEach(() => {
process.env.VERSION_NUMBER = HOST_VERSION;
delete window.__ohif;
delete window.config;
delete window[PKG];
delete window.__hostSharedLoaded;
extModule = { id: PKG };
window.browserImportFunction = jest.fn();
if (!window.crypto || !window.crypto.subtle) {
Object.defineProperty(window, 'crypto', {
value: nodeCrypto.webcrypto,
configurable: true,
});
}
global.fetch = jest.fn();
URL.createObjectURL = jest.fn(() => 'blob:http://localhost/mock-blob');
URL.revokeObjectURL = jest.fn();
jest.resetModules();
loader = require('./runtimeExtensionLoader');
});
afterEach(() => {
delete window.browserImportFunction;
delete window.__ohif;
delete window.config;
delete window[PKG];
delete global.fetch;
delete URL.createObjectURL;
delete URL.revokeObjectURL;
document.head.querySelectorAll('link[rel="stylesheet"]').forEach(l => l.remove());
});
afterAll(() => {
process.env.VERSION_NUMBER = ORIGINAL_VERSION_NUMBER;
});
describe('host-shared globals', () => {
test('are assigned before a descriptor bundle is imported', async () => {
let sharedWhenImported;
window.browserImportFunction.mockImplementation(async () => {
sharedWhenImported = window.__hostSharedLoaded;
window[PKG] = extModule;
return {};
});
await loader.loadRuntimeDescriptor(umdDescriptor());
expect(sharedWhenImported).toBe(true);
});
test('are assigned before a URL is imported through the fallthrough', async () => {
let sharedWhenImported;
window.browserImportFunction.mockImplementation(async () => {
sharedWhenImported = window.__hostSharedLoaded;
return { default: extModule };
});
await loader.loadExternalModule('/plugins/x.js');
expect(sharedWhenImported).toBe(true);
});
test('are not loaded for a descriptor the loader refuses', async () => {
await loader.loadRuntimeDescriptor(
umdDescriptor({ importPath: 'https://evil.example.com/x.js' })
);
expect(window.__hostSharedLoaded).toBeUndefined();
});
});
describe('strict globalName format discriminator', () => {
test('UMD happy path: globalName set returns the window global and audits loaded/umd', async () => {
mockUmdImport();
const mod = await loader.loadRuntimeDescriptor(umdDescriptor());
expect(mod).toBe(extModule);
expect(window.browserImportFunction).toHaveBeenCalledWith(
'http://localhost/plugins/t.umd.js'
);
const record = lastRecord();
expect(record.status).toBe('loaded');
expect(record.format).toBe('umd');
expect(record.packageName).toBe(PKG);
expect(record.hostVersion).toBe('3.13.0-beta.89');
expect(record.resolvedUrl).toBe('http://localhost/plugins/t.umd.js');
expect(typeof record.durationMs).toBe('number');
expect(typeof record.timestamp).toBe('string');
});
test('UMD global holding the whole module: returns its default and leaves the named exports on window', async () => {
// The create-ohif template builds without output.library.export, so the
// global is the module (default plus named exports), as sharePlugin puts
// a compiled-in plugin's.
const helper = () => {};
const wholeModule = { default: extModule, helper };
window.browserImportFunction.mockImplementation(async () => {
window[PKG] = wholeModule;
return {};
});
const mod = await loader.loadRuntimeDescriptor(umdDescriptor());
expect(mod).toBe(extModule);
expect(lastRecord().status).toBe('loaded');
expect(window[PKG].helper).toBe(helper);
});
test('ESM happy path: globalName absent returns the namespace default and audits loaded/esm', async () => {
mockEsmImport();
const mod = await loader.loadRuntimeDescriptor(esmDescriptor());
expect(mod).toBe(extModule);
const record = lastRecord();
expect(record.status).toBe('loaded');
expect(record.format).toBe('esm');
expect(record.resolvedUrl).toBe('http://localhost/plugins/t.mjs');
});
test('globalName set but the script never assigns the global: import-error, NO .default fallback', async () => {
// The namespace DOES have a default export; strict UMD lookup must not use it.
mockEsmImport();
const mod = await loader.loadRuntimeDescriptor(umdDescriptor());
expect(mod).toBeNull();
expect(lastRecord().status).toBe('import-error');
expect(lastRecord().format).toBe('umd');
expect(lastRecord().error).toMatch(/output\.library\.name/);
});
test('globalName absent but only a window global was assigned: import-error, NO window[packageName] fallback', async () => {
// A UMD build loaded through an ESM descriptor: global gets set, namespace
// has no default. Strict ESM lookup must not consult window[packageName].
mockUmdImport();
const mod = await loader.loadRuntimeDescriptor(esmDescriptor());
expect(mod).toBeNull();
expect(lastRecord().status).toBe('import-error');
expect(lastRecord().format).toBe('esm');
expect(lastRecord().error).toMatch(/no default export/);
});
});
describe('Mode bare-name cache resolution (the task-6 scenario)', () => {
test('resolveRuntimeModule returns the SAME object loadRuntimeDescriptor produced', async () => {
// appInit loads the app-config descriptor -> runtimeModules.set; later a
// bundled mode's route mounts and Mode.tsx calls loadModules with the BARE
// package name (extensionDependencies keys). The generated string branch
// has no static `if` for runtime packages, so it consults
// resolveRuntimeModule — a cache hit, not a bare-specifier import that
// would reject the Promise.all and leave the mode blank.
mockUmdImport();
const mod = await loader.loadRuntimeDescriptor(umdDescriptor());
expect(loader.resolveRuntimeModule(PKG)).toBe(mod);
});
test('unknown bare names are not in the cache', async () => {
expect(loader.resolveRuntimeModule('@never/loaded')).toBeUndefined();
});
test('idempotent: a second load for the same packageName does not import again', async () => {
mockUmdImport();
const first = await loader.loadRuntimeDescriptor(umdDescriptor());
const second = await loader.loadRuntimeDescriptor(umdDescriptor());
expect(second).toBe(first);
expect(window.browserImportFunction.mock.calls.length).toBe(1);
expect(audit().length).toBe(1); // no duplicate audit record either
});
});
describe('origin allowlist', () => {
test('cross-origin without allowlist: refused-origin, returns null, nothing imported', async () => {
const mod = await loader.loadRuntimeDescriptor(
umdDescriptor({ importPath: 'https://evil.example.com/x.js' })
);
expect(mod).toBeNull();
expect(lastRecord().status).toBe('refused-origin');
expect(window.browserImportFunction).not.toHaveBeenCalled();
expect(global.fetch).not.toHaveBeenCalled();
});
test('protocol-relative importPath resolves to its real cross-origin and is refused', async () => {
const mod = await loader.loadRuntimeDescriptor(
umdDescriptor({ importPath: '//evil.example.com/x.js' })
);
expect(mod).toBeNull();
expect(lastRecord().status).toBe('refused-origin');
expect(lastRecord().resolvedUrl).toBe('http://evil.example.com/x.js');
});
});
describe('integrity (allowlisted cross-origin)', () => {
const CDN_URL = 'https://cdn.example.com/plugins/t.umd.js';
const scriptBytes = Buffer.from(`window["${PKG}"] = { id: "${PKG}" };`);
const goodIntegrity =
'sha384-' + nodeCrypto.createHash('sha384').update(scriptBytes).digest('base64');
const allowCdn = () => {
window.__ohif = { runtimePluginOrigins: ['https://cdn.example.com'] };
};
const mockFetchScript = () => {
global.fetch.mockResolvedValue({
ok: true,
arrayBuffer: async () =>
scriptBytes.buffer.slice(
scriptBytes.byteOffset,
scriptBytes.byteOffset + scriptBytes.byteLength
),
});
};
test('cross-origin without integrity is integrity-failed (required), before any fetch/import', async () => {
allowCdn();
const mod = await loader.loadRuntimeDescriptor(umdDescriptor({ importPath: CDN_URL }));
expect(mod).toBeNull();
expect(lastRecord().status).toBe('integrity-failed');
expect(lastRecord().error).toMatch(/integrity is required/);
expect(global.fetch).not.toHaveBeenCalled();
expect(window.browserImportFunction).not.toHaveBeenCalled();
});
test('correct sha384 integrity: fetch -> digest -> blob import -> loaded, blob URL revoked', async () => {
allowCdn();
mockFetchScript();
mockUmdImport();
const mod = await loader.loadRuntimeDescriptor(
umdDescriptor({ importPath: CDN_URL, integrity: goodIntegrity })
);
expect(mod).toBe(extModule);
expect(lastRecord().status).toBe('loaded');
expect(lastRecord().resolvedUrl).toBe(CDN_URL);
expect(global.fetch).toHaveBeenCalledWith(CDN_URL, { mode: 'cors' });
expect(window.browserImportFunction).toHaveBeenCalledWith('blob:http://localhost/mock-blob');
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:http://localhost/mock-blob');
});
test('wrong hash: integrity-failed, module never evaluated', async () => {
allowCdn();
mockFetchScript();
mockUmdImport();
const mod = await loader.loadRuntimeDescriptor(
umdDescriptor({
importPath: CDN_URL,
integrity: 'sha384-' + Buffer.alloc(48).toString('base64'),
})
);
expect(mod).toBeNull();
expect(lastRecord().status).toBe('integrity-failed');
expect(window.browserImportFunction).not.toHaveBeenCalled();
});
});
describe('coreVersionRange gate', () => {
test("'^3.0.0' with prerelease host 3.13.0-beta.89 loads (includePrerelease)", async () => {
mockUmdImport();
const mod = await loader.loadRuntimeDescriptor(umdDescriptor({ coreVersionRange: '^3.0.0' }));
expect(mod).toBe(extModule);
expect(lastRecord().status).toBe('loaded');
expect(lastRecord().requiredRange).toBe('^3.0.0');
});
test("'>=4.0.0' is version-mismatch, fail-closed BEFORE import", async () => {
mockUmdImport();
const mod = await loader.loadRuntimeDescriptor(
umdDescriptor({ coreVersionRange: '>=4.0.0' })
);
expect(mod).toBeNull();
const record = lastRecord();
expect(record.status).toBe('version-mismatch');
expect(record.hostVersion).toBe('3.13.0-beta.89');
expect(record.requiredRange).toBe('>=4.0.0');
expect(window.browserImportFunction).not.toHaveBeenCalled();
});
});
describe('id contract', () => {
test("the module's id must equal packageName", async () => {
window.browserImportFunction.mockImplementation(async () => {
window[PKG] = { id: '@wrong/id' };
return {};
});
const mod = await loader.loadRuntimeDescriptor(umdDescriptor());
expect(mod).toBeNull();
expect(lastRecord().status).toBe('import-error');
expect(lastRecord().error).toMatch(/"@wrong\/id" must equal packageName/);
});
});
describe('styles', () => {
test('descriptor styles are appended as stylesheet links and never duplicated', async () => {
mockUmdImport();
await loader.loadRuntimeDescriptor(umdDescriptor({ styles: ['/plugins/t.css'] }));
const selector = 'link[rel="stylesheet"][href="http://localhost/plugins/t.css"]';
expect(document.head.querySelectorAll(selector).length).toBe(1);
// Second load through a FRESH module instance (empty cache, so injectStyles
// runs again against the same document): still exactly one link.
jest.resetModules();
const freshLoader = require('./runtimeExtensionLoader');
mockUmdImport();
await freshLoader.loadRuntimeDescriptor(umdDescriptor({ styles: ['/plugins/t.css'] }));
expect(document.head.querySelectorAll(selector).length).toBe(1);
});
});
describe('kind', () => {
test('records whether the descriptor was an extension or a mode', async () => {
mockUmdImport();
await loader.loadRuntimeDescriptor(umdDescriptor(), undefined, 'mode');
expect(lastRecord()).toMatchObject({ packageName: PKG, kind: 'mode', status: 'loaded' });
});
test('is recorded on a refused descriptor too', async () => {
await loader.loadRuntimeDescriptor(
umdDescriptor({ importPath: 'https://evil.example.com/x.js' }),
undefined,
'extension'
);
expect(lastRecord()).toMatchObject({ kind: 'extension', status: 'refused-origin' });
});
test("a built-in plugin's registration-error record takes the caller's kind", () => {
loader.recordRegistrationError('@fixture/kind-built-in', new Error('boom'), 'mode');
expect(lastRecord()).toMatchObject({ packageName: '@fixture/kind-built-in', kind: 'mode' });
});
});
describe('a descriptor for a plugin declared in pluginConfig.json', () => {
test('is refused before anything is fetched, and the record says why', async () => {
const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
mockUmdImport();
const result = await loader.loadRuntimeDescriptor(umdDescriptor(), new Set([PKG]));
expect(result).toBeNull();
expect(window.browserImportFunction).not.toHaveBeenCalled();
expect(window[PKG]).toBeUndefined();
expect(lastRecord()).toMatchObject({ packageName: PKG, status: 'duplicate-of-built-in' });
expect(lastRecord().error).toMatch(/already compiled into this viewer/);
expect(loader.resolveRuntimeModule(PKG)).toBeUndefined();
warn.mockRestore();
});
test('a name that is not built in loads as before', async () => {
mockUmdImport();
const result = await loader.loadRuntimeDescriptor(umdDescriptor(), new Set(['@other/ext']));
expect(result).toBe(extModule);
expect(lastRecord().status).toBe('loaded');
});
test('is surfaced as a warning, not a failure', async () => {
const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
await loader.loadRuntimeDescriptor(umdDescriptor(), new Set([PKG]));
const show = jest.fn();
loader.surfaceRuntimeExtensionFailures({ show });
expect(show).toHaveBeenCalledTimes(1);
expect(show).toHaveBeenCalledWith(
expect.objectContaining({
title: 'Runtime plugin skipped',
type: 'warning',
message: expect.stringContaining('duplicate-of-built-in'),
})
);
warn.mockRestore();
});
});
describe('loadExternalModule audit + failure surfacing', () => {
test('cross-origin non-allowlisted URL rejects AND pushes a refused-origin audit record', async () => {
await expect(
loader.loadExternalModule('https://evil.example.com/x.js')
).rejects.toThrow(/not allowlisted/);
const record = lastRecord();
expect(record.status).toBe('refused-origin');
expect(record.packageName).toBe('https://evil.example.com/x.js');
expect(record.resolvedUrl).toBe('https://evil.example.com/x.js');
});
test("recordRegistrationError flips the latest 'loaded' record", async () => {
mockUmdImport();
await loader.loadRuntimeDescriptor(umdDescriptor());
expect(lastRecord().status).toBe('loaded');
loader.recordRegistrationError(PKG, new Error('modeFactory blew up'), 'extension');
expect(lastRecord().status).toBe('registration-error');
expect(lastRecord().error).toBe('modeFactory blew up');
});
test('recordRegistrationError adds a record for a built-in extension, and it is surfaced', () => {
// A built-in extension has no audit record of its own; before this, its
// registration failure was dropped silently.
const before = window.__ohif?.runtimePlugins?.length ?? 0;
loader.recordRegistrationError('@fixture/built-in-ext', new Error('preRegistration threw'), 'extension');
const records = window.__ohif.runtimePlugins;
expect(records.length).toBe(before + 1);
expect(lastRecord()).toMatchObject({
packageName: '@fixture/built-in-ext',
importPath: '(built-in)',
status: 'registration-error',
error: 'preRegistration threw',
});
const show = jest.fn();
loader.surfaceRuntimeExtensionFailures({ show });
const shown = show.mock.calls.filter(([n]) => n.message.includes('@fixture/built-in-ext'));
expect(shown).toHaveLength(1);
expect(shown[0][0].message).toContain('preRegistration threw');
});
test('reconcileRuntimeRegistrations flips a loaded-but-unregistered descriptor to registration-error', async () => {
mockUmdImport();
await loader.loadRuntimeDescriptor(umdDescriptor());
expect(lastRecord().status).toBe('loaded');
// Descriptor is in the config yet absent from the registered ids.
loader.reconcileRuntimeRegistrations(
{ getRegisteredExtensionIds: () => [] },
[umdDescriptor()]
);
expect(lastRecord().status).toBe('registration-error');
});
test('reconcileRuntimeRegistrations unwraps [descriptor, config] tuple entries', async () => {
mockUmdImport();
await loader.loadRuntimeDescriptor(umdDescriptor());
expect(lastRecord().status).toBe('loaded');
// Tuple form: descriptor is entry[0]. Before the unwrap fix this record
// stayed 'loaded' and its failure was never surfaced.
loader.reconcileRuntimeRegistrations(
{ getRegisteredExtensionIds: () => [] },
[[umdDescriptor(), { some: 'config' }]]
);
expect(lastRecord().status).toBe('registration-error');
});
test('reconcileRuntimeRegistrations leaves a registered descriptor as loaded', async () => {
mockUmdImport();
await loader.loadRuntimeDescriptor(umdDescriptor());
loader.reconcileRuntimeRegistrations(
{ getRegisteredExtensionIds: () => [PKG] },
[[umdDescriptor(), { some: 'config' }]]
);
expect(lastRecord().status).toBe('loaded');
});
test('surfaceRuntimeExtensionFailures shows one error toast per failure, exactly once', async () => {
await loader.loadRuntimeDescriptor(
umdDescriptor({ importPath: 'https://evil.example.com/x.js' })
);
mockUmdImport();
await loader.loadRuntimeDescriptor(umdDescriptor()); // loaded: must NOT surface
const show = jest.fn();
loader.surfaceRuntimeExtensionFailures({ show });
expect(show).toHaveBeenCalledTimes(1);
expect(show).toHaveBeenCalledWith(
expect.objectContaining({
type: 'error',
message: expect.stringContaining('refused-origin'),
})
);
expect(audit()[0].surfaced).toBe(true);
// Safe to call repeatedly: already-surfaced failures produce 0 new toasts.
loader.surfaceRuntimeExtensionFailures({ show });
expect(show).toHaveBeenCalledTimes(1);
});
});
});
describe('sharePlugin', () => {
afterEach(() => {
delete window['@fixture/ext-shared'];
});
test('puts the whole module, named exports included, on window under its package name', () => {
const module = { default: { id: '@fixture/ext-shared' }, toolNames: { A: 'A' } };
expect(sharePlugin('@fixture/ext-shared', module)).toBe(module);
expect(window['@fixture/ext-shared']).toBe(module);
expect(window['@fixture/ext-shared'].toolNames).toEqual({ A: 'A' });
});
test('never overwrites an existing global (e.g. an SDK package from runtimeShared.ts)', () => {
const existing = { default: { id: 'existing' } };
window['@fixture/ext-shared'] = existing;
const module = { default: { id: 'other' } };
expect(sharePlugin('@fixture/ext-shared', module)).toBe(module);
expect(window['@fixture/ext-shared']).toBe(existing);
});
});
describe('loadInPhases', () => {
const descriptor = { packageName: '@fixture/runtime', importPath: '/plugins/runtime.umd.js' };
test('loads every compiled-in entry before any runtime descriptor starts', async () => {
const events = [];
const load = jest.fn(async entry => {
const name = typeof entry === 'string' ? entry : (entry.packageName ?? entry[0].packageName);
events.push(`start ${name}`);
await new Promise(resolve => setTimeout(resolve, name === 'slow-compiled' ? 20 : 0));
events.push(`end ${name}`);
return name;
});
await loadInPhases(['slow-compiled', descriptor, 'fast-compiled'], load);
const firstRuntimeStart = events.indexOf('start @fixture/runtime');
expect(firstRuntimeStart).toBeGreaterThan(events.indexOf('end slow-compiled'));
expect(firstRuntimeStart).toBeGreaterThan(events.indexOf('end fast-compiled'));
});
test('treats a [descriptor, config] tuple as a runtime entry', async () => {
const events = [];
const load = jest.fn(async entry => {
events.push(Array.isArray(entry) ? 'tuple' : entry);
});
await loadInPhases([[descriptor, { option: true }], 'compiled'], load);
expect(events).toEqual(['compiled', 'tuple']);
});
test('returns results in input order, whatever the phase', async () => {
const load = async entry => (typeof entry === 'string' ? `loaded ${entry}` : 'loaded runtime');
await expect(loadInPhases([descriptor, 'a', 'b'], load)).resolves.toEqual([
'loaded runtime',
'loaded a',
'loaded b',
]);
});
});
// The documented recipe for a runtime plugin that imports an extension loaded on
// demand: the deployer also lists that extension by name in
// window.config.extensions, so it is loaded and shared before the plugin runs,
// wherever it sits in the list.
describe('listing an on-demand extension alongside a runtime plugin', () => {
afterEach(() => {
delete window['@fixture/on-demand-ext'];
});
test('the extension is on window when the runtime plugin loads', async () => {
const extensionModule = { default: { id: '@fixture/on-demand-ext' }, toolNames: {} };
const descriptor = {
packageName: '@fixture/runtime',
importPath: '/plugins/runtime.umd.js',
globalName: '@fixture/runtime',
};
let seenByRuntimePlugin;
const load = async entry => {
if (typeof entry === 'string') {
// What the generated loadModule does for a compiled-in plugin.
await new Promise(resolve => setTimeout(resolve, 10));
return sharePlugin(entry, extensionModule).default;
}
seenByRuntimePlugin = window['@fixture/on-demand-ext'];
return { id: entry.packageName };
};
await loadInPhases([descriptor, '@fixture/on-demand-ext'], load);
expect(seenByRuntimePlugin).toBe(extensionModule);
});
});
|