@openmrs/esm-dynamic-loading 6.3.1-pre.2965 → 6.3.1-pre.2986

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/.swcrc ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "$schema": "https://swc.rs/schema.json",
3
+ "exclude": [".*\\.test\\..*", "setup-tests\\..*"],
4
+ "module": {
5
+ "type": "es6",
6
+ "resolveFully": true
7
+ },
8
+ "jsc": {
9
+ "parser": {
10
+ "syntax": "typescript",
11
+ "tsx": false
12
+ },
13
+ "target": "es2020",
14
+ "baseUrl": "src"
15
+ }
16
+ }
@@ -1,8 +1,3 @@
1
- asset openmrs-esm-dynamic-loading.js 6.6 KiB [emitted] [minimized] (name: main) 1 related asset
2
- runtime modules 2.47 KiB 4 modules
3
- orphan modules 16.5 KiB [orphan] 1 module
4
- built modules 16.6 KiB [built]
5
- ./src/index.ts + 1 modules 16.6 KiB [built] [code generated]
6
- external "@openmrs/esm-globals" 42 bytes [built] [code generated]
7
- external "@openmrs/esm-translations" 42 bytes [built] [code generated]
8
- webpack 5.88.0 compiled successfully in 9243 ms
1
+ [0] Successfully compiled: 3 files with swc (158.15ms)
2
+ [0] swc --strip-leading-paths src -d dist exited with code 0
3
+ [1] tsc --project tsconfig.build.json exited with code 0
@@ -0,0 +1,52 @@
1
+ import { type ImportMap } from '@openmrs/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("@openmrs/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 OpenMRS 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<void>;
45
+ /**
46
+ * @internal
47
+ *
48
+ * Used to load the current import map
49
+ *
50
+ * @returns The current page map
51
+ */
52
+ export declare function getCurrentImportMap(): Promise<ImportMap>;
@@ -0,0 +1,211 @@
1
+ /** @module @category Dynamic Loading */ 'use strict';
2
+ // hack to make the types defined in esm-globals available here
3
+ import { dispatchToastShown } from "@openmrs/esm-globals";
4
+ import { getCoreTranslation } from "@openmrs/esm-translations";
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("@openmrs/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 OpenMRS 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
+ timeout && clearTimeout(timeout);
45
+ const jsPackageSlug = slugify(jsPackage);
46
+ const container = window[jsPackageSlug];
47
+ if (!isFederatedModule(container)) {
48
+ const error = `The global variable ${jsPackageSlug} does not refer to a federated module`;
49
+ console.error(error);
50
+ throw new Error(error);
51
+ }
52
+ container.init(__webpack_share_scopes__.default);
53
+ const factory = await container.get(share);
54
+ const module = factory();
55
+ if (!(typeof module === 'object') || module === null) {
56
+ const error = `Container for ${jsPackage} did not return an ESM module as expected`;
57
+ console.error(error);
58
+ throw new Error(error);
59
+ }
60
+ return module;
61
+ }
62
+ /**
63
+ * Utility function to convert milliseconds into human-readable strings with rather absurd
64
+ * levels of precision.
65
+ *
66
+ * @param ms Number of milliseconds
67
+ * @returns A human-readable string useful only for error logging, where we can assume English
68
+ */ function humanReadableMs(ms) {
69
+ if (ms < 1000) {
70
+ return `${ms} milliseconds`;
71
+ } else if (ms < 60000) {
72
+ return `${Math.floor(ms / 1000)} seconds`;
73
+ } else if (ms < 3600000) {
74
+ return `${Math.floor(ms / 60000)} minutes`;
75
+ } else if (ms < 86400000) {
76
+ return `${Math.floor(ms / 3600000)} hours`;
77
+ } else {
78
+ return `${Math.floor(ms / 86400000)} days`;
79
+ }
80
+ }
81
+ /**
82
+ * @internal
83
+ *
84
+ * This internal method is used to ensure that the script belonging
85
+ * to the given package is loaded and added to the head.
86
+ *
87
+ * @param jsPackage The package to load
88
+ * @param importMap The import map to use for loading this package.
89
+ * The main reason for specifying this is to avoid needing to call
90
+ * `getCurrentPageMap()` for every script when bulk loading.
91
+ */ export async function preloadImport(jsPackage, importMap) {
92
+ if (typeof jsPackage !== 'string' || jsPackage.trim().length === 0) {
93
+ const error = 'Attempted to call importDynamic() without supplying a package to load';
94
+ console.error(error);
95
+ throw new Error(error);
96
+ }
97
+ const jsPackageSlug = slugify(jsPackage);
98
+ if (!window[jsPackageSlug]) {
99
+ const activeImportMap = importMap ?? await getCurrentImportMap();
100
+ if (!activeImportMap.imports.hasOwnProperty(jsPackage)) {
101
+ const error = `Could not find the package ${jsPackage} defined in the current importmap`;
102
+ console.error(error);
103
+ throw new Error(error);
104
+ }
105
+ let url = activeImportMap.imports[jsPackage];
106
+ if (url.startsWith('./')) {
107
+ url = window.spaBase + url.substring(1);
108
+ }
109
+ const isOverridden = !!window.localStorage.getItem(`import-map-override:${jsPackage}`);
110
+ try {
111
+ return await new Promise((resolve, reject)=>{
112
+ loadScript(url, resolve, reject);
113
+ });
114
+ } catch (err) {
115
+ if (isOverridden) {
116
+ dispatchToastShown({
117
+ kind: 'error',
118
+ title: getCoreTranslation('scriptLoadingFailed', 'Error: Script failed to load'),
119
+ 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.', {
120
+ url
121
+ }),
122
+ actionButtonLabel: getCoreTranslation('resetOverrides', 'Reset overrides'),
123
+ onActionButtonClick () {
124
+ window.importMapOverrides.resetOverrides();
125
+ window.location.reload();
126
+ }
127
+ });
128
+ }
129
+ return Promise.reject(err);
130
+ }
131
+ }
132
+ return Promise.resolve();
133
+ }
134
+ /**
135
+ * @internal
136
+ *
137
+ * Used to load the current import map
138
+ *
139
+ * @returns The current page map
140
+ */ export async function getCurrentImportMap() {
141
+ return window.importMapOverrides.getCurrentPageMap();
142
+ }
143
+ function isFederatedModule(a) {
144
+ return typeof a === 'object' && a !== null && 'init' in a && typeof a['init'] === 'function' && 'get' in a && typeof a['get'] === 'function';
145
+ }
146
+ // internals to track script loading
147
+ // basically, if we're already loading a script, we should wait until the script is loaded
148
+ // we use a global to track this
149
+ const OPENMRS_SCRIPT_LOADING = Symbol('__openmrs_script_loading');
150
+ /**
151
+ * Appends a `<script>` to the DOM with the given URL.
152
+ */ function loadScript(url, resolve, reject) {
153
+ const scriptElement = document.head.querySelector(`script[src="${url}"]`);
154
+ let scriptLoading = window[OPENMRS_SCRIPT_LOADING];
155
+ if (!scriptLoading) {
156
+ scriptLoading = window[OPENMRS_SCRIPT_LOADING] = new Set([]);
157
+ }
158
+ if (!scriptElement) {
159
+ scriptLoading.add(url);
160
+ const element = document.createElement('script');
161
+ element.src = url;
162
+ element.type = 'text/javascript';
163
+ element.async = true;
164
+ // loadTime() displays an error if a script takes more than 5 seconds to load
165
+ const loadTimeout = setTimeout(()=>{
166
+ 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.`);
167
+ }, 5000); // 5 seconds; this is arbitrary
168
+ let loadFn, errFn, finishScriptLoading;
169
+ finishScriptLoading = ()=>{
170
+ clearTimeout(loadTimeout);
171
+ scriptLoading.delete(url);
172
+ loadFn && element.removeEventListener('load', loadFn);
173
+ errFn && element.removeEventListener('error', errFn);
174
+ };
175
+ loadFn = ()=>{
176
+ finishScriptLoading();
177
+ resolve(null);
178
+ };
179
+ errFn = (ev)=>{
180
+ finishScriptLoading();
181
+ const msg = `Failed to load script from ${url}`;
182
+ console.error(msg, ev);
183
+ reject(ev.message ?? msg);
184
+ };
185
+ element.addEventListener('load', loadFn);
186
+ element.addEventListener('error', errFn);
187
+ document.head.appendChild(element);
188
+ } else {
189
+ if (scriptLoading.has(url)) {
190
+ let loadFn, errFn, finishScriptLoading;
191
+ finishScriptLoading = ()=>{
192
+ loadFn && scriptElement.removeEventListener('load', loadFn);
193
+ errFn && scriptElement.removeEventListener('error', errFn);
194
+ };
195
+ loadFn = ()=>{
196
+ finishScriptLoading();
197
+ resolve(null);
198
+ };
199
+ // this errFn does not log anything
200
+ errFn = (ev)=>{
201
+ finishScriptLoading();
202
+ reject(ev.message);
203
+ };
204
+ scriptElement.addEventListener('load', loadFn);
205
+ scriptElement.addEventListener('error', errFn);
206
+ } else {
207
+ console.warn(`Script at ${url} already loaded. Not loading it again.`);
208
+ resolve(null);
209
+ }
210
+ }
211
+ }
@@ -0,0 +1 @@
1
+ export * from './dynamic-loading';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from "./dynamic-loading.js";
@@ -0,0 +1 @@
1
+ export { importDynamic } from './dynamic-loading';
package/dist/public.js ADDED
@@ -0,0 +1 @@
1
+ export { importDynamic } from "./dynamic-loading.js";
package/package.json CHANGED
@@ -1,19 +1,28 @@
1
1
  {
2
2
  "name": "@openmrs/esm-dynamic-loading",
3
- "version": "6.3.1-pre.2965",
3
+ "version": "6.3.1-pre.2986",
4
4
  "license": "MPL-2.0",
5
5
  "description": "Utilities for dynamically loading code in OpenMRS",
6
- "browser": "dist/openmrs-esm-dynamic-loading.js",
7
- "main": "src/index.ts",
8
- "source": true,
6
+ "type": "module",
7
+ "module": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./src/index.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./src/public": {
15
+ "types": "./src/public.ts",
16
+ "default": "./dist/public.js"
17
+ }
18
+ },
9
19
  "sideEffects": false,
10
20
  "scripts": {
11
- "test": "cross-env TZ=UTC jest --config jest.config.js --verbose false --passWithNoTests --color",
12
- "test:watch": "cross-env TZ=UTC jest --watch --config jest.config.js --color",
13
- "build": "webpack --mode=production",
14
- "build:development": "webpack --mode development",
15
- "analyze": "webpack --mode=production --env analyze=true",
16
- "typescript": "tsc",
21
+ "test": "cross-env TZ=UTC jest --verbose false --passWithNoTests --color",
22
+ "test:watch": "cross-env TZ=UTC jest --watch --color",
23
+ "build": "rimraf dist && concurrently \"swc --strip-leading-paths src -d dist\" \"tsc --project tsconfig.build.json\"",
24
+ "build:development": "rimraf dist && concurrently \"swc --strip-leading-paths src -d dist\" \"tsc --project tsconfig.build.json\"",
25
+ "typescript": "tsc --project tsconfig.build.json",
17
26
  "lint": "eslint src --ext ts,tsx"
18
27
  },
19
28
  "keywords": [
@@ -43,7 +52,12 @@
43
52
  "@openmrs/esm-translations": "6.x"
44
53
  },
45
54
  "devDependencies": {
46
- "@openmrs/esm-globals": "6.3.1-pre.2965"
55
+ "@openmrs/esm-globals": "6.3.1-pre.2986",
56
+ "@openmrs/esm-translations": "6.3.1-pre.2986",
57
+ "@swc/cli": "^0.7.7",
58
+ "@swc/core": "^1.11.29",
59
+ "concurrently": "^9.1.2",
60
+ "rimraf": "^6.0.1"
47
61
  },
48
62
  "stableVersion": "6.3.0"
49
63
  }
@@ -0,0 +1,9 @@
1
+ {
2
+ "$schema": "https://json.schemastore.org/tsconfig.json",
3
+ "compilerOptions": {
4
+ "declarationDir": "dist",
5
+ "emitDeclarationOnly": true
6
+ },
7
+ "extends": "./tsconfig.json",
8
+ "exclude": ["**/*.test.*", "**/setup-tests.*"]
9
+ }
package/tsconfig.json CHANGED
@@ -1,25 +1,5 @@
1
1
  {
2
- "compilerOptions": {
3
- "esModuleInterop": true,
4
- "module": "esnext",
5
- "target": "es2015",
6
- "allowSyntheticDefaultImports": true,
7
- "jsx": "react",
8
- "strictNullChecks": true,
9
- "moduleResolution": "node",
10
- "declaration": true,
11
- "declarationDir": "dist",
12
- "emitDeclarationOnly": true,
13
- "lib": [
14
- "dom",
15
- "es5",
16
- "scripthost",
17
- "es2015",
18
- "es2015.promise",
19
- "es2016.array.include",
20
- "es2018",
21
- "esnext"
22
- ]
23
- },
24
- "include": ["src/**/*"]
2
+ "$schema": "https://json.schemastore.org/tsconfig.json",
3
+ "extends": "../tsconfig.json",
4
+ "include": ["src/**/*.ts*"]
25
5
  }
@@ -1,2 +0,0 @@
1
- System.register(["@openmrs/esm-globals","@openmrs/esm-translations"],(function(e,t){var r={},n={};return{setters:[function(e){r.dispatchToastShown=e.dispatchToastShown},function(e){n.getCoreTranslation=e.getCoreTranslation}],execute:function(){e((()=>{"use strict";var e={728:e=>{e.exports=r},901:e=>{e.exports=n}},t={};function o(r){var n=t[r];if(void 0!==n)return n.exports;var i=t[r]={exports:{}};return e[r](i,i.exports,o),i.exports}o.d=(e,t)=>{for(var r in t)o.o(t,r)&&!o.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{o.S={};var e={},t={};o.I=(r,n)=>{n||(n=[]);var i=t[r];if(i||(i=t[r]={}),!(n.indexOf(i)>=0)){if(n.push(i),e[r])return e[r];o.o(o.S,r)||(o.S[r]={}),o.S[r];var a=[];return e[r]=a.length?Promise.all(a).then((()=>e[r]=1)):1}}})();var i={};return(()=>{o.r(i),o.d(i,{getCurrentImportMap:()=>p,importDynamic:()=>c,preloadImport:()=>u,slugify:()=>s});var e=o(728),t=o(901);function r(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function n(e){return function(){var t=this,n=arguments;return new Promise((function(o,i){var a=e.apply(t,n);function s(e){r(a,o,i,s,c,"next",e)}function c(e){r(a,o,i,s,c,"throw",e)}s(void 0)}))}}function a(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,n=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],n=0}finally{r=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}}function s(e){return e.replace(/[\/\-@]/g,"_")}function c(e){return l.apply(this,arguments)}function l(){return l=n((function(e){var t,r,n,i,c,l,d,p,f,h,m=arguments;return a(this,(function(a){switch(a.label){case 0:return t=m.length>1&&void 0!==m[1]?m[1]:"./start",n=!(null==(r=m.length>2?m[2]:void 0)?void 0:r.maxLoadingTime)||r.maxLoadingTime<=0?6e5:r.maxLoadingTime,i=void 0,[4,Promise.race([u(e,null==r?void 0:r.importMap),new Promise((function(t,r){i=setTimeout((function(){var t;r(new Error("Could not resolve requested script, ".concat(e,", within ").concat((t=n)<1e3?"".concat(t," milliseconds"):t<6e4?"".concat(Math.floor(t/1e3)," seconds"):t<36e5?"".concat(Math.floor(t/6e4)," minutes"):t<864e5?"".concat(Math.floor(t/36e5)," hours"):"".concat(Math.floor(t/864e5)," days"),".")))}),n)}))])];case 1:if(a.sent(),i&&clearTimeout(i),c=s(e),"object"!=typeof(v=l=window[c])||null===v||!("init"in v)||"function"!=typeof v.init||!("get"in v)||"function"!=typeof v.get)throw d="The global variable ".concat(c," does not refer to a federated module"),console.error(d),new Error(d);return l.init(o.S.default),[4,l.get(t)];case 2:if(p=a.sent(),"object"!=typeof(f=p())||null===f)throw h="Container for ".concat(e," did not return an ESM module as expected"),console.error(h),new Error(h);return[2,f]}var v}))})),l.apply(this,arguments)}function u(e,t){return d.apply(this,arguments)}function d(){return(d=n((function(r,n){var o,i,c,l,u,d,f,m;return a(this,(function(a){switch(a.label){case 0:if("string"!=typeof r||0===r.trim().length)throw o="Attempted to call importDynamic() without supplying a package to load",console.error(o),new Error(o);return i=s(r),window[i]?[3,7]:null==n?[3,1]:(l=n,[3,3]);case 1:return[4,p()];case 2:l=a.sent(),a.label=3;case 3:if(!(c=l).imports.hasOwnProperty(r))throw u="Could not find the package ".concat(r," defined in the current importmap"),console.error(u),new Error(u);(d=c.imports[r]).startsWith("./")&&(d=window.spaBase+d.substring(1)),f=!!window.localStorage.getItem("import-map-override:".concat(r)),a.label=4;case 4:return a.trys.push([4,6,,7]),[4,new Promise((function(e,t){!function(e,t,r){var n=document.head.querySelector('script[src="'.concat(e,'"]')),o=window[h];if(o||(o=window[h]=new Set([])),n){var i,a,s;o.has(e)?(s=function(){i&&n.removeEventListener("load",i),a&&n.removeEventListener("error",a)},i=function(){s(),t(null)},a=function(e){s(),r(e.message)},n.addEventListener("load",i),n.addEventListener("error",a)):(console.warn("Script at ".concat(e," already loaded. Not loading it again.")),t(null))}else{o.add(e);var c=document.createElement("script");c.src=e,c.type="text/javascript",c.async=!0;var l,u,d,p=setTimeout((function(){console.error("The script at ".concat(e," 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."))}),5e3);d=function(){clearTimeout(p),o.delete(e),l&&c.removeEventListener("load",l),u&&c.removeEventListener("error",u)},l=function(){d(),t(null)},u=function(t){d();var n,o="Failed to load script from ".concat(e);console.error(o,t),r(null!==(n=t.message)&&void 0!==n?n:o)},c.addEventListener("load",l),c.addEventListener("error",u),document.head.appendChild(c)}}(d,e,t)}))];case 5:return[2,a.sent()];case 6:return m=a.sent(),f&&(0,e.dispatchToastShown)({kind:"error",title:(0,t.getCoreTranslation)("scriptLoadingFailed","Error: Script failed to load"),description:(0,t.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.",{url:d}),actionButtonLabel:(0,t.getCoreTranslation)("resetOverrides","Reset overrides"),onActionButtonClick:function(){window.importMapOverrides.resetOverrides(),window.location.reload()}}),[2,Promise.reject(m)];case 7:return[2,Promise.resolve()]}}))}))).apply(this,arguments)}function p(){return f.apply(this,arguments)}function f(){return(f=n((function(){return a(this,(function(e){return[2,window.importMapOverrides.getCurrentPageMap()]}))}))).apply(this,arguments)}var h=Symbol("__openmrs_script_loading")})(),i})())}}}));
2
- //# sourceMappingURL=openmrs-esm-dynamic-loading.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"openmrs-esm-dynamic-loading.js","mappings":"wRAAAA,EAAOC,QAAUC,C,UCAjBF,EAAOC,QAAUE,C,GCCbC,EAA2B,CAAC,EAGhC,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EAAyBE,GAC5C,QAAqBE,IAAjBD,EACH,OAAOA,EAAaN,QAGrB,IAAID,EAASI,EAAyBE,GAAY,CAGjDL,QAAS,CAAC,GAOX,OAHAQ,EAAoBH,GAAUN,EAAQA,EAAOC,QAASI,GAG/CL,EAAOC,OACf,CCrBAI,EAAoBK,EAAI,CAACT,EAASU,KACjC,IAAI,IAAIC,KAAOD,EACXN,EAAoBQ,EAAEF,EAAYC,KAASP,EAAoBQ,EAAEZ,EAASW,IAC5EE,OAAOC,eAAed,EAASW,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,IAE1E,ECNDP,E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OoD,mBAAmBI,oB,GACnC,KAFsB9C,MAAAA,KAAAA,U,CAuBtB,IAAMa,EAAyBjE,OAAO,2B","sources":["webpack://@openmrs/esm-dynamic-loading/external system \"@openmrs/esm-globals\"","webpack://@openmrs/esm-dynamic-loading/external system \"@openmrs/esm-translations\"","webpack://@openmrs/esm-dynamic-loading/webpack/bootstrap","webpack://@openmrs/esm-dynamic-loading/webpack/runtime/define property getters","webpack://@openmrs/esm-dynamic-loading/webpack/runtime/hasOwnProperty shorthand","webpack://@openmrs/esm-dynamic-loading/webpack/runtime/make namespace object","webpack://@openmrs/esm-dynamic-loading/webpack/runtime/sharing","webpack://@openmrs/esm-dynamic-loading/./src/dynamic-loading.ts"],"sourcesContent":["module.exports = __WEBPACK_EXTERNAL_MODULE__728__;","module.exports = __WEBPACK_EXTERNAL_MODULE__901__;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.S = {};\nvar initPromises = {};\nvar initTokens = {};\n__webpack_require__.I = (name, initScope) => {\n\tif(!initScope) initScope = [];\n\t// handling circular init calls\n\tvar initToken = initTokens[name];\n\tif(!initToken) initToken = initTokens[name] = {};\n\tif(initScope.indexOf(initToken) >= 0) return;\n\tinitScope.push(initToken);\n\t// only runs once\n\tif(initPromises[name]) return initPromises[name];\n\t// creates a new share scope if needed\n\tif(!__webpack_require__.o(__webpack_require__.S, name)) __webpack_require__.S[name] = {};\n\t// runs all init snippets from all modules reachable\n\tvar scope = __webpack_require__.S[name];\n\tvar warn = (msg) => {\n\t\tif (typeof console !== \"undefined\" && console.warn) console.warn(msg);\n\t};\n\tvar uniqueName = \"@openmrs/esm-dynamic-loading\";\n\tvar register = (name, version, factory, eager) => {\n\t\tvar versions = scope[name] = scope[name] || {};\n\t\tvar activeVersion = versions[version];\n\t\tif(!activeVersion || (!activeVersion.loaded && (!eager != !activeVersion.eager ? eager : uniqueName > activeVersion.from))) versions[version] = { get: factory, from: uniqueName, eager: !!eager };\n\t};\n\tvar initExternal = (id) => {\n\t\tvar handleError = (err) => (warn(\"Initialization of sharing external failed: \" + err));\n\t\ttry {\n\t\t\tvar module = __webpack_require__(id);\n\t\t\tif(!module) return;\n\t\t\tvar initFn = (module) => (module && module.init && module.init(__webpack_require__.S[name], initScope))\n\t\t\tif(module.then) return promises.push(module.then(initFn, handleError));\n\t\t\tvar initResult = initFn(module);\n\t\t\tif(initResult && initResult.then) return promises.push(initResult['catch'](handleError));\n\t\t} catch(err) { handleError(err); }\n\t}\n\tvar promises = [];\n\tswitch(name) {\n\t}\n\tif(!promises.length) return initPromises[name] = 1;\n\treturn initPromises[name] = Promise.all(promises).then(() => (initPromises[name] = 1));\n};","/** @module @category Dynamic Loading */\n'use strict';\n// hack to make the types defined in esm-globals available here\nimport { dispatchToastShown, type ImportMap } from '@openmrs/esm-globals';\nimport { getCoreTranslation } from '@openmrs/esm-translations';\n\n/**\n * @internal\n *\n * Transforms an ESM module name to a valid JS identifier\n *\n * @param name the name of a module\n * @returns An opaque, equivalent JS identifier for the module\n */\nexport function slugify(name: string) {\n return name.replace(/[\\/\\-@]/g, '_');\n}\n\n/**\n * Loads the named export from a named package. This might be used like:\n *\n * ```js\n * const { someComponent } = importDynamic(\"@openmrs/esm-template-app\")\n * ```\n *\n * @param jsPackage The package to load the export from.\n * @param share Indicates the name of the shared module; this is an advanced feature if the package you are loading\n * doesn't use the default OpenMRS shared module name \"./start\".\n * @param options Additional options to control loading this script.\n * @param options.importMap The import map to use to load the script. This is useful for situations where you're\n * loading multiple scripts at a time, since it allows the calling code to supply an importMap, saving multiple\n * calls to `getCurrentImportMap()`.\n * @param options.maxLoadingTime A positive integer representing the maximum number of milliseconds to wait for the\n * script to load before the promise returned from this function will be rejected. Defaults to 600,000 milliseconds,\n * i.e., 10 minutes.\n */\nexport async function importDynamic<T = any>(\n jsPackage: string,\n share: string = './start',\n options?: {\n importMap?: ImportMap;\n maxLoadingTime?: number;\n },\n): Promise<T> {\n // default to 10 minutes\n const maxLoadingTime = !options?.maxLoadingTime || options.maxLoadingTime <= 0 ? 600_000 : options.maxLoadingTime;\n\n let timeout: ReturnType<typeof setTimeout> | undefined = undefined;\n await Promise.race([\n preloadImport(jsPackage, options?.importMap),\n new Promise((_, reject) => {\n timeout = setTimeout(() => {\n reject(\n new Error(`Could not resolve requested script, ${jsPackage}, within ${humanReadableMs(maxLoadingTime)}.`),\n );\n }, maxLoadingTime);\n }),\n ]);\n\n timeout && clearTimeout(timeout);\n\n const jsPackageSlug = slugify(jsPackage);\n\n const container = window[jsPackageSlug] as unknown;\n if (!isFederatedModule(container)) {\n const error = `The global variable ${jsPackageSlug} does not refer to a federated module`;\n console.error(error);\n throw new Error(error);\n }\n\n container.init(__webpack_share_scopes__.default);\n\n const factory = await container.get(share);\n const module = factory();\n\n if (!(typeof module === 'object') || module === null) {\n const error = `Container for ${jsPackage} did not return an ESM module as expected`;\n console.error(error);\n throw new Error(error);\n }\n\n return module as unknown as T;\n}\n\n/**\n * Utility function to convert milliseconds into human-readable strings with rather absurd\n * levels of precision.\n *\n * @param ms Number of milliseconds\n * @returns A human-readable string useful only for error logging, where we can assume English\n */\nfunction humanReadableMs(ms: number) {\n if (ms < 1_000) {\n return `${ms} milliseconds`;\n } else if (ms < 60_000) {\n return `${Math.floor(ms / 1000)} seconds`;\n } else if (ms < 3_600_000) {\n return `${Math.floor(ms / 60_000)} minutes`;\n } else if (ms < 86_400_000) {\n return `${Math.floor(ms / 3_600_000)} hours`;\n } else {\n return `${Math.floor(ms / 86_400_000)} days`;\n }\n}\n\n/**\n * @internal\n *\n * This internal method is used to ensure that the script belonging\n * to the given package is loaded and added to the head.\n *\n * @param jsPackage The package to load\n * @param importMap The import map to use for loading this package.\n * The main reason for specifying this is to avoid needing to call\n * `getCurrentPageMap()` for every script when bulk loading.\n */\nexport async function preloadImport(jsPackage: string, importMap?: ImportMap) {\n if (typeof jsPackage !== 'string' || jsPackage.trim().length === 0) {\n const error = 'Attempted to call importDynamic() without supplying a package to load';\n console.error(error);\n throw new Error(error);\n }\n\n const jsPackageSlug = slugify(jsPackage);\n\n if (!window[jsPackageSlug]) {\n const activeImportMap = importMap ?? (await getCurrentImportMap());\n if (!activeImportMap.imports.hasOwnProperty(jsPackage)) {\n const error = `Could not find the package ${jsPackage} defined in the current importmap`;\n console.error(error);\n throw new Error(error);\n }\n\n let url = activeImportMap.imports[jsPackage];\n if (url.startsWith('./')) {\n url = window.spaBase + url.substring(1);\n }\n\n const isOverridden = !!window.localStorage.getItem(`import-map-override:${jsPackage}`);\n try {\n return await new Promise<void>((resolve, reject) => {\n loadScript(url, resolve, reject);\n });\n } catch (err: any) {\n if (isOverridden) {\n dispatchToastShown({\n kind: 'error',\n title: getCoreTranslation('scriptLoadingFailed', 'Error: Script failed to load'),\n description: getCoreTranslation(\n 'scriptLoadingError',\n '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.',\n {\n url,\n },\n ),\n actionButtonLabel: getCoreTranslation('resetOverrides', 'Reset overrides'),\n onActionButtonClick() {\n window.importMapOverrides.resetOverrides();\n window.location.reload();\n },\n });\n }\n\n return Promise.reject(err);\n }\n }\n\n return Promise.resolve();\n}\n\n/**\n * @internal\n *\n * Used to load the current import map\n *\n * @returns The current page map\n */\nexport async function getCurrentImportMap() {\n return window.importMapOverrides.getCurrentPageMap();\n}\n\ninterface FederatedModule {\n init: (scope: typeof __webpack_share_scopes__.default) => void;\n get: (_export: string) => Promise<() => unknown>;\n}\n\nfunction isFederatedModule(a: unknown): a is FederatedModule {\n return (\n typeof a === 'object' &&\n a !== null &&\n 'init' in a &&\n typeof a['init'] === 'function' &&\n 'get' in a &&\n typeof a['get'] === 'function'\n );\n}\n\n// internals to track script loading\n// basically, if we're already loading a script, we should wait until the script is loaded\n// we use a global to track this\nconst OPENMRS_SCRIPT_LOADING = Symbol('__openmrs_script_loading');\n\n/**\n * Appends a `<script>` to the DOM with the given URL.\n */\nfunction loadScript(\n url: string,\n resolve: (value: unknown | PromiseLike<unknown>) => void,\n reject: (reason?: any) => void,\n) {\n const scriptElement = document.head.querySelector(`script[src=\"${url}\"]`);\n let scriptLoading: Set<String> = window[OPENMRS_SCRIPT_LOADING];\n if (!scriptLoading) {\n scriptLoading = window[OPENMRS_SCRIPT_LOADING] = new Set([]);\n }\n\n if (!scriptElement) {\n scriptLoading.add(url);\n const element = document.createElement('script');\n element.src = url;\n element.type = 'text/javascript';\n element.async = true;\n\n // loadTime() displays an error if a script takes more than 5 seconds to load\n const loadTimeout = setTimeout(() => {\n console.error(\n `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.`,\n );\n }, 5_000); // 5 seconds; this is arbitrary\n\n let loadFn: () => void, errFn: (ev: ErrorEvent) => void, finishScriptLoading: () => void;\n\n finishScriptLoading = () => {\n clearTimeout(loadTimeout);\n scriptLoading.delete(url);\n loadFn && element.removeEventListener('load', loadFn);\n errFn && element.removeEventListener('error', errFn);\n };\n\n loadFn = () => {\n finishScriptLoading();\n resolve(null);\n };\n\n errFn = (ev: ErrorEvent) => {\n finishScriptLoading();\n const msg = `Failed to load script from ${url}`;\n console.error(msg, ev);\n reject(ev.message ?? msg);\n };\n\n element.addEventListener('load', loadFn);\n element.addEventListener('error', errFn);\n\n document.head.appendChild(element);\n } else {\n if (scriptLoading.has(url)) {\n let loadFn: () => void, errFn: (ev: ErrorEvent) => void, finishScriptLoading: () => void;\n\n finishScriptLoading = () => {\n loadFn && scriptElement.removeEventListener('load', loadFn);\n errFn && scriptElement.removeEventListener('error', errFn);\n };\n\n loadFn = () => {\n finishScriptLoading();\n resolve(null);\n };\n\n // this errFn does not log anything\n errFn = (ev: ErrorEvent) => {\n finishScriptLoading();\n reject(ev.message);\n };\n\n scriptElement.addEventListener('load', loadFn);\n scriptElement.addEventListener('error', errFn);\n } else {\n console.warn(`Script at ${url} already loaded. Not loading it again.`);\n resolve(null);\n }\n }\n}\n"],"names":["module","exports","__WEBPACK_EXTERNAL_MODULE__728__","__WEBPACK_EXTERNAL_MODULE__901__","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","d","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","S","initPromises","initTokens","I","name","initScope","initToken","indexOf","push","promises","length","Promise","all","then","slugify","replace","importDynamic","jsPackage","share","options","maxLoadingTime","timeout","jsPackageSlug","container","error","factory","race","preloadImport","importMap","_","reject","setTimeout","ms","Error","humanReadableMs","Math","floor","clearTimeout","a","window","console","init","__webpack_share_scopes__","default","activeImportMap","url","isOverridden","err","trim","getCurrentImportMap","imports","startsWith","spaBase","substring","localStorage","getItem","resolve","scriptElement","document","head","querySelector","scriptLoading","OPENMRS_SCRIPT_LOADING","Set","loadFn","errFn","finishScriptLoading","has","removeEventListener","ev","message","addEventListener","warn","add","element","createElement","src","type","async","loadTimeout","delete","msg","appendChild","loadScript","dispatchToastShown","kind","title","getCoreTranslation","description","actionButtonLabel","onActionButtonClick","importMapOverrides","resetOverrides","location","reload","getCurrentPageMap"],"sourceRoot":""}
package/jest.config.js DELETED
@@ -1,10 +0,0 @@
1
- module.exports = {
2
- clearMocks: true,
3
- transform: {
4
- '^.+\\.tsx?$': ['@swc/jest'],
5
- },
6
- testEnvironment: 'jsdom',
7
- testEnvironmentOptions: {
8
- url: 'http://localhost/',
9
- },
10
- };
package/webpack.config.js DELETED
@@ -1,42 +0,0 @@
1
- const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
2
- const { resolve, basename } = require('path');
3
- const { CleanWebpackPlugin } = require('clean-webpack-plugin');
4
- const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
5
-
6
- const { browser, peerDependencies } = require('./package.json');
7
-
8
- module.exports = (env) => ({
9
- entry: [resolve(__dirname, 'src/index.ts')],
10
- output: {
11
- filename: basename(browser),
12
- path: resolve(__dirname, 'dist'),
13
- library: { type: 'system' },
14
- },
15
- devtool: 'source-map',
16
- module: {
17
- rules: [
18
- {
19
- test: /\.m?(js|ts|tsx)$/,
20
- exclude: /node_modules/,
21
- use: 'swc-loader',
22
- },
23
- ],
24
- },
25
- externals: Object.keys(peerDependencies || {}),
26
- resolve: {
27
- extensions: ['.ts', '.js', '.tsx', '.jsx'],
28
- },
29
- plugins: [
30
- new CleanWebpackPlugin(),
31
- new ForkTsCheckerWebpackPlugin(),
32
- new BundleAnalyzerPlugin({
33
- analyzerMode: env && env.analyze ? 'static' : 'disabled',
34
- }),
35
- ],
36
- devServer: {
37
- disableHostCheck: true,
38
- headers: {
39
- 'Access-Control-Allow-Origin': '*',
40
- },
41
- },
42
- });