@egen-civitas/esm-dynamic-loading 1.0.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.
package/README.md ADDED
@@ -0,0 +1,4 @@
1
+ # egen-esm-dynamic-loading
2
+
3
+ egen-esm-dynamic-loading provides functions for dynamically loading JS files using Webpack Module Federation
4
+ dynamic remotes.
@@ -0,0 +1,53 @@
1
+ import { type ImportMap } from '@egen-civitas/esm-globals';
2
+ /**
3
+ * @internal
4
+ *
5
+ * Transforms an ESM module name to a valid JS identifier
6
+ *
7
+ * @param name the name of a module
8
+ * @returns An opaque, equivalent JS identifier for the module
9
+ */
10
+ export declare function slugify(name: string): string;
11
+ /**
12
+ * Loads the named export from a named package. This might be used like:
13
+ *
14
+ * ```js
15
+ * const { someComponent } = importDynamic("@egen-civitas/esm-template-app")
16
+ * ```
17
+ *
18
+ * @param jsPackage The package to load the export from.
19
+ * @param share Indicates the name of the shared module; this is an advanced feature if the package you are loading
20
+ * doesn't use the default Egen shared module name "./start".
21
+ * @param options Additional options to control loading this script.
22
+ * @param options.importMap The import map to use to load the script. This is useful for situations where you're
23
+ * loading multiple scripts at a time, since it allows the calling code to supply an importMap, saving multiple
24
+ * calls to `getCurrentImportMap()`.
25
+ * @param options.maxLoadingTime A positive integer representing the maximum number of milliseconds to wait for the
26
+ * script to load before the promise returned from this function will be rejected. Defaults to 600,000 milliseconds,
27
+ * i.e., 10 minutes.
28
+ */
29
+ export declare function importDynamic<T = any>(jsPackage: string, share?: string, options?: {
30
+ importMap?: ImportMap;
31
+ maxLoadingTime?: number;
32
+ }): Promise<T>;
33
+ /**
34
+ * @internal
35
+ *
36
+ * This internal method is used to ensure that the script belonging
37
+ * to the given package is loaded and added to the head.
38
+ *
39
+ * @param jsPackage The package to load
40
+ * @param importMap The import map to use for loading this package.
41
+ * The main reason for specifying this is to avoid needing to call
42
+ * `getCurrentPageMap()` for every script when bulk loading.
43
+ */
44
+ export declare function preloadImport(jsPackage: string, importMap?: ImportMap): Promise<unknown>;
45
+ /**
46
+ * @internal
47
+ *
48
+ * Used to load the current import map.
49
+ *
50
+ * @returns The current import map.
51
+ */
52
+ export declare function getCurrentImportMap(): Promise<ImportMap>;
53
+ //# sourceMappingURL=dynamic-loading.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dynamic-loading.d.ts","sourceRoot":"","sources":["../src/dynamic-loading.ts"],"names":[],"mappings":"AAEA,OAAO,EAAsB,KAAK,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAI/E;;;;;;;GAOG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,UAEnC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,aAAa,CAAC,CAAC,GAAG,GAAG,EACzC,SAAS,EAAE,MAAM,EACjB,KAAK,GAAE,MAAkB,EACzB,OAAO,CAAC,EAAE;IACR,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,GACA,OAAO,CAAC,CAAC,CAAC,CAyCZ;AAuBD;;;;;;;;;;GAUG;AACH,wBAAsB,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,SAAS,oBAoD3E;AAED;;;;;;GAMG;AACH,wBAAsB,mBAAmB,uBAExC"}
@@ -0,0 +1,221 @@
1
+ /** @module @category Dynamic Loading */ 'use strict';
2
+ import { dispatchToastShown } from "@egen-civitas/esm-globals";
3
+ import { getCoreTranslation } from "@egen-civitas/esm-translations";
4
+ import { getCurrentPageMap, getImportMapOverrideMap, resetImportMapOverrides } from "./import-maps.js";
5
+ /**
6
+ * @internal
7
+ *
8
+ * Transforms an ESM module name to a valid JS identifier
9
+ *
10
+ * @param name the name of a module
11
+ * @returns An opaque, equivalent JS identifier for the module
12
+ */ export function slugify(name) {
13
+ return name.replace(/[\/\-@]/g, '_');
14
+ }
15
+ /**
16
+ * Loads the named export from a named package. This might be used like:
17
+ *
18
+ * ```js
19
+ * const { someComponent } = importDynamic("@egen-civitas/esm-template-app")
20
+ * ```
21
+ *
22
+ * @param jsPackage The package to load the export from.
23
+ * @param share Indicates the name of the shared module; this is an advanced feature if the package you are loading
24
+ * doesn't use the default Egen shared module name "./start".
25
+ * @param options Additional options to control loading this script.
26
+ * @param options.importMap The import map to use to load the script. This is useful for situations where you're
27
+ * loading multiple scripts at a time, since it allows the calling code to supply an importMap, saving multiple
28
+ * calls to `getCurrentImportMap()`.
29
+ * @param options.maxLoadingTime A positive integer representing the maximum number of milliseconds to wait for the
30
+ * script to load before the promise returned from this function will be rejected. Defaults to 600,000 milliseconds,
31
+ * i.e., 10 minutes.
32
+ */ export async function importDynamic(jsPackage, share = './start', options) {
33
+ // default to 10 minutes
34
+ const maxLoadingTime = !options?.maxLoadingTime || options.maxLoadingTime <= 0 ? 600000 : options.maxLoadingTime;
35
+ let timeout = undefined;
36
+ await Promise.race([
37
+ preloadImport(jsPackage, options?.importMap),
38
+ new Promise((_, reject)=>{
39
+ timeout = setTimeout(()=>{
40
+ reject(new Error(`Could not resolve requested script, ${jsPackage}, within ${humanReadableMs(maxLoadingTime)}.`));
41
+ }, maxLoadingTime);
42
+ })
43
+ ]);
44
+ if (timeout) {
45
+ clearTimeout(timeout);
46
+ }
47
+ const jsPackageSlug = slugify(jsPackage);
48
+ const container = window[jsPackageSlug];
49
+ if (!isFederatedModule(container)) {
50
+ const error = `The global variable ${jsPackageSlug} does not refer to a federated module`;
51
+ console.error(error);
52
+ throw new Error(error);
53
+ }
54
+ container.init(__webpack_share_scopes__.default);
55
+ const factory = await container.get(share);
56
+ const module = factory();
57
+ if (!(typeof module === 'object') || module === null) {
58
+ const error = `Container for ${jsPackage} did not return an ESM module as expected`;
59
+ console.error(error);
60
+ throw new Error(error);
61
+ }
62
+ return module;
63
+ }
64
+ /**
65
+ * Utility function to convert milliseconds into human-readable strings with rather absurd
66
+ * levels of precision.
67
+ *
68
+ * @param ms Number of milliseconds
69
+ * @returns A human-readable string useful only for error logging, where we can assume English
70
+ */ function humanReadableMs(ms) {
71
+ if (ms < 1000) {
72
+ return `${ms} milliseconds`;
73
+ } else if (ms < 60000) {
74
+ return `${Math.floor(ms / 1000)} seconds`;
75
+ } else if (ms < 3600000) {
76
+ return `${Math.floor(ms / 60000)} minutes`;
77
+ } else if (ms < 86400000) {
78
+ return `${Math.floor(ms / 3600000)} hours`;
79
+ } else {
80
+ return `${Math.floor(ms / 86400000)} days`;
81
+ }
82
+ }
83
+ /**
84
+ * @internal
85
+ *
86
+ * This internal method is used to ensure that the script belonging
87
+ * to the given package is loaded and added to the head.
88
+ *
89
+ * @param jsPackage The package to load
90
+ * @param importMap The import map to use for loading this package.
91
+ * The main reason for specifying this is to avoid needing to call
92
+ * `getCurrentPageMap()` for every script when bulk loading.
93
+ */ export async function preloadImport(jsPackage, importMap) {
94
+ if (typeof jsPackage !== 'string' || jsPackage.trim().length === 0) {
95
+ const error = 'Attempted to call importDynamic() without supplying a package to load';
96
+ console.error(error);
97
+ throw new Error(error);
98
+ }
99
+ const jsPackageSlug = slugify(jsPackage);
100
+ if (!window[jsPackageSlug]) {
101
+ const activeImportMap = importMap ?? await getCurrentImportMap();
102
+ if (!activeImportMap.imports.hasOwnProperty(jsPackage)) {
103
+ const error = `Could not find the package ${jsPackage} defined in the current importmap`;
104
+ console.error(error);
105
+ throw new Error(error);
106
+ }
107
+ let url = activeImportMap.imports[jsPackage];
108
+ if (url.startsWith('./')) {
109
+ url = window.spaBase + url.substring(1);
110
+ }
111
+ const isOverridden = jsPackage in getImportMapOverrideMap().imports;
112
+ try {
113
+ return await new Promise((resolve, reject)=>{
114
+ loadScript(url, resolve, reject);
115
+ });
116
+ } catch (err) {
117
+ if (isOverridden) {
118
+ dispatchToastShown({
119
+ kind: 'error',
120
+ title: getCoreTranslation('scriptLoadingFailed', 'Error: Script failed to load'),
121
+ description: getCoreTranslation('scriptLoadingError', 'Failed to load overridden script from {{- url}}. Please check that the bundled script is available at the expected URL. Click the button below to reset all import map overrides.', {
122
+ url
123
+ }),
124
+ actionButtonLabel: getCoreTranslation('resetOverrides', 'Reset overrides'),
125
+ onActionButtonClick () {
126
+ resetImportMapOverrides();
127
+ window.location.reload();
128
+ }
129
+ });
130
+ }
131
+ return Promise.reject(err);
132
+ }
133
+ }
134
+ return Promise.resolve();
135
+ }
136
+ /**
137
+ * @internal
138
+ *
139
+ * Used to load the current import map.
140
+ *
141
+ * @returns The current import map.
142
+ */ export async function getCurrentImportMap() {
143
+ return getCurrentPageMap();
144
+ }
145
+ function isFederatedModule(a) {
146
+ return typeof a === 'object' && a !== null && 'init' in a && typeof a['init'] === 'function' && 'get' in a && typeof a['get'] === 'function';
147
+ }
148
+ // internals to track script loading
149
+ // basically, if we're already loading a script, we should wait until the script is loaded
150
+ // we use a global to track this
151
+ const EGEN_SCRIPT_LOADING = Symbol('__egen_script_loading');
152
+ /**
153
+ * Appends a `<script>` to the DOM with the given URL.
154
+ */ function loadScript(url, resolve, reject) {
155
+ const scriptElement = document.head.querySelector(`script[src="${url}"]`);
156
+ let scriptLoading = window[EGEN_SCRIPT_LOADING];
157
+ if (!scriptLoading) {
158
+ scriptLoading = window[EGEN_SCRIPT_LOADING] = new Set([]);
159
+ }
160
+ if (!scriptElement) {
161
+ scriptLoading.add(url);
162
+ const element = document.createElement('script');
163
+ element.src = url;
164
+ element.type = 'text/javascript';
165
+ element.async = true;
166
+ // loadTime() displays an error if a script takes more than 5 seconds to load
167
+ const loadTimeout = setTimeout(()=>{
168
+ console.error(`The script at ${url} did not load within 5 seconds. This may indicate an issue with the imports in the script's entry-point file or with the script's bundler configuration.`);
169
+ }, 5000); // 5 seconds; this is arbitrary
170
+ let loadFn, errFn, finishScriptLoading;
171
+ finishScriptLoading = ()=>{
172
+ clearTimeout(loadTimeout);
173
+ scriptLoading.delete(url);
174
+ if (loadFn) {
175
+ element.removeEventListener('load', loadFn);
176
+ }
177
+ if (errFn) {
178
+ element.removeEventListener('error', errFn);
179
+ }
180
+ };
181
+ loadFn = ()=>{
182
+ finishScriptLoading();
183
+ resolve(null);
184
+ };
185
+ errFn = (ev)=>{
186
+ finishScriptLoading();
187
+ const msg = `Failed to load script from ${url}`;
188
+ console.error(msg, ev);
189
+ reject(ev.message ?? msg);
190
+ };
191
+ element.addEventListener('load', loadFn);
192
+ element.addEventListener('error', errFn);
193
+ document.head.appendChild(element);
194
+ } else {
195
+ if (scriptLoading.has(url)) {
196
+ let loadFn, errFn, finishScriptLoading;
197
+ finishScriptLoading = ()=>{
198
+ if (loadFn) {
199
+ scriptElement.removeEventListener('load', loadFn);
200
+ }
201
+ if (errFn) {
202
+ scriptElement.removeEventListener('error', errFn);
203
+ }
204
+ };
205
+ loadFn = ()=>{
206
+ finishScriptLoading();
207
+ resolve(null);
208
+ };
209
+ // this errFn does not log anything
210
+ errFn = (ev)=>{
211
+ finishScriptLoading();
212
+ reject(ev.message);
213
+ };
214
+ scriptElement.addEventListener('load', loadFn);
215
+ scriptElement.addEventListener('error', errFn);
216
+ } else {
217
+ console.warn(`Script at ${url} already loaded. Not loading it again.`);
218
+ resolve(null);
219
+ }
220
+ }
221
+ }
@@ -0,0 +1,50 @@
1
+ /** @module @category Import Map */
2
+ import type { ImportMap } from '@egen-civitas/esm-globals';
3
+ /**
4
+ * Returns the import map for the current page. In dev mode, this merges
5
+ * the base map with the override snapshot captured at page load.
6
+ */
7
+ export declare function getCurrentPageMap(): Promise<ImportMap>;
8
+ /**
9
+ * Returns the base import map from the DOM without any overrides applied.
10
+ */
11
+ export declare function getImportMapDefaultMap(): Promise<ImportMap>;
12
+ /**
13
+ * Returns what the import map will look like on the next page load, including
14
+ * any overrides that have been added/removed since the page loaded.
15
+ * In production, this is the same as the base map.
16
+ */
17
+ export declare function getImportMapNextPageMap(): Promise<ImportMap>;
18
+ /**
19
+ * Returns the current override map. In production, returns empty imports.
20
+ * @param includeDisabled If true, includes disabled overrides.
21
+ */
22
+ export declare function getImportMapOverrideMap(includeDisabled?: boolean): ImportMap;
23
+ /**
24
+ * Returns the list of module names whose overrides are disabled.
25
+ * In production, returns an empty array.
26
+ */
27
+ export declare function getImportMapDisabledOverrides(): string[];
28
+ /**
29
+ * Returns whether the given module's override is disabled.
30
+ * In production, returns false.
31
+ */
32
+ export declare function isImportMapOverrideDisabled(moduleName: string): boolean;
33
+ /**
34
+ * Adds an import map override. In production, this is a no-op.
35
+ */
36
+ export declare function addImportMapOverride(name: string, url: string): void;
37
+ /**
38
+ * Removes an import map override. In production, this is a no-op.
39
+ */
40
+ export declare function removeImportMapOverride(name: string): void;
41
+ /**
42
+ * Clears all import map overrides. In production, this is a no-op.
43
+ */
44
+ export declare function resetImportMapOverrides(): void;
45
+ /**
46
+ * Re-enables a previously disabled import map override. In production, this is a no-op.
47
+ */
48
+ export declare function enableImportMapOverride(name: string): void;
49
+ export declare function setupImportMapOverrides(): void;
50
+ //# sourceMappingURL=import-maps.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"import-maps.d.ts","sourceRoot":"","sources":["../src/import-maps.ts"],"names":[],"mappings":"AAAA,mCAAmC;AACnC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AA2E3D;;;GAGG;AACH,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,SAAS,CAAC,CAO5D;AAED;;GAEG;AACH,wBAAsB,sBAAsB,IAAI,OAAO,CAAC,SAAS,CAAC,CAEjE;AAED;;;;GAIG;AACH,wBAAsB,uBAAuB,IAAI,OAAO,CAAC,SAAS,CAAC,CAMlE;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,eAAe,CAAC,EAAE,OAAO,GAAG,SAAS,CAmB5E;AAED;;;GAGG;AACH,wBAAgB,6BAA6B,IAAI,MAAM,EAAE,CAiBxD;AAED;;;GAGG;AACH,wBAAgB,2BAA2B,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAKvE;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAWpE;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAiB1D;AAED;;GAEG;AACH,wBAAgB,uBAAuB,IAAI,IAAI,CAmB9C;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAgB1D;AAaD,wBAAgB,uBAAuB,SAWtC"}
@@ -0,0 +1,246 @@
1
+ /** @module @category Import Map */ const OVERRIDE_PREFIX = 'import-map-override:';
2
+ const DISABLED_KEY = 'import-map-overrides-disabled';
3
+ const CHANGE_EVENT = 'import-map-overrides:change';
4
+ // Set by setupImportMapOverrides(); controls whether override functionality is active.
5
+ let devMode = false;
6
+ // Snapshot of overrides at setup time (matches import-map-overrides library behavior:
7
+ // getCurrentPageMap returns the overrides as they were when the page loaded).
8
+ let initialOverrideSnapshot = null;
9
+ /**
10
+ * Reads all `<script type="systemjs-importmap">` tags from the DOM and merges
11
+ * them into a single {@link ImportMap}. Tags with a `src` attribute are fetched;
12
+ * inline tags have their `textContent` parsed as JSON.
13
+ */ async function readBaseMap() {
14
+ const scripts = document.querySelectorAll('script[type="systemjs-importmap"]');
15
+ const maps = [];
16
+ for(let i = 0; i < scripts.length; i++){
17
+ const script = scripts[i];
18
+ try {
19
+ if (script.src) {
20
+ const response = await fetch(script.src);
21
+ maps.push(await response.json());
22
+ } else if (script.textContent) {
23
+ maps.push(JSON.parse(script.textContent));
24
+ }
25
+ } catch (e) {
26
+ console.warn(`[import-maps] Failed to parse import map from script tag at index ${i}`, e);
27
+ }
28
+ }
29
+ return mergeMaps(maps);
30
+ }
31
+ function mergeMaps(maps) {
32
+ const merged = {
33
+ imports: {}
34
+ };
35
+ for (const map of maps){
36
+ if (map?.imports) {
37
+ Object.assign(merged.imports, map.imports);
38
+ }
39
+ }
40
+ return merged;
41
+ }
42
+ /** Returns all `import-map-override:*` entries from localStorage as an {@link ImportMap}. */ function readOverrideMap() {
43
+ const imports = {};
44
+ try {
45
+ const disabled = getImportMapDisabledOverrides();
46
+ for(let i = 0; i < localStorage.length; i++){
47
+ const key = localStorage.key(i);
48
+ if (key?.startsWith(OVERRIDE_PREFIX)) {
49
+ const moduleName = key.slice(OVERRIDE_PREFIX.length);
50
+ if (!disabled.includes(moduleName)) {
51
+ const url = localStorage.getItem(key);
52
+ if (url) {
53
+ imports[moduleName] = url;
54
+ }
55
+ }
56
+ }
57
+ }
58
+ } catch (e) {
59
+ console.warn('[import-maps] Failed to read import-map overrides from localStorage', e);
60
+ }
61
+ return {
62
+ imports
63
+ };
64
+ }
65
+ /**
66
+ * Returns the import map for the current page. In dev mode, this merges
67
+ * the base map with the override snapshot captured at page load.
68
+ */ export async function getCurrentPageMap() {
69
+ const base = await readBaseMap();
70
+ if (!devMode) {
71
+ return base;
72
+ }
73
+ const overrides = initialOverrideSnapshot ?? readOverrideMap();
74
+ return mergeMaps([
75
+ base,
76
+ overrides
77
+ ]);
78
+ }
79
+ /**
80
+ * Returns the base import map from the DOM without any overrides applied.
81
+ */ export async function getImportMapDefaultMap() {
82
+ return readBaseMap();
83
+ }
84
+ /**
85
+ * Returns what the import map will look like on the next page load, including
86
+ * any overrides that have been added/removed since the page loaded.
87
+ * In production, this is the same as the base map.
88
+ */ export async function getImportMapNextPageMap() {
89
+ if (!devMode) {
90
+ return readBaseMap();
91
+ }
92
+ const base = await readBaseMap();
93
+ return mergeMaps([
94
+ base,
95
+ readOverrideMap()
96
+ ]);
97
+ }
98
+ /**
99
+ * Returns the current override map. In production, returns empty imports.
100
+ * @param includeDisabled If true, includes disabled overrides.
101
+ */ export function getImportMapOverrideMap(includeDisabled) {
102
+ if (!devMode) {
103
+ return {
104
+ imports: {}
105
+ };
106
+ }
107
+ if (includeDisabled) {
108
+ const imports = {};
109
+ for(let i = 0; i < localStorage.length; i++){
110
+ const key = localStorage.key(i);
111
+ if (key?.startsWith(OVERRIDE_PREFIX)) {
112
+ const url = localStorage.getItem(key);
113
+ if (url) {
114
+ imports[key.slice(OVERRIDE_PREFIX.length)] = url;
115
+ }
116
+ }
117
+ }
118
+ return {
119
+ imports
120
+ };
121
+ }
122
+ return readOverrideMap();
123
+ }
124
+ /**
125
+ * Returns the list of module names whose overrides are disabled.
126
+ * In production, returns an empty array.
127
+ */ export function getImportMapDisabledOverrides() {
128
+ if (!devMode) {
129
+ return [];
130
+ }
131
+ try {
132
+ const raw = localStorage.getItem(DISABLED_KEY);
133
+ if (raw) {
134
+ const parsed = JSON.parse(raw);
135
+ if (Array.isArray(parsed)) {
136
+ return parsed;
137
+ }
138
+ }
139
+ } catch {
140
+ // ignore malformed data
141
+ }
142
+ return [];
143
+ }
144
+ /**
145
+ * Returns whether the given module's override is disabled.
146
+ * In production, returns false.
147
+ */ export function isImportMapOverrideDisabled(moduleName) {
148
+ if (!devMode) {
149
+ return false;
150
+ }
151
+ return getImportMapDisabledOverrides().includes(moduleName);
152
+ }
153
+ /**
154
+ * Adds an import map override. In production, this is a no-op.
155
+ */ export function addImportMapOverride(name, url) {
156
+ if (!devMode) {
157
+ console.warn('[Security] Import map overrides are disabled in production mode.');
158
+ return;
159
+ }
160
+ try {
161
+ localStorage.setItem(OVERRIDE_PREFIX + name, url);
162
+ window.dispatchEvent(new CustomEvent(CHANGE_EVENT));
163
+ } catch (e) {
164
+ console.warn('[import-maps] Failed to write import-map override to localStorage', e);
165
+ }
166
+ }
167
+ /**
168
+ * Removes an import map override. In production, this is a no-op.
169
+ */ export function removeImportMapOverride(name) {
170
+ if (!devMode) {
171
+ console.warn('[Security] Import map overrides are disabled in production mode.');
172
+ return;
173
+ }
174
+ try {
175
+ localStorage.removeItem(OVERRIDE_PREFIX + name);
176
+ const disabled = getImportMapDisabledOverrides().filter((n)=>n !== name);
177
+ if (disabled.length > 0) {
178
+ localStorage.setItem(DISABLED_KEY, JSON.stringify(disabled));
179
+ } else {
180
+ localStorage.removeItem(DISABLED_KEY);
181
+ }
182
+ window.dispatchEvent(new CustomEvent(CHANGE_EVENT));
183
+ } catch (e) {
184
+ console.warn('[import-maps] Failed to update import-map overrides in localStorage', e);
185
+ }
186
+ }
187
+ /**
188
+ * Clears all import map overrides. In production, this is a no-op.
189
+ */ export function resetImportMapOverrides() {
190
+ if (!devMode) {
191
+ console.warn('[Security] Import map overrides are disabled in production mode.');
192
+ return;
193
+ }
194
+ try {
195
+ const keysToRemove = [];
196
+ for(let i = 0; i < localStorage.length; i++){
197
+ const key = localStorage.key(i);
198
+ if (key?.startsWith(OVERRIDE_PREFIX)) {
199
+ keysToRemove.push(key);
200
+ }
201
+ }
202
+ keysToRemove.forEach((key)=>localStorage.removeItem(key));
203
+ localStorage.removeItem(DISABLED_KEY);
204
+ window.dispatchEvent(new CustomEvent(CHANGE_EVENT));
205
+ } catch (e) {
206
+ console.warn('[import-maps] Failed to clear import-map overrides from localStorage', e);
207
+ }
208
+ }
209
+ /**
210
+ * Re-enables a previously disabled import map override. In production, this is a no-op.
211
+ */ export function enableImportMapOverride(name) {
212
+ if (!devMode) {
213
+ console.warn('[Security] Import map overrides are disabled in production mode.');
214
+ return;
215
+ }
216
+ try {
217
+ const disabled = getImportMapDisabledOverrides().filter((n)=>n !== name);
218
+ if (disabled.length > 0) {
219
+ localStorage.setItem(DISABLED_KEY, JSON.stringify(disabled));
220
+ } else {
221
+ localStorage.removeItem(DISABLED_KEY);
222
+ }
223
+ window.dispatchEvent(new CustomEvent(CHANGE_EVENT));
224
+ } catch (e) {
225
+ console.warn('[import-maps] Failed to update import-map overrides in localStorage', e);
226
+ }
227
+ }
228
+ /**
229
+ * Initializes the import map override system with mode-aware behavior.
230
+ *
231
+ * In production (`window.spaEnv !== 'development'`), mutation functions are
232
+ * no-ops and localStorage overrides are never consulted. In development, the
233
+ * full override workflow is available.
234
+ *
235
+ * Must be called before any code that depends on the import map functions.
236
+ */ let initialized = false;
237
+ export function setupImportMapOverrides() {
238
+ if (initialized) {
239
+ return;
240
+ }
241
+ initialized = true;
242
+ devMode = window.spaEnv === 'development';
243
+ if (devMode) {
244
+ initialOverrideSnapshot = readOverrideMap();
245
+ }
246
+ }
@@ -0,0 +1,4 @@
1
+ export * from './dynamic-loading.js';
2
+ export * from './import-maps.js';
3
+ export * from './route-maps.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./dynamic-loading.js";
2
+ export * from "./import-maps.js";
3
+ export * from "./route-maps.js";
@@ -0,0 +1,2 @@
1
+ export { importDynamic } from './dynamic-loading.js';
2
+ //# sourceMappingURL=public.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"public.d.ts","sourceRoot":"","sources":["../src/public.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC"}
package/dist/public.js ADDED
@@ -0,0 +1 @@
1
+ export { importDynamic } from "./dynamic-loading.js";
@@ -0,0 +1,46 @@
1
+ /** @module @category Route Map */
2
+ import { type EgenAppRoutes, type EgenRoutes } from '@egen-civitas/esm-globals';
3
+ /**
4
+ * Returns the route map for the current page. In dev mode, this merges
5
+ * the base map with the override snapshot captured at page load.
6
+ */
7
+ export declare function getCurrentRouteMap(): Promise<EgenRoutes>;
8
+ /**
9
+ * Returns the base route map from the DOM without any overrides applied.
10
+ */
11
+ export declare function getRouteMapDefaultMap(): Promise<EgenRoutes>;
12
+ /**
13
+ * Returns what the route map will look like on the next page load, including
14
+ * any overrides that have been added/removed since the page loaded.
15
+ * In production, this is the same as the base map.
16
+ */
17
+ export declare function getRouteMapNextPageMap(): Promise<EgenRoutes>;
18
+ /**
19
+ * Returns the current raw override entries from localStorage.
20
+ * In production, returns an empty object.
21
+ */
22
+ export declare function getRouteMapOverrideMap(): Record<string, string>;
23
+ /**
24
+ * Adds a route override. In production, this is a no-op.
25
+ * The app must be reloaded for overrides to take effect.
26
+ *
27
+ * @param moduleName The name of the module the routes are for
28
+ * @param routes Either an {@link EgenAppRoutes} object, a string that represents a JSON
29
+ * version of an {@link EgenAppRoutes} object, or a string or URL that resolves to a
30
+ * JSON document that represents an {@link EgenAppRoutes} object
31
+ */
32
+ export declare function addRouteMapOverride(moduleName: string, routes: EgenAppRoutes | string | URL): void;
33
+ /**
34
+ * Removes a route override. In production, this is a no-op.
35
+ * The app must be reloaded for the removal to take effect.
36
+ *
37
+ * @param moduleName The module to remove the overrides for
38
+ */
39
+ export declare function removeRouteMapOverride(moduleName: string): void;
40
+ /**
41
+ * Clears all route overrides. In production, this is a no-op.
42
+ * The app must be reloaded for the removal to take effect.
43
+ */
44
+ export declare function resetRouteMapOverrides(): void;
45
+ export declare function setupRouteMapOverrides(): Promise<void>;
46
+ //# sourceMappingURL=route-maps.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-maps.d.ts","sourceRoot":"","sources":["../src/route-maps.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,OAAO,EAAiC,KAAK,aAAa,EAAE,KAAK,UAAU,EAAE,MAAM,2BAA2B,CAAC;AA2G/G;;;GAGG;AACH,wBAAsB,kBAAkB,IAAI,OAAO,CAAC,UAAU,CAAC,CAO9D;AAED;;GAEG;AACH,wBAAsB,qBAAqB,IAAI,OAAO,CAAC,UAAU,CAAC,CAEjE;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,IAAI,OAAO,CAAC,UAAU,CAAC,CAMlE;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAoB/D;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,GAAG,MAAM,GAAG,GAAG,QAkC3F;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,MAAM,QAYxD;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,SAmBrC;AAaD,wBAAgB,sBAAsB,IAAI,OAAO,CAAC,IAAI,CAAC,CAgBtD"}
@@ -0,0 +1,252 @@
1
+ /** @module @category Route Map */ import { isEgenAppRoutes, isEgenRoutes } from "@egen-civitas/esm-globals";
2
+ const OVERRIDE_PREFIX = 'egen-routes:';
3
+ const CHANGE_EVENT = 'egen-routes:change';
4
+ // Set by setupRouteMapOverrides(); controls whether override functionality is active.
5
+ let devMode = false;
6
+ // Snapshot of overrides at setup time (mirrors the import-map-overrides pattern:
7
+ // getCurrentRouteMap returns the overrides as they were when the page loaded).
8
+ let initialOverrideSnapshot = null;
9
+ /**
10
+ * Reads all `<script type="egen-routes">` tags from the DOM and merges
11
+ * them into a single {@link EgenRoutes} object. Tags with a `src` attribute
12
+ * are fetched; inline tags have their `textContent` parsed as JSON.
13
+ */ async function readBaseMap() {
14
+ const scripts = document.querySelectorAll("script[type='egen-routes']");
15
+ const maps = [];
16
+ for(let i = 0; i < scripts.length; i++){
17
+ const script = scripts[i];
18
+ try {
19
+ let parsed;
20
+ if (script.src) {
21
+ const response = await fetch(script.src);
22
+ parsed = await response.json();
23
+ } else if (script.textContent) {
24
+ parsed = JSON.parse(script.textContent);
25
+ }
26
+ if (parsed && isEgenRoutes(parsed)) {
27
+ maps.push(parsed);
28
+ }
29
+ } catch (e) {
30
+ console.warn(`[route-maps] Failed to parse routes from script tag at index ${i}`, e);
31
+ }
32
+ }
33
+ return mergeRouteMaps(maps);
34
+ }
35
+ function mergeRouteMaps(maps) {
36
+ const merged = {};
37
+ for (const map of maps){
38
+ if (map && typeof map === 'object') {
39
+ Object.assign(merged, map);
40
+ }
41
+ }
42
+ return merged;
43
+ }
44
+ /**
45
+ * Reads all `egen-routes:*` entries from localStorage as an {@link EgenRoutes}.
46
+ * This is async because URL-valued overrides need to be fetched.
47
+ */ async function readOverrideMap() {
48
+ const result = {};
49
+ try {
50
+ const entries = [];
51
+ for(let i = 0; i < localStorage.length; i++){
52
+ const key = localStorage.key(i);
53
+ if (key?.startsWith(OVERRIDE_PREFIX)) {
54
+ const raw = localStorage.getItem(key);
55
+ if (raw) {
56
+ entries.push({
57
+ moduleName: key.slice(OVERRIDE_PREFIX.length),
58
+ raw
59
+ });
60
+ }
61
+ }
62
+ }
63
+ const settled = await Promise.allSettled(entries.map(async ({ moduleName, raw })=>{
64
+ const parsed = JSON.parse(raw);
65
+ if (isEgenAppRoutes(parsed)) {
66
+ return {
67
+ moduleName,
68
+ routes: parsed
69
+ };
70
+ }
71
+ if (typeof parsed === 'string' && parsed.startsWith('http')) {
72
+ const response = await fetch(parsed);
73
+ const fetched = await response.json();
74
+ if (isEgenAppRoutes(fetched)) {
75
+ return {
76
+ moduleName,
77
+ routes: fetched
78
+ };
79
+ }
80
+ throw new Error(`${parsed} did not resolve to a valid EgenAppRoutes object`);
81
+ }
82
+ throw new Error(`Override for ${moduleName} is neither a valid routes object nor a URL`);
83
+ }));
84
+ for (const entry of settled){
85
+ if (entry.status === 'fulfilled') {
86
+ result[entry.value.moduleName] = entry.value.routes;
87
+ } else {
88
+ console.warn('[route-maps] Failed to load route override', entry.reason);
89
+ }
90
+ }
91
+ } catch (e) {
92
+ console.warn('[route-maps] Failed to read route overrides from localStorage', e);
93
+ }
94
+ return result;
95
+ }
96
+ /**
97
+ * Returns the route map for the current page. In dev mode, this merges
98
+ * the base map with the override snapshot captured at page load.
99
+ */ export async function getCurrentRouteMap() {
100
+ const base = await readBaseMap();
101
+ if (!devMode) {
102
+ return base;
103
+ }
104
+ const overrides = initialOverrideSnapshot ?? await readOverrideMap();
105
+ return mergeRouteMaps([
106
+ base,
107
+ overrides
108
+ ]);
109
+ }
110
+ /**
111
+ * Returns the base route map from the DOM without any overrides applied.
112
+ */ export async function getRouteMapDefaultMap() {
113
+ return readBaseMap();
114
+ }
115
+ /**
116
+ * Returns what the route map will look like on the next page load, including
117
+ * any overrides that have been added/removed since the page loaded.
118
+ * In production, this is the same as the base map.
119
+ */ export async function getRouteMapNextPageMap() {
120
+ if (!devMode) {
121
+ return readBaseMap();
122
+ }
123
+ const base = await readBaseMap();
124
+ return mergeRouteMaps([
125
+ base,
126
+ await readOverrideMap()
127
+ ]);
128
+ }
129
+ /**
130
+ * Returns the current raw override entries from localStorage.
131
+ * In production, returns an empty object.
132
+ */ export function getRouteMapOverrideMap() {
133
+ if (!devMode) {
134
+ return {};
135
+ }
136
+ const result = {};
137
+ try {
138
+ for(let i = 0; i < localStorage.length; i++){
139
+ const key = localStorage.key(i);
140
+ if (key?.startsWith(OVERRIDE_PREFIX)) {
141
+ const value = localStorage.getItem(key);
142
+ if (value) {
143
+ result[key.slice(OVERRIDE_PREFIX.length)] = value;
144
+ }
145
+ }
146
+ }
147
+ } catch (e) {
148
+ console.warn('[route-maps] Failed to read route overrides from localStorage', e);
149
+ }
150
+ return result;
151
+ }
152
+ /**
153
+ * Adds a route override. In production, this is a no-op.
154
+ * The app must be reloaded for overrides to take effect.
155
+ *
156
+ * @param moduleName The name of the module the routes are for
157
+ * @param routes Either an {@link EgenAppRoutes} object, a string that represents a JSON
158
+ * version of an {@link EgenAppRoutes} object, or a string or URL that resolves to a
159
+ * JSON document that represents an {@link EgenAppRoutes} object
160
+ */ export function addRouteMapOverride(moduleName, routes) {
161
+ if (!devMode) {
162
+ console.warn('[Security] Route overrides are disabled outside development mode.');
163
+ return;
164
+ }
165
+ try {
166
+ if (typeof routes === 'string') {
167
+ if (routes.startsWith('http')) {
168
+ localStorage.setItem(OVERRIDE_PREFIX + moduleName, JSON.stringify(routes));
169
+ } else {
170
+ const maybeRoutes = JSON.parse(routes);
171
+ if (isEgenAppRoutes(maybeRoutes)) {
172
+ localStorage.setItem(OVERRIDE_PREFIX + moduleName, JSON.stringify(maybeRoutes));
173
+ } else {
174
+ console.error(`The supplied routes for ${moduleName} is not a valid EgenAppRoutes object`, routes);
175
+ return;
176
+ }
177
+ }
178
+ } else if (routes instanceof URL) {
179
+ localStorage.setItem(OVERRIDE_PREFIX + moduleName, JSON.stringify(routes.toString()));
180
+ } else if (isEgenAppRoutes(routes)) {
181
+ localStorage.setItem(OVERRIDE_PREFIX + moduleName, JSON.stringify(routes));
182
+ } else {
183
+ console.error(`Override for ${moduleName} is not in a valid format. Expected either a Javascript Object, a JSON string of a Javascript object, or a URL`, routes);
184
+ return;
185
+ }
186
+ window.dispatchEvent(new CustomEvent(CHANGE_EVENT));
187
+ } catch (e) {
188
+ console.warn('[route-maps] Failed to write route override to localStorage', e);
189
+ }
190
+ }
191
+ /**
192
+ * Removes a route override. In production, this is a no-op.
193
+ * The app must be reloaded for the removal to take effect.
194
+ *
195
+ * @param moduleName The module to remove the overrides for
196
+ */ export function removeRouteMapOverride(moduleName) {
197
+ if (!devMode) {
198
+ console.warn('[Security] Route overrides are disabled outside development mode.');
199
+ return;
200
+ }
201
+ try {
202
+ localStorage.removeItem(OVERRIDE_PREFIX + moduleName);
203
+ window.dispatchEvent(new CustomEvent(CHANGE_EVENT));
204
+ } catch (e) {
205
+ console.warn('[route-maps] Failed to remove route override from localStorage', e);
206
+ }
207
+ }
208
+ /**
209
+ * Clears all route overrides. In production, this is a no-op.
210
+ * The app must be reloaded for the removal to take effect.
211
+ */ export function resetRouteMapOverrides() {
212
+ if (!devMode) {
213
+ console.warn('[Security] Route overrides are disabled outside development mode.');
214
+ return;
215
+ }
216
+ try {
217
+ const keysToRemove = [];
218
+ for(let i = 0; i < localStorage.length; i++){
219
+ const key = localStorage.key(i);
220
+ if (key?.startsWith(OVERRIDE_PREFIX)) {
221
+ keysToRemove.push(key);
222
+ }
223
+ }
224
+ keysToRemove.forEach((key)=>localStorage.removeItem(key));
225
+ window.dispatchEvent(new CustomEvent(CHANGE_EVENT));
226
+ } catch (e) {
227
+ console.warn('[route-maps] Failed to clear route overrides from localStorage', e);
228
+ }
229
+ }
230
+ /**
231
+ * Initializes the route map override system with mode-aware behavior.
232
+ *
233
+ * In production (`window.spaEnv !== 'development'`), mutation functions are
234
+ * no-ops and localStorage overrides are never consulted. In development, the
235
+ * full override workflow is available.
236
+ *
237
+ * Must be called before any code that depends on the route map functions.
238
+ */ let setupPromise = null;
239
+ export function setupRouteMapOverrides() {
240
+ if (setupPromise) {
241
+ return setupPromise;
242
+ }
243
+ devMode = window.spaEnv === 'development';
244
+ if (devMode) {
245
+ setupPromise = readOverrideMap().then((snapshot)=>{
246
+ initialOverrideSnapshot = snapshot;
247
+ });
248
+ } else {
249
+ setupPromise = Promise.resolve();
250
+ }
251
+ return setupPromise;
252
+ }
package/package.json ADDED
@@ -0,0 +1,75 @@
1
+ {
2
+ "name": "@egen-civitas/esm-dynamic-loading",
3
+ "version": "1.0.0",
4
+ "license": "MPL-2.0",
5
+ "description": "Utilities for dynamically loading code in Egen",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "files": [
9
+ "dist",
10
+ "mock.ts",
11
+ "mock-jest.ts"
12
+ ],
13
+ "module": "dist/index.js",
14
+ "types": "dist/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ },
20
+ "./src/public": {
21
+ "types": "./dist/public.d.ts",
22
+ "default": "./dist/public.js"
23
+ }
24
+ },
25
+ "sideEffects": false,
26
+ "scripts": {
27
+ "test": "cross-env TZ=UTC vitest run --passWithNoTests",
28
+ "test:watch": "cross-env TZ=UTC vitest watch --passWithNoTests",
29
+ "build": "rimraf dist && concurrently \"swc --strip-leading-paths src -d dist\" \"tsc --project tsconfig.build.json\"",
30
+ "build:development": "rimraf dist && concurrently \"swc --strip-leading-paths src -d dist\" \"tsc --project tsconfig.build.json\"",
31
+ "typescript": "tsc --project tsconfig.build.json",
32
+ "lint": "eslint src --ext ts,tsx",
33
+ "coverage": "cross-env TZ=UTC vitest run --coverage --passWithNoTests"
34
+ },
35
+ "keywords": [
36
+ "egen",
37
+ "microfrontends"
38
+ ],
39
+ "directories": {
40
+ "lib": "dist",
41
+ "src": "src"
42
+ },
43
+ "browserslist": [
44
+ "extends browserslist-config-egen"
45
+ ],
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "git+https://github.com/egen-civitas/egen-esm-core.git"
49
+ },
50
+ "bugs": {
51
+ "url": "https://github.com/egen-civitas/egen-esm-core/issues"
52
+ },
53
+ "homepage": "https://github.com/egen-civitas/egen-esm-core#readme",
54
+ "publishConfig": {
55
+ "access": "public"
56
+ },
57
+ "peerDependencies": {
58
+ "@egen-civitas/esm-globals": "^1.0.0",
59
+ "@egen-civitas/esm-translations": "^1.0.0"
60
+ },
61
+ "devDependencies": {
62
+ "@egen-civitas/esm-globals": "^1.0.0",
63
+ "@egen-civitas/esm-translations": "^1.0.0",
64
+ "@swc/cli": "0.8.1",
65
+ "@swc/core": "1.15.21",
66
+ "@vitest/coverage-v8": "^4.1.2",
67
+ "concurrently": "^9.2.1",
68
+ "happy-dom": "^20.6.0",
69
+ "jsdom": "^29.0.2",
70
+ "rimraf": "^6.1.3",
71
+ "single-spa": "^6.0.3",
72
+ "vitest": "^4.1.2",
73
+ "vitest-fetch-mock": "^0.4.5"
74
+ }
75
+ }