@lwrjs/loader 0.6.0-alpha.9 → 0.6.2

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.
@@ -4,5 +4,5 @@
4
4
  * SPDX-License-Identifier: MIT
5
5
  * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
6
6
  */
7
- /* LWR Legacy Module Loader Shim v0.6.0-alpha.9 */
8
- !function(){"use strict";var e;function t(e){}function r(e,r,o,s){const{autoBoot:n,customInit:i}=e;if(function(e,t){if(!e&&!t)throw new Error("The customInit hook is required when autoBoot is false");if(e&&t)throw new Error("The customInit hook must not be defined when autoBoot is true")}(n,i),i){i({initializeApp:r,define:o,onBootstrapError:s,attachDispatcher:t},e)}}!function(e){e[e.Start=0]="Start"}(e||(e={}));const o="function"==typeof setTimeout,s="undefined"!=typeof console;const n=globalThis;n.LWR.requiredModules=n.LWR.requiredModules||[],n.LWR.requiredModules.indexOf("lwr/loaderLegacy/v/0_6_0-alpha_9")<0&&n.LWR.requiredModules.push("lwr/loaderLegacy/v/0_6_0-alpha_9"),new class{constructor(e){this.defineCache={},this.orderedDefs=[],this.global=e,this.config=e.LWR,this.loaderModule="lwr/loaderLegacy/v/0_6_0-alpha_9";const t=this.tempDefine.bind(this);e.LWR.define=t,this.bootReady=this.config.autoBoot,o&&(this.watchdogTimerId=this.startWatchdogTimer());try{r(Object.freeze(this.config),this.postCustomInit.bind(this),t,(e=>{this.errorHandler=e}))}catch(e){this.enterErrorState(e)}}canInit(){const e=this.config.requiredModules.every((e=>this.orderedDefs.includes(e)));return this.bootReady&&e}tempDefine(...e){const t=e[0];this.defineCache[t]=e,this.orderedDefs.push(t),this.canInit()&&(o&&clearTimeout(this.watchdogTimerId),this.initApp())}postCustomInit(){this.bootReady=!0,this.canInit()&&this.initApp()}initApp(){try{const e=function(e,t,r,o){if(!t||"function"!=typeof t[2])throw new Error(`Expected loader with specifier "${e}" to be a module`);const s={};t[2].call(null,s);const{Loader:n}=s,i=new n(r);return o&&o.length&&i.registerExternalModules(o),i.define(e,["exports"],(e=>{Object.assign(e,{define:i.define.bind(i),load:i.load.bind(i),services:i.services})}),t[3]),i}(this.loaderModule,this.defineCache[this.loaderModule],this.config.baseUrl,this.config.preloadModules);this.mountApp(e)}catch(e){this.enterErrorState(e)}}waitForDOMContentLoaded(){return void 0===typeof document||"interactive"===document.readyState||"complete"===document.readyState?Promise.resolve():new Promise((e=>{document.addEventListener("DOMContentLoaded",(()=>{e()}))}))}mountApp(e){const{bootstrapModule:t,rootComponent:r,importMappings:o,rootComponents:s,endpoints:n}=this.config;this.global.LWR=Object.freeze({define:e.define.bind(e),rootComponent:r,rootComponents:s,importMappings:o,endpoints:n}),this.orderedDefs.forEach((t=>{t!==this.loaderModule&&e.define(...this.defineCache[t])}));const{disableInitDefer:i}=this.config;e.registerImportMappings(o).then((()=>{if(!i)return this.waitForDOMContentLoaded()})).then((()=>e.load(t))).catch((e=>{this.enterErrorState(new Error(`Application ${r} could not be loaded: ${e}`))}))}enterErrorState(e){this.errorHandler?this.errorHandler(e):s&&console.error(`An error occurred during LWR bootstrap. ${e.message}`,e.stack)}startWatchdogTimer(){return setTimeout((()=>{this.enterErrorState(new Error("Failed to load required modules - timed out"))}),3e5)}}(n)}(),LWR.define("lwr/loaderLegacy/v/0_6_0-alpha_9",["exports"],(function(exports){"use strict";const templateRegex=/\{([0-9]+)\}/g;function templateString(e,t){return e.replace(templateRegex,((e,r)=>t[r]))}function generateErrorMessage(e,t){const r=Array.isArray(t)?templateString(e.message,t):e.message;return`LWR${e.code}: ${r}`}class LoaderError extends Error{constructor(e,t){super(),this.message=generateErrorMessage(e,t)}}function invariant(e,t){if(!e)throw new LoaderError(t)}const MISSING_NAME=Object.freeze({code:3e3,message:"A module name is required.",level:0}),FAIL_INSTANTIATE=Object.freeze({code:3004,message:"Failed to instantiate module: {0}",level:0}),NO_AMD_REQUIRE=Object.freeze({code:3005,message:"AMD require not supported.",level:0}),FAILED_DEP=Object.freeze({code:3006,level:0,message:"Failed to load dependency: {0}"}),INVALID_DEPS=Object.freeze({code:3007,message:"Unexpected value received for dependencies argument; expected an array.",level:0}),FAIL_LOAD=Object.freeze({code:3008,level:0,message:"Error loading {0}"}),UNRESOLVED=Object.freeze({code:3009,level:0,message:"Unable to resolve bare specifier: {0}"}),NO_BASE_URL=Object.freeze({code:3010,level:0,message:"baseUrl not set"});Object.freeze({code:3011,level:0,message:"Cannot set a loader service multiple times"});const INVALID_HOOK=Object.freeze({code:3012,level:0,message:"Invalid hook received"}),INVALID_LOADER_SERVICE_RESPONSE=Object.freeze({code:3013,level:0,message:"Invalid response received from hook"}),MODULE_LOAD_TIMEOUT=Object.freeze({code:3014,level:0,message:"Error loading {0} - timed out"}),HTTP_FAIL_LOAD=Object.freeze({code:3015,level:0,message:"Error loading {0}, status code {1}"}),STALE_HOOK_ERROR=Object.freeze({code:3016,level:0,message:"An error occurred handling module conflict"}),MODULE_ALREADY_LOADED=Object.freeze({code:3017,level:0,message:"Marking module(s) as externally loaded, but they are already loaded: {0}"}),FAIL_HOOK_LOAD=Object.freeze({code:3018,level:0,message:'Error loading "{0}" from hook'}),BAD_IMPORT_MAP=Object.freeze({code:3011,level:0,message:"import map is not valid"}),hasDocument="undefined"!=typeof document,hasSetTimeout="function"==typeof setTimeout,hasConsole="undefined"!=typeof console;function getBaseUrl(){let e;if(hasDocument){const t=document.querySelector("base[href]");e=t&&t.href}if(!e&&"undefined"!=typeof location){e=location.href.split("#")[0].split("?")[0];const t=e.lastIndexOf("/");-1!==t&&(e=e.slice(0,t+1))}return e}function isUrl(e){return-1!==e.indexOf("://")}function resolveIfNotPlainOrUrl(e,t){if(-1!==e.indexOf("\\")&&(e=e.replace(/\\/g,"/")),"/"===e[0]&&"/"===e[1])return t.slice(0,t.indexOf(":")+1)+e;if("."===e[0]&&("/"===e[1]||"."===e[1]&&("/"===e[2]||2===e.length&&(e+="/"))||1===e.length&&(e+="/"))||"/"===e[0]){const r=t.slice(0,t.indexOf(":")+1);let o;if("/"===t[r.length+1]?"file:"!==r?(o=t.slice(r.length+2),o=o.slice(o.indexOf("/")+1)):o=t.slice(8):o=t.slice(r.length+("/"===t[r.length]?1:0)),"/"===e[0])return t.slice(0,t.length-o.length-1)+e;const s=o.slice(0,o.lastIndexOf("/")+1)+e,n=[];let i=-1;for(let e=0;e<s.length;e++)-1!==i?"/"===s[e]&&(n.push(s.slice(i,e+1)),i=-1):"."===s[e]?"."!==s[e+1]||"/"!==s[e+2]&&e+2!==s.length?"/"===s[e+1]||e+1===s.length?e+=1:i=e:(n.pop(),e+=2):i=e;return-1!==i&&n.push(s.slice(i)),t.slice(0,t.length-o.length)+n.join("")}}function resolveUrl(e,t){return resolveIfNotPlainOrUrl(e,t)||(isUrl(e)?e:resolveIfNotPlainOrUrl("./"+e,t))}function createScript(e){const t=document.createElement("script");return t.charset="utf-8",t.async=!0,t.crossOrigin="anonymous",t.src=e,t}let lastWindowError$1,lastWindowErrorUrl;function loadModuleDef(e){return new Promise((function(t,r){if(hasDocument){const o=createScript(e);o.addEventListener("error",(()=>{r(new LoaderError(FAIL_LOAD,[e]))})),o.addEventListener("load",(()=>{document.head.removeChild(o),lastWindowErrorUrl===e?r(lastWindowError$1):t()})),document.head.appendChild(o)}}))}hasDocument&&window.addEventListener("error",(e=>{lastWindowErrorUrl=e.filename,lastWindowError$1=e.error}));const MODULE_LOAD_TIMEOUT_TIMER=3e5;let lastWindowError;function isCustomResponse(e){return Object.prototype.hasOwnProperty.call(e,"data")&&!Object.prototype.hasOwnProperty.call(e,"blob")}function isFetchResponse(e){return"function"==typeof e.blob}function isResponseAPromise(e){return!(!e||!e.then)}async function evaluateLoadHookResponse(response,id){return Promise.resolve().then((async()=>{if(!response.status)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);if(200!==response.status)throw new LoaderError(HTTP_FAIL_LOAD,[id,`${response.status}`]);const isResponse=isFetchResponse(response);let code;if(isCustomResponse(response))code=response.data;else{if(!isResponse)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);code=await response.text()}if(!code)throw new LoaderError(FAIL_LOAD,[id]);code=`${code}\n//# sourceURL=${id}`;try{eval(code)}catch(e){throw new LoaderError(FAIL_LOAD,[id])}if(lastWindowError)throw new LoaderError(FAIL_LOAD,[id]);return!0})).finally((()=>{}))}async function evaluateLoadHook(e,t){return hasSetTimeout?new Promise(((r,o)=>{const s=setTimeout((()=>{o(new LoaderError(MODULE_LOAD_TIMEOUT,[e]))}),MODULE_LOAD_TIMEOUT_TIMER);t.then((e=>{r(e)})).catch((()=>{o(new LoaderError(FAIL_HOOK_LOAD,[e]))})).finally((()=>{clearTimeout(s)}))})):t}function reportError(e){hasConsole&&console.error(e)}function evaluateHandleStaleModuleHooks(e,t){const{name:r,oldHash:o,newHash:s}=t;for(let t=0;t<e.length;t++){const n=e[t];try{if(null!==n({name:r,oldHash:o,newHash:s}))break}catch(e){reportError(new LoaderError(STALE_HOOK_ERROR))}}}hasDocument&&globalThis.addEventListener("error",(e=>{lastWindowError=e.error})),!hasSetTimeout&&hasConsole&&console.warn("setTimeout API is not available, watchdog timer on load hook will not be set");class ModuleRegistry{constructor(e){this.namedDefineRegistry=new Map,this.moduleRegistry=new Map,this.baseUrl=e}async load(e,t){const r=await this.resolve(e,t),o=this.getModuleRecord(r,e);return o.evaluated?o.module:(o.evaluationPromise||(o.evaluationPromise=this.topLevelEvaluation(o)),o.evaluationPromise)}async resolve(e,t){const r=this.baseUrl;let o,s=e;const n=this.resolveHook;if(n){for(let e=0;e<n.length;e++){const t=(0,n[e])(s,{parentUrl:r});let i;if((t||null===t)&&(i=isResponseAPromise(t)?await t:t),null!==i){if("string"==typeof i){if(resolveIfNotPlainOrUrl(i,r))throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);s=i;continue}if(o=i&&i.url&&(resolveIfNotPlainOrUrl(i.url,r)||i.url),!o)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);break}}if(s!==e){if(!o&&this.namedDefineRegistry.has(s))return s;e=s}}if(!o){const t=resolveIfNotPlainOrUrl(e,r)||e;if(this.moduleRegistry.has(t))return t;if(this.resolver){if(o=this.resolver.resolve(t,r),this.namedDefineRegistry.has(t)&&this.namedDefineRegistry.get(t).defined){const e=this.moduleRegistry.get(o);if(!e||!e.aliases.has(t))return t}}else o=t}if(!o||!isUrl(o)){if(this.namedDefineRegistry.has(e))return e;throw new LoaderError(UNRESOLVED,[e])}return t&&isUrl(o)&&(o+=`?importer=${encodeURIComponent(t)}`),o}has(e){return this.moduleRegistry.has(e)}define(e,t,r,o){const s=this.namedDefineRegistry.get(e);if(s&&s.defined)return void(this.lastDefine=s);const n={name:e,dependencies:t,exporter:r,signatures:o,defined:!0};s&&s.external&&s.external.resolveExternal(n),this.namedDefineRegistry.set(e,n),this.lastDefine=n,o.hashes&&Object.entries(o.hashes).forEach((([e,t])=>{this.checkModuleSignature(e,t)}))}registerExternalModules(e){const t=[];if(e.map((e=>{if(this.namedDefineRegistry.has(e))t.push(e);else{let t,r;const o=new Promise(((o,s)=>{t=o,r=setTimeout((()=>{s(new LoaderError(MODULE_LOAD_TIMEOUT,[e]))}),MODULE_LOAD_TIMEOUT_TIMER)})).finally((()=>{clearTimeout(r)})),s={name:e,defined:!1,external:{resolveExternal:t,moduleDefPromise:o}};this.namedDefineRegistry.set(e,s)}})),t.length)throw new LoaderError(MODULE_ALREADY_LOADED,[t.join(", ")])}checkModuleSignature(e,t){const r=this.namedDefineRegistry.get(e);if(!r){const r={name:e,signatures:{ownHash:t},defined:!1};return void this.namedDefineRegistry.set(e,r)}const o=r.signatures?r.signatures.ownHash:void 0;if(o&&t!==o){const r=this.handleStaleModuleHook;r?evaluateHandleStaleModuleHooks(r,{name:e,oldHash:o,newHash:t}):hasConsole&&console.warn(`stale module detected ${e}, current sig:${o}, new sig:${t}`)}}setImportResolver(e){this.resolver=e}getModuleRecord(e,t){let r=this.moduleRegistry.get(e);if(r)return r.aliases.has(t)||r.aliases.add(t),r;const o=this.getModuleDef(e,t),s=o.then((e=>{const t=e.dependencies.map((e=>{if("exports"!==e)return invariant("require"!==e,NO_AMD_REQUIRE),this.getModuleDependencyRecord.call(this,e)})).filter((e=>void 0!==e));return Promise.all(t)}));return r={id:e,aliases:new Set([t]),module:Object.create(null),dependencyRecords:s,instantiation:o,evaluated:!1,evaluationPromise:null},this.moduleRegistry.set(e,r),r}async getModuleDependencyRecord(e){const t=await this.resolve(e);return this.getModuleRecord(t,e)}async topLevelEvaluation(e){return await this.instantiateAll(e,{}),this.evaluateModule(e,{})}async instantiateAll(e,t){if(!t[e.id]){t[e.id]=!0;const r=await e.dependencyRecords;if(r)for(let e=0;e<r.length;e++){const o=r[e];await this.instantiateAll(o,t)}}}async evaluateModule(e,t){const r=await e.dependencyRecords;r.length>0&&(t[e.id]=!0,await this.evaluateModuleDependencies(r,t));const{exporter:o,dependencies:s}=await e.instantiation,n={},i=await Promise.all(s.map((async e=>{if("exports"===e)return n;const t=await this.resolve(e),r=this.moduleRegistry.get(t);if(!r)throw new LoaderError(FAILED_DEP,[t]);const o=r.module;if(!r.evaluated)return this.getCircularDependencyWrapper(o);if(o)return o.__defaultInterop?o.default:o;throw new LoaderError(FAILED_DEP,[t])})));if(e.evaluated)return e.module;let a=o(...i);void 0!==a?(a={default:a},Object.defineProperty(a,"__defaultInterop",{value:!0})):this.isNamedExportDefaultOnly(n)&&Object.defineProperty(n,"__useDefault",{value:!0});const l=a||n;for(const t in l)Object.defineProperty(e.module,t,{enumerable:!0,set(e){l[t]=e},get:()=>l[t]});return l.__useDefault&&Object.defineProperty(e.module,"__useDefault",{value:!0}),l.__defaultInterop&&Object.defineProperty(e.module,"__defaultInterop",{value:!0}),e.evaluated=!0,Object.freeze(e.module),e.module}isNamedExportDefaultOnly(e){return void 0!==e&&2===Object.getOwnPropertyNames(e).length&&Object.prototype.hasOwnProperty.call(e,"default")&&Object.prototype.hasOwnProperty.call(e,"__esModule")}getCircularDependencyWrapper(e){const t=()=>e.__useDefault||e.__defaultInterop?e.default:e;return t.__circular__=!0,t}async evaluateModuleDependencies(e,t){for(let r=0;r<e.length;r++){const o=e[r];o.evaluated||t[o.id]||(t[o.id]=!0,await this.evaluateModule(o,t))}}async getModuleDef(e,t){this.lastDefine=void 0;const r=isUrl(e)?t!==e?t:void 0:e;let o=r&&this.namedDefineRegistry.get(r);if(o&&o.external)return o.external.moduleDefPromise;if(o&&o.defined)return o;const s=this.baseUrl;return Promise.resolve().then((async()=>{const t=this.loadHook;if(t)for(let r=0;r<t.length;r++){const o=(0,t[r])(e,s),n=isResponseAPromise(o)?await evaluateLoadHook(e,o):o;if(void 0===n)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);if(n&&null!==n)return evaluateLoadHookResponse(n,e)}return!1})).then((t=>{if(!0!==t&&hasDocument)return loadModuleDef(e)})).then((()=>{if(o=r&&this.namedDefineRegistry.get(r),o||(o=this.lastDefine),!o)throw new LoaderError(FAIL_INSTANTIATE,[e]);return o})).catch((e=>{throw e}))}addLoaderPlugin(e){if("object"!=typeof e)throw new LoaderError(INVALID_HOOK);const{loadModule:t,resolveModule:r}=e;r&&(this.resolveHook?this.resolveHook.push(r):this.resolveHook=[r]),t&&(this.loadHook?this.loadHook.push(t):this.loadHook=[t])}registerHandleStaleModuleHook(e){this.handleStaleModuleHook?this.handleStaleModuleHook.push(e):this.handleStaleModuleHook=[e]}}function getMatch(e,t){if(t[e])return e;let r=e.length;do{const o=e.slice(0,r+1);if(o in t)return o}while(-1!==(r=e.lastIndexOf("/",r-1)))}function targetWarning(e,t,r){hasConsole&&console.warn("Package target "+r+", resolving target '"+t+"' for "+e)}function applyPackages(e,t,r){const o=getMatch(e,t);if(o){const r=t[o];if(null===r)return;if(!(e.length>o.length&&"/"!==r[r.length-1])){return e.length>o.length&&"/"===r[r.length-1]&&r.lastIndexOf(o)===r.length-o.length?r.substring(0,r.lastIndexOf(o))+encodeURIComponent(e):r+e.slice(o.length)}targetWarning(o,r,"should have a trailing '/'")}else if(r&&!isUrl(e))return r+encodeURIComponent(e)}function resolveImportMapEntry(e,t,r){e.scopes||(e.scopes={}),e.imports||(e.imports={});const o=e.scopes;let s=r&&getMatch(r,o);for(;s;){const e=applyPackages(t,o[s]);if(e)return e;s=getMatch(s.slice(0,s.lastIndexOf("/")),o)}return applyPackages(t,e.imports,e.default)||isUrl(t)&&t||void 0}function resolveAndComposePackages(e,t,r,o,s){for(const n in e){const i=resolveIfNotPlainOrUrl(n,r)||n,a=e[n];if("string"!=typeof a)continue;const l=resolveImportMapEntry(o,resolveIfNotPlainOrUrl(a,r)||a,s);l?t[i]=l:targetWarning(n,a,"bare specifier did not resolve")}}function resolveAndComposeImportMap(e,t,r={imports:{},scopes:{}}){const o={imports:Object.assign({},r.imports),scopes:Object.assign({},r.scopes),default:e.default};if(e.imports&&resolveAndComposePackages(e.imports,o.imports,t,r),e.scopes)for(const s in e.scopes){const n=resolveUrl(s,t);resolveAndComposePackages(e.scopes[s],o.scopes[n]||(o.scopes[n]={}),t,r,n)}return e.default&&(o.default=resolveIfNotPlainOrUrl(e.default,t)),o}class ImportMapResolver{constructor(e){this.importMap=e}resolve(e,t){return resolveImportMapEntry(this.importMap,e,t)}}const IMPORTMAP_SCRIPT_TYPE="lwr-importmap";function iterateDocumentImportMaps(e,t){const r=document.querySelectorAll(`script[type="${IMPORTMAP_SCRIPT_TYPE}"]`+t),o=Array.from(r).filter((e=>!e.src||(hasConsole&&console.warn("LWR does not support import maps from script src"),!1)));Array.prototype.forEach.call(o,e)}async function getImportMapFromScript(e){return Promise.resolve(e.innerHTML)}async function evaluateImportMaps(e){let t={imports:{},scopes:{}},r=Promise.resolve(t);if(hasDocument){if(e||(e=getBaseUrl()),!e)throw new LoaderError(NO_BASE_URL);iterateDocumentImportMaps((o=>{r=r.then((()=>getImportMapFromScript(o))).then((e=>{try{return JSON.parse(e)}catch(e){throw new LoaderError(BAD_IMPORT_MAP)}})).then((r=>(t=resolveAndComposeImportMap(r,o.src||e,t),t)))}),"")}return r}class Loader{constructor(e){if(e&&(e=e.replace(/\/?$/,"/")),e||(e=getBaseUrl()),!e)throw new LoaderError(NO_BASE_URL);this.baseUrl=e,this.registry=new ModuleRegistry(e),this.services=Object.freeze({addLoaderPlugin:this.registry.addLoaderPlugin.bind(this.registry),handleStaleModule:this.registry.registerHandleStaleModuleHook.bind(this.registry)})}define(e,t,r,o){invariant("string"==typeof e,MISSING_NAME);let s=r,n=t,i=o;"function"==typeof n&&(s=t,n=[],i=r),i=i||{},invariant(Array.isArray(n),INVALID_DEPS),this.registry.define(e,n,s,i)}async load(e,t){return this.registry.load(e,t)}has(e){return this.registry.has(e)}async resolve(e,t){return this.registry.resolve(e,t)}async registerImportMappings(e){let t;if(t=e?resolveAndComposeImportMap(e,this.baseUrl,this.parentImportMap):await evaluateImportMaps(this.baseUrl),this.parentImportMap=t,this.parentImportMap){const e=new ImportMapResolver(this.parentImportMap);this.registry.setImportResolver(e)}}registerExternalModules(e){this.registry.registerExternalModules(e)}}exports.Loader=Loader,Object.defineProperty(exports,"__esModule",{value:!0})}));
7
+ /* LWR Legacy Module Loader Shim v0.6.2 */
8
+ !function(){"use strict";var e;let t;function r(e){t=e}!function(e){e[e.Start=0]="Start",e[e.End=1]="End"}(e||(e={}));const o=globalThis.performance,s=void 0!==o&&"function"==typeof o.mark&&"function"==typeof o.clearMarks&&"function"==typeof o.measure&&"function"==typeof o.clearMeasures;function n({id:r,specifier:n}){t?t({id:r,phase:e.Start,specifier:n}):s&&o.mark(r+(n?`.${n}`:""))}function i({id:r,specifier:n}){if(t)t({id:r,phase:e.End,specifier:n});else if(s){const e=n?`.${n}`:"",t=r+e,s=`${r}.duration${e}`;o.measure(s,t),o.clearMarks(t),o.clearMeasures(s)}}function a(e,t,o,s){const{autoBoot:n,customInit:i}=e;if(function(e,t){if(!e&&!t)throw new Error("The customInit hook is required when autoBoot is false");if(e&&t)throw new Error("The customInit hook must not be defined when autoBoot is true")}(n,i),i){i({initializeApp:t,define:o,onBootstrapError:s,attachDispatcher:r},e)}}const l="function"==typeof setTimeout,d="undefined"!=typeof console;const c=globalThis;c.LWR.requiredModules=c.LWR.requiredModules||[],c.LWR.requiredModules.indexOf("lwr/loaderLegacy/v/0_6_2")<0&&c.LWR.requiredModules.push("lwr/loaderLegacy/v/0_6_2"),new class{constructor(e){this.defineCache={},this.orderedDefs=[],this.global=e,this.config=e.LWR,this.loaderModule="lwr/loaderLegacy/v/0_6_2";const t=this.tempDefine.bind(this);e.LWR.define=t,this.bootReady=this.config.autoBoot,l&&(this.watchdogTimerId=this.startWatchdogTimer());try{a(Object.freeze(this.config),this.postCustomInit.bind(this),t,(e=>{this.errorHandler=e}))}catch(e){this.enterErrorState(e)}}canInit(){const e=this.config.requiredModules.every((e=>this.orderedDefs.includes(e)));return this.bootReady&&e}tempDefine(...e){const t=e[0];this.defineCache[t]=e,this.orderedDefs.push(t),this.canInit()&&(l&&clearTimeout(this.watchdogTimerId),this.initApp())}postCustomInit(){this.bootReady=!0,this.canInit()&&this.initApp()}initApp(){try{const e={baseUrl:this.config.baseUrl,profiler:{logOperationStart:n,logOperationEnd:i},appMetadata:{appId:this.config.appId,bootstrapModule:this.config.bootstrapModule,rootComponent:this.config.rootComponent,rootComponents:this.config.rootComponents}},t=function(e,t,r,o){if(!t||"function"!=typeof t[2])throw new Error(`Expected loader with specifier "${e}" to be a module`);const s={};t[2].call(null,s);const{Loader:n}=s,i=new n(r);return o&&o.length&&i.registerExternalModules(o),i.define(e,["exports"],(e=>{Object.assign(e,{define:i.define.bind(i),load:i.load.bind(i),services:i.services})}),t[3]),i}(this.loaderModule,this.defineCache[this.loaderModule],e,this.config.preloadModules);this.createProfilerModule(t),this.mountApp(t)}catch(e){this.enterErrorState(e)}}waitForDOMContentLoaded(){return void 0===typeof document||"interactive"===document.readyState||"complete"===document.readyState?Promise.resolve():new Promise((e=>{document.addEventListener("DOMContentLoaded",(()=>{e()}))}))}createProfilerModule(e){e.define("lwr/profiler/v/0_6_2",["exports"],(e=>{Object.assign(e,{logOperationStart:n,logOperationEnd:i})}),{})}mountApp(e){const{bootstrapModule:t,rootComponent:r,importMappings:o,rootComponents:s,endpoints:n}=this.config;this.global.LWR=Object.freeze({define:e.define.bind(e),rootComponent:r,rootComponents:s,importMappings:o,endpoints:n}),this.orderedDefs.forEach((t=>{t!==this.loaderModule&&e.define(...this.defineCache[t])}));const{disableInitDefer:i}=this.config;e.registerImportMappings(o).then((()=>{if(!i)return this.waitForDOMContentLoaded()})).then((()=>e.load(t))).catch((e=>{this.enterErrorState(new Error(`Application ${r} could not be loaded: ${e}`))}))}enterErrorState(e){n({id:"lwr.bootstrap.error"}),this.errorHandler?this.errorHandler(e):d&&console.error(`An error occurred during LWR bootstrap. ${e.message}`,e.stack)}startWatchdogTimer(){return setTimeout((()=>{this.enterErrorState(new Error("Failed to load required modules - timed out"))}),3e5)}}(c)}(),LWR.define("lwr/loaderLegacy/v/0_6_2",["exports"],(function(exports){"use strict";const templateRegex=/\{([0-9]+)\}/g;function templateString(e,t){return e.replace(templateRegex,((e,r)=>t[r]))}function generateErrorMessage(e,t){const r=Array.isArray(t)?templateString(e.message,t):e.message;return`LWR${e.code}: ${r}`}class LoaderError extends Error{constructor(e,t){super(),this.message=generateErrorMessage(e,t)}}function invariant(e,t){if(!e)throw new LoaderError(t)}const MISSING_NAME=Object.freeze({code:3e3,message:"A module name is required.",level:0}),FAIL_INSTANTIATE=Object.freeze({code:3004,message:"Failed to instantiate module: {0}",level:0}),NO_AMD_REQUIRE=Object.freeze({code:3005,message:"AMD require not supported.",level:0}),FAILED_DEP=Object.freeze({code:3006,level:0,message:"Failed to load dependency: {0}"}),INVALID_DEPS=Object.freeze({code:3007,message:"Unexpected value received for dependencies argument; expected an array.",level:0}),FAIL_LOAD=Object.freeze({code:3008,level:0,message:"Error loading {0}"}),UNRESOLVED=Object.freeze({code:3009,level:0,message:"Unable to resolve bare specifier: {0}"}),NO_BASE_URL=Object.freeze({code:3010,level:0,message:"baseUrl not set"});Object.freeze({code:3011,level:0,message:"Cannot set a loader service multiple times"});const INVALID_HOOK=Object.freeze({code:3012,level:0,message:"Invalid hook received"}),INVALID_LOADER_SERVICE_RESPONSE=Object.freeze({code:3013,level:0,message:"Invalid response received from hook"}),MODULE_LOAD_TIMEOUT=Object.freeze({code:3014,level:0,message:"Error loading {0} - timed out"}),HTTP_FAIL_LOAD=Object.freeze({code:3015,level:0,message:"Error loading {0}, status code {1}"}),STALE_HOOK_ERROR=Object.freeze({code:3016,level:0,message:"An error occurred handling module conflict"}),MODULE_ALREADY_LOADED=Object.freeze({code:3017,level:0,message:"Marking module(s) as externally loaded, but they are already loaded: {0}"}),FAIL_HOOK_LOAD=Object.freeze({code:3018,level:0,message:'Error loading "{0}" from hook'}),BAD_IMPORT_MAP=Object.freeze({code:3011,level:0,message:"import map is not valid"}),hasDocument="undefined"!=typeof document,hasSetTimeout="function"==typeof setTimeout,hasConsole="undefined"!=typeof console;function getBaseUrl(){let e;if(hasDocument){const t=document.querySelector("base[href]");e=t&&t.href}if(!e&&"undefined"!=typeof location){e=location.href.split("#")[0].split("?")[0];const t=e.lastIndexOf("/");-1!==t&&(e=e.slice(0,t+1))}return e}function isUrl(e){return-1!==e.indexOf("://")}function resolveIfNotPlainOrUrl(e,t){if(-1!==e.indexOf("\\")&&(e=e.replace(/\\/g,"/")),"/"===e[0]&&"/"===e[1])return t.slice(0,t.indexOf(":")+1)+e;if("."===e[0]&&("/"===e[1]||"."===e[1]&&("/"===e[2]||2===e.length&&(e+="/"))||1===e.length&&(e+="/"))||"/"===e[0]){const r=t.slice(0,t.indexOf(":")+1);let o;if("/"===t[r.length+1]?"file:"!==r?(o=t.slice(r.length+2),o=o.slice(o.indexOf("/")+1)):o=t.slice(8):o=t.slice(r.length+("/"===t[r.length]?1:0)),"/"===e[0])return t.slice(0,t.length-o.length-1)+e;const s=o.slice(0,o.lastIndexOf("/")+1)+e,n=[];let i=-1;for(let e=0;e<s.length;e++)-1!==i?"/"===s[e]&&(n.push(s.slice(i,e+1)),i=-1):"."===s[e]?"."!==s[e+1]||"/"!==s[e+2]&&e+2!==s.length?"/"===s[e+1]||e+1===s.length?e+=1:i=e:(n.pop(),e+=2):i=e;return-1!==i&&n.push(s.slice(i)),t.slice(0,t.length-o.length)+n.join("")}}function resolveUrl(e,t){return resolveIfNotPlainOrUrl(e,t)||(isUrl(e)?e:resolveIfNotPlainOrUrl("./"+e,t))}function createScript(e){const t=document.createElement("script");return t.charset="utf-8",t.async=!0,t.crossOrigin="anonymous",t.src=e,t}let lastWindowError$1,lastWindowErrorUrl;function loadModuleDef(e){return new Promise((function(t,r){if(hasDocument){const o=createScript(e);o.addEventListener("error",(()=>{r(new LoaderError(FAIL_LOAD,[e]))})),o.addEventListener("load",(()=>{document.head.removeChild(o),lastWindowErrorUrl===e?r(lastWindowError$1):t()})),document.head.appendChild(o)}}))}hasDocument&&window.addEventListener("error",(e=>{lastWindowErrorUrl=e.filename,lastWindowError$1=e.error}));const MODULE_LOAD_TIMEOUT_TIMER=3e5;let lastWindowError;function isCustomResponse(e){return Object.prototype.hasOwnProperty.call(e,"data")&&!Object.prototype.hasOwnProperty.call(e,"blob")}function isFetchResponse(e){return"function"==typeof e.blob}function isResponseAPromise(e){return!(!e||!e.then)}async function evaluateLoadHookResponse(response,id){return Promise.resolve().then((async()=>{if(!response.status)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);if(200!==response.status)throw new LoaderError(HTTP_FAIL_LOAD,[id,`${response.status}`]);const isResponse=isFetchResponse(response);let code;if(isCustomResponse(response))code=response.data;else{if(!isResponse)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);code=await response.text()}if(!code)throw new LoaderError(FAIL_LOAD,[id]);code=`${code}\n//# sourceURL=${id}`;try{eval(code)}catch(e){throw new LoaderError(FAIL_LOAD,[id])}if(lastWindowError)throw new LoaderError(FAIL_LOAD,[id]);return!0})).finally((()=>{}))}async function evaluateLoadHook(e,t){return hasSetTimeout?new Promise(((r,o)=>{const s=setTimeout((()=>{o(new LoaderError(MODULE_LOAD_TIMEOUT,[e]))}),MODULE_LOAD_TIMEOUT_TIMER);t.then((e=>{r(e)})).catch((()=>{o(new LoaderError(FAIL_HOOK_LOAD,[e]))})).finally((()=>{clearTimeout(s)}))})):t}function reportError(e){hasConsole&&console.error(e)}function evaluateHandleStaleModuleHooks(e,t){const{name:r,oldHash:o,newHash:s}=t;for(let t=0;t<e.length;t++){const n=e[t];try{if(null!==n({name:r,oldHash:o,newHash:s}))break}catch(e){reportError(new LoaderError(STALE_HOOK_ERROR))}}}hasDocument&&globalThis.addEventListener("error",(e=>{lastWindowError=e.error})),!hasSetTimeout&&hasConsole&&console.warn("setTimeout API is not available, watchdog timer on load hook will not be set");const LOADER_PREFIX="lwr.loader.",MODULE_DEFINE=`${LOADER_PREFIX}module.define`,MODULE_FETCH=`${LOADER_PREFIX}module.fetch`,MODULE_ERROR=`${LOADER_PREFIX}module.error`;class ModuleRegistry{constructor(e){this.namedDefineRegistry=new Map,this.moduleRegistry=new Map,this.baseUrl=e.baseUrl,this.profiler=e.profiler}async load(e,t){const r=await this.resolve(e,t),o=this.getModuleRecord(r,e);return o.evaluated?o.module:(o.evaluationPromise||(o.evaluationPromise=this.topLevelEvaluation(o)),o.evaluationPromise)}async resolve(e,t){const r=this.baseUrl;let o,s=e;const n=this.resolveHook;if(n){for(let e=0;e<n.length;e++){const t=(0,n[e])(s,{parentUrl:r});let i;if((t||null===t)&&(i=isResponseAPromise(t)?await t:t),null!==i){if("string"==typeof i){if(resolveIfNotPlainOrUrl(i,r))throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);s=i;continue}if(o=i&&i.url&&(resolveIfNotPlainOrUrl(i.url,r)||i.url),!o)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);break}}if(s!==e){if(!o&&this.namedDefineRegistry.has(s))return s;e=s}}if(!o){const t=resolveIfNotPlainOrUrl(e,r)||e;if(this.moduleRegistry.has(t))return t;if(this.resolver){if(o=this.resolver.resolve(t,r),this.namedDefineRegistry.has(t)&&this.namedDefineRegistry.get(t).defined){const e=this.moduleRegistry.get(o);if(!e||!e.aliases.has(t))return t}}else o=t}if(!o||!isUrl(o)){if(this.namedDefineRegistry.has(e))return e;throw new LoaderError(UNRESOLVED,[e])}return t&&isUrl(o)&&(o+=`?importer=${encodeURIComponent(t)}`),o}has(e){return this.moduleRegistry.has(e)}define(e,t,r,o){const s=this.namedDefineRegistry.get(e);if(s&&s.defined)return void(this.lastDefine=s);const n={name:e,dependencies:t,exporter:r,signatures:o,defined:!0};s&&s.external&&s.external.resolveExternal(n),this.profiler.logOperationStart({id:MODULE_DEFINE,specifier:e}),this.namedDefineRegistry.set(e,n),this.lastDefine=n,o.hashes&&Object.entries(o.hashes).forEach((([e,t])=>{this.checkModuleSignature(e,t)}))}registerExternalModules(e){const t=[];if(e.map((e=>{if(this.namedDefineRegistry.has(e))t.push(e);else{let t,r;const o=new Promise(((o,s)=>{t=o,r=setTimeout((()=>{s(new LoaderError(MODULE_LOAD_TIMEOUT,[e]))}),MODULE_LOAD_TIMEOUT_TIMER)})).finally((()=>{clearTimeout(r)})),s={name:e,defined:!1,external:{resolveExternal:t,moduleDefPromise:o}};this.namedDefineRegistry.set(e,s)}})),t.length)throw new LoaderError(MODULE_ALREADY_LOADED,[t.join(", ")])}checkModuleSignature(e,t){const r=this.namedDefineRegistry.get(e);if(!r){const r={name:e,signatures:{ownHash:t},defined:!1};return void this.namedDefineRegistry.set(e,r)}const o=r.signatures?r.signatures.ownHash:void 0;if(o&&t!==o){const r=this.handleStaleModuleHook;r?evaluateHandleStaleModuleHooks(r,{name:e,oldHash:o,newHash:t}):hasConsole&&console.warn(`stale module detected ${e}, current sig:${o}, new sig:${t}`)}}setImportResolver(e){this.resolver=e}getModuleRecord(e,t){let r=this.moduleRegistry.get(e);if(r)return r.aliases.has(t)||r.aliases.add(t),r;const o=this.getModuleDef(e,t),s=o.then((e=>{const t=e.dependencies.map((e=>{if("exports"!==e)return invariant("require"!==e,NO_AMD_REQUIRE),this.getModuleDependencyRecord.call(this,e)})).filter((e=>void 0!==e));return Promise.all(t)}));return r={id:e,aliases:new Set([t]),module:Object.create(null),dependencyRecords:s,instantiation:o,evaluated:!1,evaluationPromise:null},this.moduleRegistry.set(e,r),r}async getModuleDependencyRecord(e){const t=await this.resolve(e);return this.getModuleRecord(t,e)}async topLevelEvaluation(e){return await this.instantiateAll(e,{}),this.evaluateModule(e,{})}async instantiateAll(e,t){if(!t[e.id]){t[e.id]=!0;const r=await e.dependencyRecords;if(r)for(let e=0;e<r.length;e++){const o=r[e];await this.instantiateAll(o,t)}}}async evaluateModule(e,t){const r=await e.dependencyRecords;r.length>0&&(t[e.id]=!0,await this.evaluateModuleDependencies(r,t));const{exporter:o,dependencies:s}=await e.instantiation,n={},i=await Promise.all(s.map((async e=>{if("exports"===e)return n;const t=await this.resolve(e),r=this.moduleRegistry.get(t);if(!r)throw new LoaderError(FAILED_DEP,[t]);const o=r.module;if(!r.evaluated)return this.getCircularDependencyWrapper(o);if(o)return o.__defaultInterop?o.default:o;throw new LoaderError(FAILED_DEP,[t])})));if(e.evaluated)return e.module;let a=o(...i);void 0!==a?(a={default:a},Object.defineProperty(a,"__defaultInterop",{value:!0})):this.isNamedExportDefaultOnly(n)&&Object.defineProperty(n,"__useDefault",{value:!0});const l=a||n;for(const t in l)Object.defineProperty(e.module,t,{enumerable:!0,set(e){l[t]=e},get:()=>l[t]});return l.__useDefault&&Object.defineProperty(e.module,"__useDefault",{value:!0}),l.__defaultInterop&&Object.defineProperty(e.module,"__defaultInterop",{value:!0}),l.__esModule&&Object.defineProperty(e.module,"__esModule",{value:!0}),e.evaluated=!0,Object.freeze(e.module),e.module}isNamedExportDefaultOnly(e){return void 0!==e&&2===Object.getOwnPropertyNames(e).length&&Object.prototype.hasOwnProperty.call(e,"default")&&Object.prototype.hasOwnProperty.call(e,"__esModule")}getCircularDependencyWrapper(e){const t=()=>e.__useDefault||e.__defaultInterop?e.default:e;return t.__circular__=!0,t}async evaluateModuleDependencies(e,t){for(let r=0;r<e.length;r++){const o=e[r];o.evaluated||t[o.id]||(t[o.id]=!0,await this.evaluateModule(o,t))}}async getModuleDef(e,t){this.lastDefine=void 0;const r=isUrl(e)?t!==e?t:void 0:e;let o=r&&this.namedDefineRegistry.get(r);if(o&&o.external)return o.external.moduleDefPromise;if(o&&o.defined)return o;const s=this.baseUrl,n=r||t;return this.profiler.logOperationStart({id:MODULE_FETCH,specifier:n}),Promise.resolve().then((async()=>{const t=this.loadHook;if(t)for(let r=0;r<t.length;r++){const o=(0,t[r])(e,s),n=isResponseAPromise(o)?await evaluateLoadHook(e,o):o;if(void 0===n)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);if(n&&null!==n)return evaluateLoadHookResponse(n,e)}return!1})).then((t=>{if(!0!==t&&hasDocument)return loadModuleDef(e)})).then((()=>{if(o=r&&this.namedDefineRegistry.get(r),o||(o=this.lastDefine),!o)throw new LoaderError(FAIL_INSTANTIATE,[e]);return this.profiler.logOperationEnd({id:MODULE_FETCH,specifier:n}),o})).catch((e=>{throw this.profiler.logOperationStart({id:MODULE_ERROR,specifier:n}),e}))}addLoaderPlugin(e){if("object"!=typeof e)throw new LoaderError(INVALID_HOOK);const{loadModule:t,resolveModule:r}=e;r&&(this.resolveHook?this.resolveHook.push(r):this.resolveHook=[r]),t&&(this.loadHook?this.loadHook.push(t):this.loadHook=[t])}registerHandleStaleModuleHook(e){this.handleStaleModuleHook?this.handleStaleModuleHook.push(e):this.handleStaleModuleHook=[e]}}function getMatch(e,t){if(t[e])return e;let r=e.length;do{const o=e.slice(0,r+1);if(o in t)return o}while(-1!==(r=e.lastIndexOf("/",r-1)))}function targetWarning(e,t,r){hasConsole&&console.warn("Package target "+r+", resolving target '"+t+"' for "+e)}function applyPackages(e,t,r){const o=getMatch(e,t);if(o){const r=t[o];if(null===r)return;if(!(e.length>o.length&&"/"!==r[r.length-1])){return e.length>o.length&&"/"===r[r.length-1]&&r.lastIndexOf(o)===r.length-o.length?r.substring(0,r.lastIndexOf(o))+encodeURIComponent(e):r+e.slice(o.length)}targetWarning(o,r,"should have a trailing '/'")}else if(r&&!isUrl(e))return r+encodeURIComponent(e)}function resolveImportMapEntry(e,t,r){e.scopes||(e.scopes={}),e.imports||(e.imports={});const o=e.scopes;let s=r&&getMatch(r,o);for(;s;){const e=applyPackages(t,o[s]);if(e)return e;s=getMatch(s.slice(0,s.lastIndexOf("/")),o)}return applyPackages(t,e.imports,e.default)||isUrl(t)&&t||void 0}function resolveAndComposePackages(e,t,r,o,s){for(const n in e){const i=resolveIfNotPlainOrUrl(n,r)||n,a=e[n];if("string"!=typeof a)continue;const l=resolveImportMapEntry(o,resolveIfNotPlainOrUrl(a,r)||a,s);l?t[i]=l:targetWarning(n,a,"bare specifier did not resolve")}}function resolveAndComposeImportMap(e,t,r={imports:{},scopes:{}}){const o={imports:Object.assign({},r.imports),scopes:Object.assign({},r.scopes),default:e.default};if(e.imports&&resolveAndComposePackages(e.imports,o.imports,t,r),e.scopes)for(const s in e.scopes){const n=resolveUrl(s,t);resolveAndComposePackages(e.scopes[s],o.scopes[n]||(o.scopes[n]={}),t,r,n)}return e.default&&(o.default=resolveIfNotPlainOrUrl(e.default,t)),o}class ImportMapResolver{constructor(e){this.importMap=e}resolve(e,t){return resolveImportMapEntry(this.importMap,e,t)}}const IMPORTMAP_SCRIPT_TYPE="lwr-importmap";function iterateDocumentImportMaps(e,t){const r=document.querySelectorAll(`script[type="${IMPORTMAP_SCRIPT_TYPE}"]`+t),o=Array.from(r).filter((e=>!e.src||(hasConsole&&console.warn("LWR does not support import maps from script src"),!1)));Array.prototype.forEach.call(o,e)}async function getImportMapFromScript(e){return Promise.resolve(e.innerHTML)}async function evaluateImportMaps(e){let t={imports:{},scopes:{}},r=Promise.resolve(t);if(hasDocument){if(e||(e=getBaseUrl()),!e)throw new LoaderError(NO_BASE_URL);iterateDocumentImportMaps((o=>{r=r.then((()=>getImportMapFromScript(o))).then((e=>{try{return JSON.parse(e)}catch(e){throw new LoaderError(BAD_IMPORT_MAP)}})).then((r=>(t=resolveAndComposeImportMap(r,o.src||e,t),t)))}),"")}return r}class Loader{constructor(e){let t=(e=e||{}).baseUrl,r=e.profiler;if(t&&(t=t.replace(/\/?$/,"/")),t||(t=getBaseUrl()),!t)throw new LoaderError(NO_BASE_URL);this.baseUrl=t,r||(r={logOperationStart:()=>{},logOperationEnd:()=>{}}),this.registry=new ModuleRegistry({baseUrl:t,profiler:r}),this.services=Object.freeze({addLoaderPlugin:this.registry.addLoaderPlugin.bind(this.registry),handleStaleModule:this.registry.registerHandleStaleModuleHook.bind(this.registry),appMetadata:e.appMetadata})}define(e,t,r,o){invariant("string"==typeof e,MISSING_NAME);let s=r,n=t,i=o;"function"==typeof n&&(s=t,n=[],i=r),i=i||{},invariant(Array.isArray(n),INVALID_DEPS),this.registry.define(e,n,s,i)}async load(e,t){return this.registry.load(e,t)}has(e){return this.registry.has(e)}async resolve(e,t){return this.registry.resolve(e,t)}async registerImportMappings(e){let t;if(t=e?resolveAndComposeImportMap(e,this.baseUrl,this.parentImportMap):await evaluateImportMaps(this.baseUrl),this.parentImportMap=t,this.parentImportMap){const e=new ImportMapResolver(this.parentImportMap);this.registry.setImportResolver(e)}}registerExternalModules(e){this.registry.registerExternalModules(e)}}exports.Loader=Loader,Object.defineProperty(exports,"__esModule",{value:!0})}));
@@ -4,227 +4,303 @@
4
4
  * SPDX-License-Identifier: MIT
