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 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 | 178x 178x 534x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 534x 534x 534x 3856x 3856x 2873x 2873x 627x 627x 627x 3856x 3856x 3856x 3856x 534x 534x 178x 178x 1246x 178x 1246x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 178x 178x 178x 178x 178x 178x 178x 178x 178x 1x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 12x 215088x 215088x 176557x 38531x 38531x 38531x 37531x 38531x 1974985x 1859528x 115457x 115457x 32131x 32131x 32131x 1654241x 502x 502x 502x 251x 251x 251x 1653739x 1653739x 1653739x 32131x 83326x 83326x 83326x 83326x 282213x 282213x 282213x 83326x 502x 502x 502x 502x 502x 356x 356x 450x 450x 1177x 39043x 29270x 9773x 9773x 9768x 5x 5x 5x 1517x 1517x 1517x 18615x 18615x 890x 890x 178x 178x 712x 190x 190x 190x 75x 190x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 534x 534x 534x 534x 3x 3x 1x 534x 356x 1x 1x 1x 1177x 2x 2x 1175x 1175x 1175x 1175x 1175x 1175x 1175x 1175x 1175x 1175x 718x 718x 718x 718x 718x 718x 17903x 17903x 17903x 17903x 6729x 6729x 19796x 18710x 19796x 18894x 902x 902x 1893x 1893x 178x 178x 178x 178x 178x 178x 83326x 83326x 83326x 2170301x 48563x 1776430x 2121738x 120080x 178x 119902x 374977x 902x 374075x 2169221x | import update, { extend } from 'immutability-helper';
import JSON5 from 'json5';
import { PubSubService } from '../_shared/pubSubServiceInterface';
import type { Customization, CustomizationEntries } from './types';
import type { CommandsManager } from '../../classes';
import type ExtensionManager from '../../extensions/ExtensionManager';
import { getCustomizationUrlPolicy } from './customizationUrl';
import { getUrlCustomizationModulePayload } from './getUrlCustomizationModulePayload';
import { resolveCustomizationUrl } from './resolve';
import { parseCustomizationParams, validateCustomizationRequests } from './validate';
import type { ValidatedCustomization } from './validate';
import type { CustomizationUrlPolicy } from './customizationUrlDefaults';
import type {
CustomizationModule,
CustomizationPhaseInput,
LoadedCustomization,
LoadOptions,
PhasedCustomizationConfig,
} from './customizationUrlTypes';
/**
* Reserved key in a `mode` phase block for the "general" customizations that
* apply to every mode. The general block is applied FIRST on each mode enter;
* a block keyed by the entered mode's id / routeName is applied after it so a
* single mode can override the general values.
*/
export const GENERAL_MODE_KEY = '*';
const EVENTS = {
MODE_CUSTOMIZATION_MODIFIED: 'event::CustomizationService:modeModified',
GLOBAL_CUSTOMIZATION_MODIFIED: 'event::CustomizationService:globalModified',
DEFAULT_CUSTOMIZATION_MODIFIED: 'event::CustomizationService:defaultModified',
};
/**
* Enum representing the different scopes of customizations available in the system.
*/
export enum CustomizationScope {
/**
* Global customizations that override both mode and default customizations.
* These are applied universally across the application.
*/
Global = 'global',
/**
* Mode-specific customizations that are only active during a particular mode.
* These are cleared and reset when switching between modes.
*/
Mode = 'mode',
/**
* Default customizations that serve as fallbacks when no global or mode-specific
* customizations are defined. These are not cleared when the service re-inits
* for a mode change; only Mode scope is reset.
*/
Default = 'default',
}
/**
* The CustomizationService allows for retrieving of custom components
* and configuration for mode and global values.
* The intent of the items is to provide a react component. This can be
* done by straight out providing an entire react component or else can be
* done by configuring a react component, or configuring a part of a react
* component. These are intended to be fairly indistinguishable in use of
* it, although the internals of how that is implemented may need to know
* about the customization service.
*
* A customization value can be:
* 1. React function, taking (React, props) and returning a rendered component
* For example, createLogoComponentFn renders a component logo for display
* 2. Custom UI component configuration, as defined by the component which uses it.
* For example, context menus define a complex structure allowing site-determined
* context menus to be set.
* 3. A string name, being the extension id for retrieving one of the above.
*
* The default values for the extension come from the app_config value 'whiteLabeling',
* The whiteLabelling can have lists of extensions to load for the default global and
* mode extensions. These are:
* 'globalExtensions' which is a list of extension id's to load for global values
* 'modeExtensions' which is a list of extension id's to load for mode values
* They default to the list ['*'] if not otherwise provided, which means to check
* every module for the given id and to load it/add it to the extensions.
*/
export default class CustomizationService extends PubSubService {
public static EVENTS = EVENTS;
public Scope = CustomizationScope;
public static REGISTRATION = {
name: 'customizationService',
create: ({ configuration, commandsManager }) => {
return new CustomizationService({ configuration, commandsManager });
},
};
commandsManager: CommandsManager;
extensionManager: ExtensionManager;
/**
* A collection of global customizations that act as a priority layer.
* These customizations are applied universally, overriding both mode-specific
* and default customizations. Ideal for system-wide changes.
*/
private globalCustomizations = new Map<string, Customization>();
/**
* A collection of mode-specific customizations. These allow modes to define
* their own behavior without impacting other modes. These customizations
* are cleared and redefined whenever a mode changes, ensuring isolation
* between modes. Read more about modes in the modes documentation.
*/
private modeCustomizations = new Map<string, Customization>();
/**
* A collection of default customizations used as fallbacks. Entries are merged
* over time (including from `init()` re-reading extension default modules) and
* are not cleared on mode change. Mode and Global scopes override these values.
*/
private defaultCustomizations = new Map<string, Customization>();
/**
* Has the transformed/final customization value. This avoids needing to
* transform every time a customization is requested.
*/
private transformedCustomizations = new Map<string, Customization>();
private configuration: AppTypes.Config;
/**
* URL customization modules already imported and applied (key = normalized `/prefix/name`).
* Entries are kept for the lifetime of the page: repeated loads skip imports, and the app
* normally applies `?customization=` only at bootstrap (see {@link applyWindowUrlCustomizations}).
*/
private _urlCustomizationLoaded = new Map<string, LoadedCustomization>();
private _urlCustomizationPending = new Map<string, Promise<LoadedCustomization | null>>();
/**
* Every URL customization module resolved this page session, in load order
* (dependencies before dependents). The lifecycle phase appliers
* ({@link applyBootstrapCustomizations}, {@link applyGlobalCustomizations},
* {@link applyModeCustomizations}) iterate this list so a module's phase
* blocks are applied at the right time regardless of when it was fetched.
*/
private _resolvedUrlModules: LoadedCustomization[] = [];
/**
* Normalized form of `appConfig.customizationService`. Either a phase-tagged
* config ({@link PhasedCustomizationConfig}) or, for the legacy array/object
* form, the references to add (Global) during {@link init}.
*/
private _customizationConfig: {
phased?: PhasedCustomizationConfig;
legacyReferences?: unknown;
} | null = null;
/** Id/aliases of the mode currently entered, used to re-apply mode phase blocks. */
private _currentModeIds: string[] = [];
/**
* Extension module entry ids (e.g. `${extensionId}.customizationModule.default`) whose
* default/global payloads have already been merged via {@link init}. Matches the URL
* loader pattern: repeated {@link init} skips work for the same slot so immutability-style
* merges are not applied twice. A slot is recorded only after a module was present and applied;
* if a module appears only on a later {@link init} (e.g. a newly registered extension), it is merged then.
*/
private _extensionCustomizationModuleApplied = new Set<string>();
constructor({ configuration, commandsManager }) {
super(EVENTS);
this.configuration = configuration;
this.commandsManager = commandsManager;
}
// ===========================================================================
// Public API
// ===========================================================================
/**
* Clears mode customizations and merges each extension's `customizationModule.default` /
* `customizationModule.global` into the service. Safe to call multiple times (e.g. from
* {@link onModeEnter}): each extension module slot is merged at most once per page session,
* matching the deduplication pattern used for URL-loaded modules in {@link requires}.
* Slots with no module yet are left unmarked so a later call can merge when the module appears.
*/
public init(extensionManager: ExtensionManager): void {
this.extensionManager = extensionManager;
// Mode customizations are defined per mode in onModeEnter; reset them here.
// Default customizations are not cleared — they are merged again from
// extension modules below so definitions stay available across mode changes.
this.modeCustomizations.clear();
this.extensionManager.getRegisteredExtensionIds().forEach(extensionId => {
const keyDefault = `${extensionId}.customizationModule.default`;
if (!this._extensionCustomizationModuleApplied.has(keyDefault)) {
const defaultCustomizations = this._findExtensionValue(keyDefault);
if (defaultCustomizations) {
const { value } = defaultCustomizations;
this._addReference(value, CustomizationScope.Default);
this._extensionCustomizationModuleApplied.add(keyDefault);
}
}
const keyGlobal = `${extensionId}.customizationModule.global`;
if (!this._extensionCustomizationModuleApplied.has(keyGlobal)) {
const globalCustomizations = this._findExtensionValue(keyGlobal);
Iif (globalCustomizations) {
const { value } = globalCustomizations;
this._addReference(value, CustomizationScope.Global);
this._extensionCustomizationModuleApplied.add(keyGlobal);
}
}
});
// Only add references for the configuration once. The phase-tagged config
// form (bootstrap/global/mode) is applied by the lifecycle appliers
// instead, so only the legacy array/object form is added here as Global.
const config = this._getCustomizationConfig();
if (config.legacyReferences !== undefined && !this.configuration?._hasBeenAdded) {
this.addReferences(config.legacyReferences);
Object.defineProperty(this.configuration, '_hasBeenAdded', { value: true, writable: false });
}
}
/**
* Memoized, normalized view of `appConfig.customizationService`. Detects the
* phase-tagged form (any of `requires` / `bootstrap` / `global` / `mode`)
* and otherwise treats the value as legacy Global references.
*/
private _getCustomizationConfig(): {
phased?: PhasedCustomizationConfig;
legacyReferences?: unknown;
} {
if (!this._customizationConfig) {
this._customizationConfig = normalizeCustomizationConfig(this.configuration);
}
return this._customizationConfig;
}
/**
* Loads and applies `?customization=` modules from `window.location.search`.
*
* **Throws on disallowed values.** A `?customization=` value whose prefix is
* not in `appConfig.customizationUrlPrefixes` (the default — the feature is off
* until prefixes are configured) rejects this promise, which by design aborts
* app bootstrap rather than silently ignoring the request.
*
* **Intended SPA behavior:** The shell typically calls this once during startup. It does not
* run again on client-side route changes. The query key `customization` may still appear in
* URLs (for example preserved by worklist navigation) without implying that modules are
* re-evaluated on every navigation. Modules resolved here are also deduplicated by normalized
* URL for the lifetime of the page in {@link requires}. To pick up a different `?customization=`
* set, use a full page load or call {@link applyCustomizationUrlSearchParams} /
* {@link requires} from your own integration code when appropriate.
*
* **What is loaded:** Each `?customization=` entry resolves to a JSONC file (JSON with
* comments / trailing commas) under a configured prefix directory. The file is fetched and
* parsed as **data** — it is never executed. Executable code (plugins, modes, extensions)
* loads only through `pluginConfig.json`, never from the customization URL path. A module's
* `global` payload is applied as global customizations and its `requires` are loaded first.
*/
public async applyWindowUrlCustomizations(overrides?: Partial<LoadOptions>): Promise<void> {
Iif (typeof window === 'undefined') {
return;
}
await this.applyCustomizationUrlSearchParams(
new URLSearchParams(window.location.search),
overrides
);
}
/**
* Parses `?customization=` values from the search string and delegates to
* {@link requires}.
*/
public async applyCustomizationUrlSearchParams(
params: URLSearchParams,
overrides?: Partial<LoadOptions>
): Promise<void> {
const raws = parseCustomizationParams(params);
Iif (!raws.length) {
return;
}
await this.requires(raws, overrides);
}
/**
* Depth-first dynamic import of URL customization modules
* `requires` edges and `customization` field
* references are loaded before dependents. Already-loaded modules (same normalized key) are
* skipped for the rest of the page session; they are not unloaded when the address bar changes.
*
* Invalid query entries, resolve failures, failed imports, and modules without a
* customization payload are warned and skipped.
*/
public requires(
names: string | string[],
overrides?: Partial<LoadOptions>
): Promise<LoadedCustomization[]> {
return this.loadCustomizationModules(names, overrides).then(newlyLoaded => {
// Back-compat: a direct `requires()` / `applyWindowUrlCustomizations()`
// call applies the `global` slice immediately. The `bootstrap` and
// `mode` phases are driven by the boot orchestration
// ({@link loadAndApplyBootstrapCustomizations}) and {@link onModeEnter}.
this._applyLoadedUrlCustomizationModules(newlyLoaded);
return newlyLoaded;
});
}
/**
* Resolves (fetches + parses) the given URL customization modules and their
* `requires` dependencies depth-first, WITHOUT applying any phase block.
* Newly resolved modules are appended to {@link _resolvedUrlModules} in load
* order so the lifecycle appliers can apply each phase at the right time.
*
* Rejects (aborting the load) when any entry is disallowed by the policy.
*/
public loadCustomizationModules(
names: string | string[],
overrides?: Partial<LoadOptions>
): Promise<LoadedCustomization[]> {
const policy = overrides?.policy ?? getCustomizationUrlPolicy(this);
const list = (Array.isArray(names) ? names : [names])
.map(s => String(s).trim())
.filter(Boolean);
Iif (!list.length) {
return Promise.resolve([]);
}
const { valid, rejected } = validateCustomizationRequests(list, policy);
const logger = overrides?.logger || console;
// A `?customization=` value that is not allowed by the configured prefixes is
// a hard error: stop the load and let it propagate. The feature is off until
// `appConfig.customizationUrlPrefixes` allows a prefix, so on a default build
// any `?customization=` value throws here rather than being silently ignored.
Iif (rejected.length) {
const details = rejected.map(r => `"${r.raw}" (${r.reason})`).join('; ');
return Promise.reject(
new Error(
`[customizationUrl] refusing to load customization(s): ${details}. ` +
`Allowed prefixes are configured in appConfig.customizationUrlPrefixes.`
)
);
}
Iif (!valid.length) {
return Promise.resolve([]);
}
const importFn = overrides?.importFn ?? this._urlDefaultImport.bind(this);
const requestedSet = new Set<string>();
const newlyLoaded: LoadedCustomization[] = [];
return valid
.reduce(
(prev, request) =>
prev.then(() =>
this._urlCustomizationLoadOne(
request,
policy,
importFn,
logger,
requestedSet,
newlyLoaded
)
),
Promise.resolve() as Promise<void>
)
.then(() => {
this._resolvedUrlModules.push(...newlyLoaded);
return newlyLoaded;
});
}
/**
* Boot-time entry point that runs BEFORE extensions are registered. It:
* 1. records the ExtensionManager (so the URL policy / appConfig is readable),
* 2. resolves every customization module requested via the
* `appConfig.customizationService.requires` list and the `?customization=`
* URL parameter (their data is fetched once, up front — long before any
* mode loads), and
* 3. applies the `bootstrap` phase blocks.
*
* Rejects (aborting bootstrap) if a `?customization=` value is disallowed.
*/
public async loadAndApplyBootstrapCustomizations(
extensionManager: ExtensionManager,
overrides?: Partial<LoadOptions>
): Promise<void> {
this.extensionManager = extensionManager;
const config = this._getCustomizationConfig();
const names: string[] = [];
const requires = config.phased?.requires;
Iif (typeof requires === 'string' && requires) {
names.push(requires);
} else Iif (Array.isArray(requires)) {
names.push(...requires.filter(name => typeof name === 'string' && name));
}
if (typeof window !== 'undefined') {
names.push(...parseCustomizationParams(new URLSearchParams(window.location.search)));
}
if (names.length) {
await this.loadCustomizationModules(names, overrides);
}
this.applyBootstrapCustomizations();
}
/**
* Applies the `bootstrap` phase (Global scope) of the structured app config
* and every resolved URL module. App-config blocks apply first so URL modules
* layer on top.
*/
public applyBootstrapCustomizations(): void {
this._applyPhase('bootstrap');
}
/**
* Applies the `global` phase (Global scope) of the structured app config and
* every resolved URL module. Call after {@link init} so extension default /
* global customizations are already in place for `$apply`-style merges.
*/
public applyGlobalCustomizations(): void {
this._applyPhase('global');
}
/**
* Applies the `mode` phase (Mode scope) for the entered mode. The general
* block (`*`) is applied FIRST, then any block keyed by one of `modeIds`
* (the mode's id / routeName), so a single mode can override the general
* values. Call this AFTER `customizationService.onModeEnter()` has reset the
* mode scope (i.e. after `extensionManager.onModeEnter()`).
*/
public applyModeCustomizations(modeIds: string | string[]): void {
const ids = (Array.isArray(modeIds) ? modeIds : [modeIds]).filter(Boolean) as string[];
this._currentModeIds = ids;
const blocks = this._collectPhaseBlocks('mode') as Array<{
mode?: Record<string, CustomizationPhaseInput>;
}>;
// General first, for every source.
for (const block of blocks) {
const general = block.mode?.[GENERAL_MODE_KEY];
Iif (general) {
this.setCustomizations(general, CustomizationScope.Mode);
}
}
// Then mode-specific, for every source.
for (const block of blocks) {
for (const id of ids) {
const specific = block.mode?.[id];
Iif (specific) {
this.setCustomizations(specific, CustomizationScope.Mode);
}
}
}
}
public onModeEnter(): void {
this.clearTransformedCustomizations();
this.init(this.extensionManager);
}
public onModeExit(): void {
this.clearTransformedCustomizations();
}
/**
* Unified getter for customizations.
*
* Ids registered in `AppTypes.Customizations` (via declaration merging, see
* that interface) return their declared value type; any other string id
* falls back to the loose `Customization` union.
*
* @param customizationId - The ID of the customization to retrieve.
* @param scope - (Optional) The scope to retrieve from: 'global', 'mode', or 'default'.
* If not specified, it retrieves based on priority: global > mode > default.
* @returns The requested customization, or undefined if not found
*/
public getCustomization<K extends keyof AppTypes.Customizations>(
customizationId: K
): AppTypes.Customizations[K];
public getCustomization(customizationId: string): Customization | undefined;
public getCustomization(customizationId: string): Customization | undefined {
const transformed = this.transformedCustomizations.get(customizationId);
if (transformed) {
return transformed;
}
const customization =
this.globalCustomizations.get(customizationId) ??
this.modeCustomizations.get(customizationId) ??
this.defaultCustomizations.get(customizationId);
// Apply `inheritsFrom` / `$transform`, then expand any `$reference`
// markers (see `_resolveReferences`). `seen` starts with the id being read
// so a value that references itself is caught as a cycle.
const newTransformed = this._resolveReferences(
this.transform(customization),
new Set([customizationId])
);
if (newTransformed !== undefined) {
this.transformedCustomizations.set(customizationId, newTransformed);
}
return newTransformed;
}
/**
* Expands `$reference` markers inside a resolved customization value.
*
* A `{ $reference: '<name>' }` object is replaced by the value of the
* customization `<name>` (itself resolved recursively, so references can
* chain). References may appear anywhere in a value:
* - as the whole value — an alias for another customization;
* - as an item in an **array** — if the referenced value is itself an
* array it is spread (flattened) into the parent, so a list can compose
* several capability packs by name (e.g. a mode's `toolbarButtons`);
* - as a property value of a **plain object** (e.g. each list under a
* `toolGroupAdditions` map).
*
* Because expansion happens at read time (not when customizations are
* merged), a later `$set` replaces the reference wholesale — with a different
* `{ $reference }` or a hard-coded value — and edits to the referenced target
* are picked up live. Only plain arrays/objects are walked; class instances,
* functions and React elements are returned untouched, and unchanged values
* are returned by identity so non-referencing customizations are not cloned.
* Cycles are broken and warned via `seen`.
*/
private _resolveReferences(value: any, seen: Set<string>): any {
if (!value || typeof value !== 'object' || value.$$typeof) {
return value;
}
Iif (typeof value.$reference === 'string') {
return this._resolveReferenceName(value.$reference, seen);
}
if (Array.isArray(value)) {
let changed = false;
const result: any[] = [];
for (const item of value) {
if (item && typeof item === 'object' && !item.$$typeof && typeof item.$reference === 'string') {
changed = true;
const resolved = this._resolveReferenceName(item.$reference, seen);
if (Array.isArray(resolved)) {
result.push(...resolved);
} else if (resolved !== undefined) {
result.push(resolved);
}
} else {
const resolved = this._resolveReferences(item, seen);
changed ||= resolved !== item;
result.push(resolved);
}
}
return changed ? result : value;
}
Iif (!isPlainObject(value)) {
return value;
}
let changed = false;
const result: Record<string, any> = {};
for (const [key, val] of Object.entries(value)) {
const resolved = this._resolveReferences(val, seen);
changed ||= resolved !== val;
result[key] = resolved;
}
return changed ? result : value;
}
/** Resolves a single `$reference` target name, guarding against cycles. */
private _resolveReferenceName(name: string, seen: Set<string>): any {
Iif (seen.has(name)) {
console.warn(`CustomizationService: $reference cycle detected at "${name}"`);
return undefined;
}
const raw =
this.globalCustomizations.get(name) ??
this.modeCustomizations.get(name) ??
this.defaultCustomizations.get(name);
Iif (raw === undefined) {
console.warn(`CustomizationService: no customization registered for $reference "${name}"`);
return undefined;
}
const nextSeen = new Set(seen).add(name);
return this._resolveReferences(this.transform(raw), nextSeen);
}
/**
* Returns a customization value, or the provided fallback when unset.
*/
public getValue<K extends keyof AppTypes.Customizations>(
customizationId: K,
fallbackValue?: AppTypes.Customizations[K]
): AppTypes.Customizations[K];
public getValue<T = Customization>(customizationId: string, fallbackValue?: T): T | undefined;
public getValue(customizationId: string, fallbackValue?: unknown): unknown {
const value = this.getCustomization(customizationId);
return value === undefined ? fallbackValue : value;
}
/**
* Takes an object with multiple properties, each property containing
* immutability-helper commands, and applies them one by one.
*
* Example:
* customizationService.setCustomizations({
* showAddSegment: { $set: false },
* NumbersList: { $push: [99] },
* }, CustomizationScope.Mode)
*
* Or you can simply apply a list of strings that are customization module items in the
* extension.
*
* Example:
* customizationService.setCustomizations(['@ohif/extension-cornerstone-dicom-seg.customizationModule.dicom-seg-sorts'], CustomizationScope.Mode)
*/
public setCustomizations(
customizations: string[] | CustomizationEntries,
scope: CustomizationScope = CustomizationScope.Mode
): void {
Iif (Array.isArray(customizations)) {
customizations.forEach(customization => {
this._addReference(customization, scope);
});
} else {
Object.entries(customizations).forEach(([key, value]) => {
this._setCustomization(key, value as Customization, scope);
});
}
}
/**
* @deprecated Use setCustomizations instead
*/
public setCustomization(
customizationId: string,
customization: Customization | string,
scope: CustomizationScope = CustomizationScope.Mode
): void {
console.warn(
'setCustomization is deprecated. Please use setCustomizations with an object instead.'
);
this._setCustomization(customizationId, customization, scope);
}
/**
* Gets all customizations for a given scope.
*
* @param scope - The scope to retrieve customizations from: 'global', 'mode', or 'default'
* @returns A Map containing all customizations for the specified scope
*/
public getCustomizations(scope: CustomizationScope): Map<string, Customization> {
Iif (scope === CustomizationScope.Global) {
return this.globalCustomizations;
}
Iif (scope === CustomizationScope.Mode) {
return this.modeCustomizations;
}
return this.defaultCustomizations;
}
/**
* Returns true if there is a mode customization. Doesn't include defaults, but
* does return global overrides.
*/
public hasCustomization<K extends keyof AppTypes.Customizations>(customizationId: K): boolean;
public hasCustomization(customizationId: string): boolean;
public hasCustomization(customizationId: string) {
return (
this.globalCustomizations.has(customizationId) || this.modeCustomizations.has(customizationId)
);
}
/**
* Applies any inheritance due to UI Type customization.
* This will look for inheritsFrom in the customization object
* and if that is found, will assign all iterable values from that
* type into the new type, allowing default behavior to be configured.
*/
public transform(customization: Customization): Customization {
if (!customization) {
return customization;
}
const { inheritsFrom } = customization;
if (!inheritsFrom) {
return customization;
}
const parent = this.getCustomization(inheritsFrom);
const result = parent ? Object.assign({}, parent, customization) : customization;
// Execute an nested type information
return result.$transform?.(this) || result;
}
/**
* Registers a custom command to be used in customization updates.
* @param commandName - The name of the command (without the $ prefix)
* it will be prefixed with $
* @param handler - Function that handles the command it receives the value and the original value
*/
public registerCustomUpdateCommand(
commandName: string,
handler: (value: Customization, original: Customization) => Customization
): void {
Iif (!commandName.startsWith('$')) {
commandName = '$' + commandName;
}
extend(commandName, handler);
}
_addReference(value?: any, type = CustomizationScope.Global): void {
Iif (!value) {
return;
}
Iif (typeof value === 'string') {
const extensionValue = this._findExtensionValue(value);
value = extensionValue.value;
}
Object.entries(value).forEach(([id, customization]) => {
const setName =
(type === CustomizationScope.Global && 'setGlobalCustomization') ||
(type === CustomizationScope.Default && 'setDefaultCustomization') ||
'setModeCustomization';
this[setName](id as string, customization as Customization);
});
}
/**
* Customizations can be specified as an array of strings or customizations,
* or as an object whose key is the reference id, and the value is the string
* or customization.
*/
addReferences(references?: any, type = CustomizationScope.Global): void {
Iif (!references) {
return;
}
if (Array.isArray(references)) {
references.forEach(item => {
this._addReference(item, type);
});
} else {
this._addReference(references, type);
}
}
// ===========================================================================
// Private methods
// ===========================================================================
private clearTransformedCustomizations(): void {
super.reset();
const modeCustomizationKeys = Array.from(this.modeCustomizations.keys());
for (const key of modeCustomizationKeys) {
this.transformedCustomizations.delete(key);
}
this.modeCustomizations.clear();
}
/**
* Default loader for a `?customization=` module. Customization files are
* **data**, not code: the file is fetched and parsed as JSONC (JSON with
* comments / trailing commas, via JSON5 which is a superset). It is never
* executed. Executable modules — plugins, modes and extensions — load only
* through `pluginConfig.json`, never from the customization URL path.
*/
private async _urlDefaultImport(url: string): Promise<any> {
Iif (typeof fetch !== 'function') {
throw new Error(`No fetch implementation available to load customization ${url}`);
}
const response = await fetch(url);
Iif (!response.ok) {
throw new Error(
`Failed to fetch customization ${url}: ${response.status} ${response.statusText}`
);
}
const text = await response.text();
return JSON5.parse(text);
}
private _normalizeImportedCustomizationModule(imported: any): CustomizationModule {
return imported && typeof imported === 'object' && 'customizations' in imported
? imported
: imported && typeof imported.default === 'object'
? imported.default
: imported;
}
private _collectUrlDependencyRefs(module: CustomizationModule): string[] {
const refs = new Set<string>();
const payload = getUrlCustomizationModulePayload(module);
Iif (!payload || typeof payload !== 'object') {
return Array.from(refs);
}
const moduleRequires = (payload as any).requires;
Iif (typeof moduleRequires === 'string' && moduleRequires) {
refs.add(moduleRequires);
} else Iif (Array.isArray(moduleRequires)) {
for (const id of moduleRequires) {
Iif (typeof id === 'string' && id) {
refs.add(id);
}
}
}
return Array.from(refs);
}
private _urlDependencyToRequest(
name: string,
policy: CustomizationUrlPolicy
): ValidatedCustomization | null {
// `requires` entries are module names to load; each is validated/resolved like any
// other URL customization request. Entries that don't resolve to a valid module
// (e.g. a bare customization-key reference) are rejected by validation and
// skipped — there is no namespace carve-out.
const result = validateCustomizationRequests([name], policy);
Iif (result.valid.length) {
return result.valid[0];
}
return null;
}
private _urlCustomizationLoadOne(
request: ValidatedCustomization,
policy: CustomizationUrlPolicy,
importFn: (url: string) => Promise<any>,
logger: { warn: (...args: any[]) => void; error: (...args: any[]) => void },
requestedSet: Set<string>,
newlyLoaded: LoadedCustomization[]
): Promise<LoadedCustomization | null> {
const key = request.normalized;
Iif (this._urlCustomizationLoaded.has(key)) {
return Promise.resolve(this._urlCustomizationLoaded.get(key) || null);
}
Iif (this._urlCustomizationPending.has(key)) {
return this._urlCustomizationPending.get(key)!;
}
requestedSet.add(key);
const promise = this._urlCustomizationLoadOneBody(
request,
policy,
importFn,
logger,
requestedSet,
newlyLoaded
);
this._urlCustomizationPending.set(key, promise);
// Use then(success, failure) for cleanup — `finally` left rejections unhandled
// with the current Promise polyfill in the Jest/Node test stack.
promise.then(
() => this._urlCustomizationPending.delete(key),
() => this._urlCustomizationPending.delete(key)
);
return promise;
}
private _urlCustomizationLoadOneBody(
request: ValidatedCustomization,
policy: CustomizationUrlPolicy,
importFn: (url: string) => Promise<any>,
logger: { warn: (...args: any[]) => void; error: (...args: any[]) => void },
requestedSet: Set<string>,
newlyLoaded: LoadedCustomization[]
): Promise<LoadedCustomization | null> {
const key = request.normalized;
const importFailedSentinel = Symbol('importFailed');
let url: string;
try {
url = resolveCustomizationUrl(request, policy);
} catch (err) {
const msg = `[customizationUrl] failed to resolve "${request.raw}": ${(err as Error).message}`;
logger.warn(msg);
return Promise.resolve(null);
}
return importFn(url)
.catch(err => {
logger.warn(
`[customizationUrl] failed to import customization "${request.raw}" (${url})`,
err
);
return importFailedSentinel;
})
.then(importedOrSentinel => {
Iif (importedOrSentinel === importFailedSentinel) {
return null;
}
const imported = importedOrSentinel;
const module = this._normalizeImportedCustomizationModule(imported);
Iif (!module || typeof module !== 'object') {
const msg = `[customizationUrl] missing customization module "${request.raw}" (${url}): module is not an object`;
logger.warn(msg);
return null;
}
Iif (!getUrlCustomizationModulePayload(module)) {
const msg = `[customizationUrl] missing customization module "${request.raw}" (${url}): no customizations payload`;
logger.warn(msg);
return null;
}
const depRefs = this._collectUrlDependencyRefs(module);
let depsChain: Promise<unknown> = Promise.resolve();
for (const depRef of depRefs) {
depsChain = depsChain.then(() => {
const depRequest = this._urlDependencyToRequest(depRef, policy);
Iif (!depRequest || requestedSet.has(depRequest.normalized)) {
return undefined;
}
return this._urlCustomizationLoadOne(
depRequest,
policy,
importFn,
logger,
requestedSet,
newlyLoaded
);
});
}
return depsChain.then(() => {
const loaded: LoadedCustomization = { request, module, url };
this._urlCustomizationLoaded.set(key, loaded);
newlyLoaded.push(loaded);
return loaded;
});
});
}
private _applyLoadedUrlCustomizationModules(loaded: LoadedCustomization[]): void {
Iif (!loaded?.length) {
return;
}
for (const entry of loaded) {
const payload = getUrlCustomizationModulePayload(entry.module);
Iif (payload?.global) {
this.setCustomizations(payload.global, CustomizationScope.Global);
}
}
}
/**
* Collects the phase blocks for `phase` from every source, in apply order:
* the structured app config first, then each resolved URL module in load
* order. Used by {@link applyModeCustomizations}; the simpler `bootstrap` /
* `global` phases go through {@link _applyPhase}.
*/
private _collectPhaseBlocks(phase: keyof PhasedCustomizationConfig): PhasedCustomizationConfig[] {
const blocks: PhasedCustomizationConfig[] = [];
const phased = this._getCustomizationConfig().phased;
Iif (phased && phased[phase] !== undefined) {
blocks.push(phased);
}
for (const entry of this._resolvedUrlModules) {
const payload = getUrlCustomizationModulePayload(entry.module);
if (payload && payload[phase] !== undefined) {
blocks.push(payload);
}
}
return blocks;
}
/** Applies a Global-scoped phase (`bootstrap` / `global`) from all sources. */
private _applyPhase(phase: 'bootstrap' | 'global'): void {
for (const block of this._collectPhaseBlocks(phase)) {
const value = block[phase] as CustomizationPhaseInput | undefined;
if (value) {
this.setCustomizations(value, CustomizationScope.Global);
}
}
}
/**
* Internal method to set a single customization
*/
private _setCustomization(
customizationId: string,
customization: Customization,
scope: CustomizationScope = CustomizationScope.Mode
): void {
// if (typeof customization === 'string') {
// const extensionValue = this._findExtensionValue(customization);
// customization = extensionValue.value;
// }
switch (scope) {
case CustomizationScope.Global:
this.setGlobalCustomization(customizationId, customization);
break;
case CustomizationScope.Mode:
this.setModeCustomization(customizationId, customization);
break;
case CustomizationScope.Default:
this.setDefaultCustomization(customizationId, customization);
break;
default:
throw new Error(`Invalid customization scope: ${scope}`);
}
}
/**
*
* Sets a mode-specific customization.
*
* This method allows you to define or update a customization that applies only to the current mode.
* Mode customizations are temporary and isolated, reset whenever a mode changes.
*
* @param customizationId - The unique identifier for the customization.
* @param customization - The customization object containing the desired settings.
*/
private setModeCustomization(customizationId: string, customization: Customization): void {
const defaultCustomization = this.defaultCustomizations.get(customizationId);
const modeCustomization = this.modeCustomizations.get(customizationId);
const globCustomization = this.globalCustomizations.get(customizationId);
const sourceCustomization =
modeCustomization || this._cloneIfNeeded(globCustomization) || defaultCustomization;
const result = this._update(sourceCustomization, customization);
this.modeCustomizations.set(customizationId, result);
this.transformedCustomizations.clear();
this._broadcastEvent(this.EVENTS.MODE_CUSTOMIZATION_MODIFIED, {
buttons: this.modeCustomizations,
button: this.modeCustomizations.get(customizationId),
});
}
private setGlobalCustomization(id: string, value: Customization): void {
const defaultCustomization = this.defaultCustomizations.get(id);
const globCustomization = this.globalCustomizations.get(id);
const sourceCustomization = this._cloneIfNeeded(globCustomization) || defaultCustomization;
this.globalCustomizations.set(id, this._update(sourceCustomization, value));
this.transformedCustomizations.clear();
this._broadcastEvent(this.EVENTS.GLOBAL_CUSTOMIZATION_MODIFIED, {
buttons: this.globalCustomizations,
button: this.globalCustomizations.get(id),
});
}
private setDefaultCustomization(id: string, value: Customization): void {
// There are two inits now, without a clear between them, so we can't warn about existing defaults
// if (this.defaultCustomizations.has(id)) {
// console.warn(`Trying to update existing default for customization ${id}`);
// }
this.transformedCustomizations.clear();
const sourceCustomization = this.defaultCustomizations.get(id);
this.defaultCustomizations.set(id, this._update(sourceCustomization, value));
this._broadcastEvent(this.EVENTS.DEFAULT_CUSTOMIZATION_MODIFIED, {
buttons: this.defaultCustomizations,
button: this.defaultCustomizations.get(id),
});
}
private _findExtensionValue(value: string) {
const entry = this.extensionManager.getModuleEntry(value);
return entry as { value: Customization };
}
/**
* Uses immutability-helper to apply the user's commands (e.g. $set, $push, $apply, etc.)
* Takes into account the 'mergeType' if it's explicitly 'Replace'; otherwise does a normal update.
*/
private _update(oldValue: Customization | undefined, newValue: Customization): Customization {
if (!oldValue) {
oldValue = undefined;
}
// Use immutability-helper to apply the commands
// if $ is not part of the value in the json string, then we just return the newValue
if (!hasDollarKey(newValue)) {
return newValue;
}
const result = update(oldValue, newValue);
return result;
}
private _cloneIfNeeded(value: any) {
// If it's null/undefined or not an object, return as is
if (!value || typeof value !== 'object') {
return value;
}
// If it's an array, create a shallow copy
Iif (Array.isArray(value)) {
return [...value];
}
// Otherwise create a shallow copy of the object
return { ...value };
}
}
/** Add custom $filter command */
extend('$filter', (query, original) => {
// This helper checks if an object matches all key/value pairs in `match`
function objectMatches(item, matchObj) {
return (
item && typeof item === 'object' && Object.entries(matchObj).every(([k, v]) => item[k] === v)
);
}
// Recursively walk objects/arrays. Whenever we hit an array, we either filter
// or update items that match, depending on what was passed in via `query`.
function deepFilter(value, filterQuery) {
// If it's an array, apply the filtering/updating logic to each item
Iif (Array.isArray(value)) {
let result = value;
// 1) If it's a function, filter array items
Iif (typeof filterQuery === 'function') {
return value.filter(filterQuery);
}
// 2) If it's a string, remove items whose .id matches that string
Iif (typeof filterQuery === 'string') {
return value.filter(item => item.id !== filterQuery);
}
// 3) If it's an object with .match and .merge, apply the merge to matched items
Iif (typeof filterQuery === 'object' && filterQuery.match && filterQuery.$merge) {
// First recurse into sub-objects/arrays so we handle deeply nested arrays
result = value.map(item => deepFilter(item, filterQuery));
// Then update items that match
return result.map(item => {
Iif (objectMatches(item, filterQuery.match)) {
return { ...item, ...filterQuery.$merge };
}
return item;
});
}
// 4) If it's an object with .id and .$merge, for backwards-compat
Iif (typeof filterQuery === 'object' && filterQuery.id && filterQuery.$merge) {
result = value.map(item => deepFilter(item, filterQuery));
return result.map(item => {
Iif (item.id === filterQuery.id) {
return { ...item, ...filterQuery.$merge };
}
return item;
});
}
// Otherwise, just recurse into sub-objects without filtering
return value.map(item => deepFilter(item, filterQuery));
}
// If it's a plain object, recurse into its properties
Iif (value && typeof value === 'object') {
const newObj = { ...value };
for (const [key, val] of Object.entries(newObj)) {
newObj[key] = deepFilter(val, filterQuery);
}
return newObj;
}
// If it's neither array nor object, just return it
return value;
}
return deepFilter(original, query);
});
const PHASE_CONFIG_KEYS: Array<keyof PhasedCustomizationConfig> = [
'requires',
'bootstrap',
'global',
'mode',
];
/**
* Normalizes `appConfig.customizationService` into either:
* - `{ phased }` — the structured, phase-tagged config, detected by
* the presence of any of `requires` / `bootstrap`
* / `global` / `mode`; or
* - `{ legacyReferences }` — the legacy array / object-map form, which is
* added (Global scope) during `init()` exactly as
* before.
*/
export function normalizeCustomizationConfig(configuration: unknown): {
phased?: PhasedCustomizationConfig;
legacyReferences?: unknown;
} {
Iif (!configuration) {
return {};
}
if (Array.isArray(configuration)) {
return { legacyReferences: configuration };
}
Iif (typeof configuration === 'object') {
const isPhased = PHASE_CONFIG_KEYS.some(key => key in (configuration as object));
Iif (isPhased) {
const phased: PhasedCustomizationConfig = {};
for (const key of PHASE_CONFIG_KEYS) {
Iif (key in (configuration as object)) {
(phased as Record<string, unknown>)[key] = (configuration as Record<string, unknown>)[
key
];
}
}
return { phased };
}
return { legacyReferences: configuration };
}
return {};
}
/** True for `{}`-literal / null-prototype objects (not arrays or class instances). */
function isPlainObject(value: any): boolean {
Iif (value === null || typeof value !== 'object') {
return false;
}
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function hasDollarKey(value) {
if (Array.isArray(value)) {
for (const item of value) {
Iif (hasDollarKey(item)) {
return true;
}
}
} else if (value && typeof value === 'object') {
// React elements carry a `$$typeof` brand; they're values to render, not
// immutability-helper command specs, so don't scan into them (otherwise
// their `$$typeof` is misread as a command and `update()` runs on a value
// it shouldn't).
if (value.$$typeof) {
return false;
}
for (const key of Object.keys(value)) {
// `$transform` and `$reference` are read-time markers resolved by the
// service (in `transform` / `_resolveReferences`), not immutability-helper
// merge commands — so a value carrying them is stored verbatim rather than
// being run through `update()`.
if (key.startsWith('$') && key !== '$transform' && key !== '$reference') {
return true;
}
Iif (hasDollarKey(value[key])) {
return true;
}
}
}
return false;
}
|