5
5
  * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
6
6
  */
7
- /* LWR Legacy Module Loader Shim v0.6.0-alpha.9 */
7
+ /* LWR Legacy Module Loader Shim v0.6.2 */
8
8
  (function () {
9
- 'use strict';
9
+ 'use strict';
10
10
 
11
- function createLoader(name, definition, baseUrl, externalModules) {
12
- if (!definition || typeof definition[2] !== 'function') {
13
- throw new Error(`Expected loader with specifier "${name}" to be a module`);
14
- }
15
- // Create a Loader instance
16
- const exports = {};
17
- definition[2].call(null, exports);
18
- const { Loader } = exports;
19
- const loader = new Loader(baseUrl);
20
- // register externally loaded modules
21
- if (externalModules && externalModules.length) {
22
- loader.registerExternalModules(externalModules);
23
- }
24
- // Define the loader module with public API: { define, load, services }
25
- const exporter = (exports) => {
26
- Object.assign(exports, {
27
- define: loader.define.bind(loader),
28
- load: loader.load.bind(loader),
29
- services: loader.services,
30
- });
31
- return;
32
- };
33
- loader.define(name, ['exports'], exporter, definition[3]);
34
- return loader;
35
- }
11
+ // Bootstrap / shim
12
+ const BOOTSTRAP_PREFIX = 'lwr.bootstrap.';
13
+ const BOOTSTRAP_ERROR = `${BOOTSTRAP_PREFIX}error`;
36
14
 
37
- const REQUIRED_MODULES_TIMEOUT = 300 * 1000;
15
+ var Phase;
38
16
 
39
- var Phase;
40
- (function (Phase) {
41
- Phase[Phase["Start"] = 0] = "Start";
42
- })(Phase || (Phase = {}));
43
- function attachDispatcher(dispatcher) {
44
- }
17
+ (function (Phase) {
18
+ Phase[Phase["Start"] = 0] = "Start";
19
+ Phase[Phase["End"] = 1] = "End";
20
+ })(Phase || (Phase = {}));
45
21
 
46
- // Check for errors with autoBoot and customInit
47
- function validatePreInit(autoBoot, customInit) {
48
- // If autoBoot === false, there must be a customInit hook
49
- if (!autoBoot && !customInit) {
50
- throw new Error('The customInit hook is required when autoBoot is false');
51
- }
52
- // If autoBoot === true, there must NOT be a customInit hook
53
- if (autoBoot && customInit) {
54
- throw new Error('The customInit hook must not be defined when autoBoot is true');
55
- }
56
- }
57
- // Process the customInit hook
58
- function customInit(config, initializeApp, define, onBootstrapError) {
59
- // Validate config
60
- const { autoBoot, customInit } = config;
61
- validatePreInit(autoBoot, customInit);
62
- // Set up arguments and call the customInit hook, if available
63
- if (customInit) {
64
- const lwr = {
65
- initializeApp,
66
- define,
67
- onBootstrapError,
68
- attachDispatcher,
69
- };
70
- customInit(lwr, config);
71
- }
72
- }
22
+ // Attach a custom dispatcher
23
+ let customDispatcher;
24
+ function attachDispatcher(dispatcher) {
25
+ customDispatcher = dispatcher;
26
+ } // Check if the Performance API is available
27
+ // e.g. JSDom (used in Jest) doesn't implement these
28
+
29
+ const perf = globalThis.performance;
30
+ const isPerfSupported = typeof perf !== 'undefined' && typeof perf.mark === 'function' && typeof perf.clearMarks === 'function' && typeof perf.measure === 'function' && typeof perf.clearMeasures === 'function'; // For marking request metrics
31
+ // Fallback to the Performance API if there is no custom dispatcher
73
32
 
74
- /* global document */
75
- /* eslint-disable lwr/no-unguarded-apis */
76
- const hasSetTimeout = typeof setTimeout === 'function';
77
- const hasConsole = typeof console !== 'undefined';
78
- /* eslint-enable lwr/no-unguarded-apis */
79
- class LoaderShim {
80
- constructor(global) {
81
- this.defineCache = {};
82
- this.orderedDefs = [];
83
- // Parse configuration
84
- this.global = global;
85
- this.config = global.LWR;
86
- this.loaderModule = 'lwr/loaderLegacy/v/0_6_0-alpha_9';
87
- // Set up the temporary LWR.define function and customInit hook
88
- const tempDefine = this.tempDefine.bind(this);
89
- global.LWR.define = tempDefine;
90
- this.bootReady = this.config.autoBoot;
91
- // Start watchdog timer
92
- if (hasSetTimeout) {
93
- this.watchdogTimerId = this.startWatchdogTimer();
94
- }
95
- try {
96
- customInit(Object.freeze(this.config), this.postCustomInit.bind(this), tempDefine, (e) => {
97
- this.errorHandler = e;
98
- });
99
- }
100
- catch (e) {
101
- this.enterErrorState(e);
102
- }
103
- }
104
- // Return true if the app can be initialized
105
- canInit() {
106
- // Initialize the app if:
107
- // - bootReady: autoBoot is on OR customInit has finished
108
- // - all required modules are defined
109
- const allDefined = this.config.requiredModules.every((m) => this.orderedDefs.includes(m));
110
- return this.bootReady && allDefined;
111
- }
112
- /**
113
- * Create a temporary LWR.define() function which captures all
114
- * calls that occur BEFORE the full loader module is available
115
- *
116
- * Each call to LWR.define() is stored in 2 ways:
117
- * - in a map as [moduleName, arguments] pairs
118
- * - each moduleName is pushed onto an array, to preserve
119
- * the order in which the modules were defined
120
- */
121
- tempDefine(...args) {
122
- // Cache the incoming module
123
- const moduleName = args[0];
124
- this.defineCache[moduleName] = args;
125
- this.orderedDefs.push(moduleName);
126
- if (this.canInit()) {
127
- if (hasSetTimeout) {
128
- // requiredModules are defined, clear watchdog timer
129
- // eslint-disable-next-line lwr/no-unguarded-apis, no-undef
130
- clearTimeout(this.watchdogTimerId);
131
- }
132
- this.initApp();
133
- }
134
- }
135
- // Called by the customInit hook via lwr.initializeApp()
136
- postCustomInit() {
137
- this.bootReady = true;
138
- if (this.canInit()) {
139
- this.initApp();
140
- }
141
- }
142
- // Create the loader and initialize the application
143
- initApp() {
144
- try {
145
- const loader = createLoader(this.loaderModule, this.defineCache[this.loaderModule], this.config.baseUrl, this.config.preloadModules);
146
- this.mountApp(loader);
147
- }
148
- catch (e) {
149
- this.enterErrorState(e);
150
- }
151
- }
152
- waitForDOMContentLoaded() {
153
- // eslint-disable-next-line lwr/no-unguarded-apis
154
- if (typeof document === undefined) {
155
- return Promise.resolve();
156
- }
157
- // Resolve if document is already "ready" https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState
158
- // eslint-disable-next-line lwr/no-unguarded-apis
159
- if (document.readyState === 'interactive' || document.readyState === 'complete') {
160
- return Promise.resolve();
161
- }
162
- return new Promise((resolve) => {
163
- // eslint-disable-next-line lwr/no-unguarded-apis
164
- document.addEventListener('DOMContentLoaded', () => {
165
- resolve();
166
- });
167
- });
168
- }
169
- // Set up the application globals, import map, root custom element...
170
- mountApp(loader) {
171
- const { bootstrapModule, rootComponent, importMappings, rootComponents, endpoints } = this.config;
172
- // Set global LWR.define to loader.define
173
- this.global.LWR = Object.freeze({
174
- define: loader.define.bind(loader),
175
- rootComponent,
176
- rootComponents,
177
- importMappings,
178
- endpoints,
179
- });
180
- // Redefine all modules in the temporary cache
181
- this.orderedDefs.forEach((specifier) => {
182
- if (specifier !== this.loaderModule) {
183
- loader.define(...this.defineCache[specifier]);
184
- }
185
- });
186
- // by default, app initialization is gated on waiting for document to be parsed (via DOMContentLoaded)
187
- const { disableInitDefer } = this.config;
188
- // Load the import mappings and application bootstrap module
189
- loader
190
- .registerImportMappings(importMappings)
191
- .then(() => {
192
- if (!disableInitDefer) {
193
- return this.waitForDOMContentLoaded();
194
- }
195
- })
196
- .then(() => loader.load(bootstrapModule))
197
- .catch((reason) => {
198
- this.enterErrorState(new Error(`Application ${rootComponent} could not be loaded: ${reason}`));
199
- });
200
- }
201
- // Trigger bootstrap error state, and call error handler if registered
202
- enterErrorState(error) {
203
- if (this.errorHandler) {
204
- this.errorHandler(error);
205
- }
206
- else {
207
- if (hasConsole) {
208
- // eslint-disable-next-line lwr/no-unguarded-apis, no-undef
209
- console.error(`An error occurred during LWR bootstrap. ${error.message}`, error.stack);
210
- }
211
- }
212
- }
213
- // eslint-disable-next-line no-undef, lwr/no-unguarded-apis
214
- startWatchdogTimer() {
215
- // eslint-disable-next-line lwr/no-unguarded-apis, no-undef
216
- return setTimeout(() => {
217
- this.enterErrorState(new Error('Failed to load required modules - timed out'));
218
- }, REQUIRED_MODULES_TIMEOUT);
219
- }
33
+ function logOperationStart({
34
+ id,
35
+ specifier
36
+ }) {
37
+ if (customDispatcher) {
38
+ customDispatcher({
39
+ id,
40
+ phase: Phase.Start,
41
+ specifier
42
+ });
43
+ } else if (isPerfSupported) {
44
+ perf.mark(id + (specifier ? `.${specifier}` : ''));
220
45
  }
46
+ } // For measuring duration metrics
47
+ // Fallback to the Performance API if there is no custom dispatcher
48
+
49
+ /* istanbul ignore next */
221
50
 
222
- // The loader module is ALWAYS required
223
- const GLOBAL = globalThis;
224
- GLOBAL.LWR.requiredModules = GLOBAL.LWR.requiredModules || [];
225
- if (GLOBAL.LWR.requiredModules.indexOf('lwr/loaderLegacy/v/0_6_0-alpha_9') < 0) {
226
- GLOBAL.LWR.requiredModules.push('lwr/loaderLegacy/v/0_6_0-alpha_9');
51
+ function logOperationEnd({
52
+ id,
53
+ specifier
54
+ }) {
55
+ if (customDispatcher) {
56
+ customDispatcher({
57
+ id,
58
+ phase: Phase.End,
59
+ specifier
60
+ });
61
+ } else if (isPerfSupported) {
62
+ const suffix = specifier ? `.${specifier}` : '';
63
+ const markName = id + suffix;
64
+ const measureName = `${id}.duration${suffix}`;
65
+ perf.measure(measureName, markName); // Clear the created mark and measure to avoid filling the performance entry buffer
66
+ // Even if they get deleted, existing PerformanceObservers preserve copies of the entries
67
+
68
+ perf.clearMarks(markName);
69
+ perf.clearMeasures(measureName);
227
70
  }
228
- new LoaderShim(GLOBAL);
71
+ }
72
+
73
+ function createLoader(name, definition, config, externalModules) {
74
+ if (!definition || typeof definition[2] !== 'function') {
75
+ throw new Error(`Expected loader with specifier "${name}" to be a module`);
76
+ }
77
+ // Create a Loader instance
78
+ const exports = {};
79
+ definition[2].call(null, exports);
80
+ const { Loader } = exports;
81
+ const loader = new Loader(config);
82
+ // register externally loaded modules
83
+ if (externalModules && externalModules.length) {
84
+ loader.registerExternalModules(externalModules);
85
+ }
86
+ // Define the loader module with public API: { define, load, services }
87
+ const exporter = (exports) => {
88
+ Object.assign(exports, {
89
+ define: loader.define.bind(loader),
90
+ load: loader.load.bind(loader),
91
+ services: loader.services,
92
+ });
93
+ return;
94
+ };
95
+ loader.define(name, ['exports'], exporter, definition[3]);
96
+ return loader;
97
+ }
98
+
99
+ const REQUIRED_MODULES_TIMEOUT = 300 * 1000;
100
+
101
+ // Check for errors with autoBoot and customInit
102
+ function validatePreInit(autoBoot, customInit) {
103
+ // If autoBoot === false, there must be a customInit hook
104
+ if (!autoBoot && !customInit) {
105
+ throw new Error('The customInit hook is required when autoBoot is false');
106
+ }
107
+ // If autoBoot === true, there must NOT be a customInit hook
108
+ if (autoBoot && customInit) {
109
+ throw new Error('The customInit hook must not be defined when autoBoot is true');
110
+ }
111
+ }
112
+ // Process the customInit hook
113
+ function customInit(config, initializeApp, define, onBootstrapError) {
114
+ // Validate config
115
+ const { autoBoot, customInit } = config;
116
+ validatePreInit(autoBoot, customInit);
117
+ // Set up arguments and call the customInit hook, if available
118
+ if (customInit) {
119
+ const lwr = {
120
+ initializeApp,
121
+ define,
122
+ onBootstrapError,
123
+ attachDispatcher,
124
+ };
125
+ customInit(lwr, config);
126
+ }
127
+ }
128
+
129
+ /* global document */
130
+ /* eslint-disable lwr/no-unguarded-apis */
131
+ const hasSetTimeout = typeof setTimeout === 'function';
132
+ const hasConsole = typeof console !== 'undefined';
133
+ /* eslint-enable lwr/no-unguarded-apis */
134
+ class LoaderShim {
135
+ constructor(global) {
136
+ this.defineCache = {};
137
+ this.orderedDefs = [];
138
+ // Parse configuration
139
+ this.global = global;
140
+ this.config = global.LWR;
141
+ this.loaderModule = 'lwr/loaderLegacy/v/0_6_2';
142
+ // Set up the temporary LWR.define function and customInit hook
143
+ const tempDefine = this.tempDefine.bind(this);
144
+ global.LWR.define = tempDefine;
145
+ this.bootReady = this.config.autoBoot;
146
+ // Start watchdog timer
147
+ if (hasSetTimeout) {
148
+ this.watchdogTimerId = this.startWatchdogTimer();
149
+ }
150
+ try {
151
+ customInit(Object.freeze(this.config), this.postCustomInit.bind(this), tempDefine, (e) => {
152
+ this.errorHandler = e;
153
+ });
154
+ }
155
+ catch (e) {
156
+ this.enterErrorState(e);
157
+ }
158
+ }
159
+ // Return true if the app can be initialized
160
+ canInit() {
161
+ // Initialize the app if:
162
+ // - bootReady: autoBoot is on OR customInit has finished
163
+ // - all required modules are defined
164
+ const allDefined = this.config.requiredModules.every((m) => this.orderedDefs.includes(m));
165
+ return this.bootReady && allDefined;
166
+ }
167
+ /**
168
+ * Create a temporary LWR.define() function which captures all
169
+ * calls that occur BEFORE the full loader module is available
170
+ *
171
+ * Each call to LWR.define() is stored in 2 ways:
172
+ * - in a map as [moduleName, arguments] pairs
173
+ * - each moduleName is pushed onto an array, to preserve
174
+ * the order in which the modules were defined
175
+ */
176
+ tempDefine(...args) {
177
+ // Cache the incoming module
178
+ const moduleName = args[0];
179
+ this.defineCache[moduleName] = args;
180
+ this.orderedDefs.push(moduleName);
181
+ if (this.canInit()) {
182
+ if (hasSetTimeout) {
183
+ // requiredModules are defined, clear watchdog timer
184
+ // eslint-disable-next-line lwr/no-unguarded-apis, no-undef
185
+ clearTimeout(this.watchdogTimerId);
186
+ }
187
+ this.initApp();
188
+ }
189
+ }
190
+ // Called by the customInit hook via lwr.initializeApp()
191
+ postCustomInit() {
192
+ this.bootReady = true;
193
+ if (this.canInit()) {
194
+ this.initApp();
195
+ }
196
+ }
197
+ // Create the loader and initialize the application
198
+ initApp() {
199
+ try {
200
+ const loaderConfig = {
201
+ baseUrl: this.config.baseUrl,
202
+ profiler: { logOperationStart, logOperationEnd },
203
+ // TODO: can be removed following https://github.com/salesforce/lwr/issues/1087
204
+ appMetadata: {
205
+ appId: this.config.appId,
206
+ bootstrapModule: this.config.bootstrapModule,
207
+ rootComponent: this.config.rootComponent,
208
+ rootComponents: this.config.rootComponents,
209
+ },
210
+ };
211
+ const loader = createLoader(this.loaderModule, this.defineCache[this.loaderModule], loaderConfig, this.config.preloadModules);
212
+ this.createProfilerModule(loader);
213
+ this.mountApp(loader);
214
+ }
215
+ catch (e) {
216
+ this.enterErrorState(e);
217
+ }
218
+ }
219
+ waitForDOMContentLoaded() {
220
+ // eslint-disable-next-line lwr/no-unguarded-apis
221
+ if (typeof document === undefined) {
222
+ return Promise.resolve();
223
+ }
224
+ // Resolve if document is already "ready" https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState
225
+ // eslint-disable-next-line lwr/no-unguarded-apis
226
+ if (document.readyState === 'interactive' || document.readyState === 'complete') {
227
+ return Promise.resolve();
228
+ }
229
+ return new Promise((resolve) => {
230
+ // eslint-disable-next-line lwr/no-unguarded-apis
231
+ document.addEventListener('DOMContentLoaded', () => {
232
+ resolve();
233
+ });
234
+ });
235
+ }
236
+ // Create a module out of the profiler
237
+ // Note: The profiler is also available as a module through lwc module resolution (see package.json)
238
+ createProfilerModule(loader) {
239
+ const exporter = (exports) => {
240
+ Object.assign(exports, { logOperationStart, logOperationEnd });
241
+ };
242
+ loader.define('lwr/profiler/v/0_6_2', ['exports'], exporter, {});
243
+ }
244
+ // Set up the application globals, import map, root custom element...
245
+ mountApp(loader) {
246
+ const { bootstrapModule, rootComponent, importMappings, rootComponents, endpoints } = this.config;
247
+ // Set global LWR.define to loader.define
248
+ this.global.LWR = Object.freeze({
249
+ define: loader.define.bind(loader),
250
+ rootComponent,
251
+ rootComponents,
252
+ importMappings,
253
+ endpoints,
254
+ });
255
+ // Redefine all modules in the temporary cache
256
+ this.orderedDefs.forEach((specifier) => {
257
+ if (specifier !== this.loaderModule) {
258
+ loader.define(...this.defineCache[specifier]);
259
+ }
260
+ });
261
+ // by default, app initialization is gated on waiting for document to be parsed (via DOMContentLoaded)
262
+ const { disableInitDefer } = this.config;
263
+ // Load the import mappings and application bootstrap module
264
+ loader
265
+ .registerImportMappings(importMappings)
266
+ .then(() => {
267
+ if (!disableInitDefer) {
268
+ return this.waitForDOMContentLoaded();
269
+ }
270
+ })
271
+ .then(() => loader.load(bootstrapModule))
272
+ .catch((reason) => {
273
+ this.enterErrorState(new Error(`Application ${rootComponent} could not be loaded: ${reason}`));
274
+ });
275
+ }
276
+ // Trigger bootstrap error state, and call error handler if registered
277
+ enterErrorState(error) {
278
+ logOperationStart({ id: BOOTSTRAP_ERROR });
279
+ if (this.errorHandler) {
280
+ this.errorHandler(error);
281
+ }
282
+ else {
283
+ if (hasConsole) {
284
+ // eslint-disable-next-line lwr/no-unguarded-apis, no-undef
285
+ console.error(`An error occurred during LWR bootstrap. ${error.message}`, error.stack);
286
+ }
287
+ }
288
+ }
289
+ // eslint-disable-next-line no-undef, lwr/no-unguarded-apis
290
+ startWatchdogTimer() {
291
+ // eslint-disable-next-line lwr/no-unguarded-apis, no-undef
292
+ return setTimeout(() => {
293
+ this.enterErrorState(new Error('Failed to load required modules - timed out'));
294
+ }, REQUIRED_MODULES_TIMEOUT);
295
+ }
296
+ }
297
+
298
+ // The loader module is ALWAYS required
299
+ const GLOBAL = globalThis;
300
+ GLOBAL.LWR.requiredModules = GLOBAL.LWR.requiredModules || [];
301
+ if (GLOBAL.LWR.requiredModules.indexOf('lwr/loaderLegacy/v/0_6_2') < 0) {
302
+ GLOBAL.LWR.requiredModules.push('lwr/loaderLegacy/v/0_6_2');
303
+ }
304
+ new LoaderShim(GLOBAL);
229
305
 
230
306
  }());