@servicetitan/web-components 39.2.0 → 40.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/common.d.ts +1 -0
- package/dist/common.d.ts.map +1 -1
- package/dist/common.js +1 -1
- package/dist/common.js.map +1 -1
- package/dist/loader.js +3 -1
- package/dist/loader.js.map +1 -1
- package/dist/utils/get-bundle-info.d.ts +1 -0
- package/dist/utils/get-bundle-info.d.ts.map +1 -1
- package/dist/utils/get-bundle-info.js +2 -0
- package/dist/utils/get-bundle-info.js.map +1 -1
- package/dist/utils/get-mfe-supports-versioned-ld-client.d.ts +3 -0
- package/dist/utils/get-mfe-supports-versioned-ld-client.d.ts.map +1 -0
- package/dist/utils/get-mfe-supports-versioned-ld-client.js +11 -0
- package/dist/utils/get-mfe-supports-versioned-ld-client.js.map +1 -0
- package/dist/utils/load-scripts.d.ts.map +1 -1
- package/dist/utils/load-scripts.js +18 -2
- package/dist/utils/load-scripts.js.map +1 -1
- package/package.json +11 -12
- package/src/__tests__/loader.test.tsx +113 -48
- package/src/common.ts +1 -1
- package/src/loader.tsx +7 -3
- package/src/utils/__tests__/get-mfe-supports-versioned-ld-client.test.ts +38 -0
- package/src/utils/__tests__/load-scripts.test.ts +172 -0
- package/src/utils/get-bundle-info.ts +2 -0
- package/src/utils/get-mfe-supports-versioned-ld-client.ts +12 -0
- package/src/utils/load-scripts.ts +19 -2
package/dist/common.d.ts
CHANGED
|
@@ -38,6 +38,7 @@ interface GetJsonOptions extends RequestInit {
|
|
|
38
38
|
retryDelay?: number;
|
|
39
39
|
onRequestError?(error: GetJsonError): void;
|
|
40
40
|
}
|
|
41
|
+
export declare function createNetworkError(message: string): Error;
|
|
41
42
|
export declare function getJson<T = any>(url: string, { retries, retryDelay, onRequestError, ...config }?: GetJsonOptions): Promise<{
|
|
42
43
|
data: T;
|
|
43
44
|
headers: Headers;
|
package/dist/common.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|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,CAAC;CAC1B;AAED,MAAM,WAAW,aAAa;IAC1B,OAAO,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;CACnC;AAED,MAAM,WAAW,YAAY;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CAChB;AAED,UAAU,cAAe,SAAQ,WAAW;IACxC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,cAAc,CAAC,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CAAC;CAC9C;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,SAMjD;AAED,wBAAsB,OAAO,CAAC,CAAC,GAAG,GAAG,EACjC,GAAG,EAAE,MAAM,EACX,EAAE,OAAW,EAAE,UAAiB,EAAE,cAAc,EAAE,GAAG,MAAM,EAAE,GAAE,cAAmB,GACnF,OAAO,CAAC;IAAE,IAAI,EAAE,CAAC,CAAC;IAAC,OAAO,EAAE,OAAO,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAAC,CAiDrD"}
|
package/dist/common.js
CHANGED
|
@@ -4,7 +4,7 @@ export const EXPOSED_DEPENDENCIES_TOKEN = symbolToken('EXPOSED_DEPENDENCIES_TOKE
|
|
|
4
4
|
export const EXPOSED_INSTANCE_DEPENDENCIES_TOKEN = symbolToken('EXPOSED_INSTANCE_DEPENDENCIES_TOKEN');
|
|
5
5
|
export const IS_WEB_COMPONENT_TOKEN = symbolToken('IS_WEB_COMPONENT_TOKEN');
|
|
6
6
|
export const RENDER_ROOT_TOKEN = symbolToken('RENDER_ROOT_TOKEN');
|
|
7
|
-
function createNetworkError(message) {
|
|
7
|
+
export function createNetworkError(message) {
|
|
8
8
|
const error = new Error(message);
|
|
9
9
|
error.name = 'NetworkError';
|
|
10
10
|
return error;
|
package/dist/common.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/common.ts"],"sourcesContent":["import { type LDService } from '@servicetitan/launchdarkly-service';\nimport { Log } from '@servicetitan/log-service';\nimport { symbolToken } from '@servicetitan/react-ioc';\nimport { ExposedDependencies } from '@servicetitan/startup-utils';\nimport { EventBus } from './event-bus';\nimport { HistoryManager } from './history-manager';\n\nexport interface ExposedInstanceDependencies {\n launchDarkly?: { version: string; ldService?: LDService };\n}\n\nexport const BASENAME_TOKEN = symbolToken<string>('BASENAME_TOKEN');\nexport const EXPOSED_DEPENDENCIES_TOKEN = symbolToken<ExposedDependencies>(\n 'EXPOSED_DEPENDENCIES_TOKEN'\n);\nexport const EXPOSED_INSTANCE_DEPENDENCIES_TOKEN = symbolToken<ExposedInstanceDependencies>(\n 'EXPOSED_INSTANCE_DEPENDENCIES_TOKEN'\n);\nexport const IS_WEB_COMPONENT_TOKEN = symbolToken<boolean>('IS_WEB_COMPONENT_TOKEN');\nexport const RENDER_ROOT_TOKEN = symbolToken<ShadowRoot>('RENDER_ROOT_TOKEN');\n\nexport interface Entries {\n ldService?: LDService;\n logService?: Log;\n historyManager?: HistoryManager;\n exposedDependencies?: ExposedDependencies;\n exposedInstanceDependencies?: ExposedInstanceDependencies;\n eventBus?: EventBus;\n basename?: string;\n onReady?: () => void;\n onDispose?: () => void;\n}\n\nexport interface IWebComponent {\n provide(entries: Entries): void;\n}\n\nexport interface GetJsonError {\n status: number;\n body: string;\n json: object;\n}\n\ninterface GetJsonOptions extends RequestInit {\n retries?: number;\n retryDelay?: number;\n onRequestError?(error: GetJsonError): void;\n}\n\
|
|
1
|
+
{"version":3,"sources":["../src/common.ts"],"sourcesContent":["import { type LDService } from '@servicetitan/launchdarkly-service';\nimport { Log } from '@servicetitan/log-service';\nimport { symbolToken } from '@servicetitan/react-ioc';\nimport { ExposedDependencies } from '@servicetitan/startup-utils';\nimport { EventBus } from './event-bus';\nimport { HistoryManager } from './history-manager';\n\nexport interface ExposedInstanceDependencies {\n launchDarkly?: { version: string; ldService?: LDService };\n}\n\nexport const BASENAME_TOKEN = symbolToken<string>('BASENAME_TOKEN');\nexport const EXPOSED_DEPENDENCIES_TOKEN = symbolToken<ExposedDependencies>(\n 'EXPOSED_DEPENDENCIES_TOKEN'\n);\nexport const EXPOSED_INSTANCE_DEPENDENCIES_TOKEN = symbolToken<ExposedInstanceDependencies>(\n 'EXPOSED_INSTANCE_DEPENDENCIES_TOKEN'\n);\nexport const IS_WEB_COMPONENT_TOKEN = symbolToken<boolean>('IS_WEB_COMPONENT_TOKEN');\nexport const RENDER_ROOT_TOKEN = symbolToken<ShadowRoot>('RENDER_ROOT_TOKEN');\n\nexport interface Entries {\n ldService?: LDService;\n logService?: Log;\n historyManager?: HistoryManager;\n exposedDependencies?: ExposedDependencies;\n exposedInstanceDependencies?: ExposedInstanceDependencies;\n eventBus?: EventBus;\n basename?: string;\n onReady?: () => void;\n onDispose?: () => void;\n}\n\nexport interface IWebComponent {\n provide(entries: Entries): void;\n}\n\nexport interface GetJsonError {\n status: number;\n body: string;\n json: object;\n}\n\ninterface GetJsonOptions extends RequestInit {\n retries?: number;\n retryDelay?: number;\n onRequestError?(error: GetJsonError): void;\n}\n\nexport function createNetworkError(message: string) {\n const error = new Error(message);\n\n error.name = 'NetworkError';\n\n return error;\n}\n\nexport async function getJson<T = any>(\n url: string,\n { retries = 5, retryDelay = 1000, onRequestError, ...config }: GetJsonOptions = {}\n): Promise<{ data: T; headers: Headers; url: string }> {\n let response: Response;\n try {\n response = await fetch(url, config);\n } catch {\n if (retries > 0 && !config.signal?.aborted) {\n return new Promise((resolve, reject) => {\n const { signal } = config;\n\n const timeoutId = window.setTimeout(() => {\n getJson(url, {\n ...config,\n onRequestError,\n retries: retries - 1,\n retryDelay: retryDelay * 4,\n }).then(resolve, reject);\n }, retryDelay);\n\n const abortHandler = () => {\n window.clearTimeout(timeoutId);\n signal?.removeEventListener('abort', abortHandler);\n reject(signal?.reason);\n };\n\n signal?.addEventListener('abort', abortHandler);\n });\n }\n\n throw createNetworkError(`Failed to fetch: \"${url}\".`);\n }\n\n const responseJSON = await response.json().catch(() => ({}));\n\n if (!response.ok) {\n let message = `Requesting \"${url}\" failed with status code ${response.status}.`;\n\n try {\n message += ` Details: ${await response.text()}.`;\n } catch {} // eslint-disable-line no-empty\n\n onRequestError?.({\n status: response.status,\n json: responseJSON,\n body: await response.text().catch(() => ''),\n });\n throw createNetworkError(message);\n }\n\n return { data: responseJSON, headers: response.headers, url: response.url ?? url };\n}\n"],"names":["symbolToken","BASENAME_TOKEN","EXPOSED_DEPENDENCIES_TOKEN","EXPOSED_INSTANCE_DEPENDENCIES_TOKEN","IS_WEB_COMPONENT_TOKEN","RENDER_ROOT_TOKEN","createNetworkError","message","error","Error","name","getJson","url","retries","retryDelay","onRequestError","config","response","fetch","signal","aborted","Promise","resolve","reject","timeoutId","window","setTimeout","then","abortHandler","clearTimeout","removeEventListener","reason","addEventListener","responseJSON","json","catch","ok","status","text","body","data","headers"],"mappings":"AAEA,SAASA,WAAW,QAAQ,0BAA0B;AAStD,OAAO,MAAMC,iBAAiBD,YAAoB,kBAAkB;AACpE,OAAO,MAAME,6BAA6BF,YACtC,8BACF;AACF,OAAO,MAAMG,sCAAsCH,YAC/C,uCACF;AACF,OAAO,MAAMI,yBAAyBJ,YAAqB,0BAA0B;AACrF,OAAO,MAAMK,oBAAoBL,YAAwB,qBAAqB;AA8B9E,OAAO,SAASM,mBAAmBC,OAAe;IAC9C,MAAMC,QAAQ,IAAIC,MAAMF;IAExBC,MAAME,IAAI,GAAG;IAEb,OAAOF;AACX;AAEA,OAAO,eAAeG,QAClBC,GAAW,EACX,EAAEC,UAAU,CAAC,EAAEC,aAAa,IAAI,EAAEC,cAAc,EAAE,GAAGC,QAAwB,GAAG,CAAC,CAAC;QAiDrBC;IA/C7D,IAAIA;IACJ,IAAI;QACAA,WAAW,MAAMC,MAAMN,KAAKI;IAChC,EAAE,eAAM;YACgBA;QAApB,IAAIH,UAAU,KAAK,GAACG,iBAAAA,OAAOG,MAA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rF"}
|
package/dist/loader.js
CHANGED
|
@@ -131,7 +131,9 @@ function lazyWebComponent(props) {
|
|
|
131
131
|
packageUrl: src
|
|
132
132
|
});
|
|
133
133
|
await loadScripts(bundleInfo);
|
|
134
|
-
const
|
|
134
|
+
const hostLDService = exposedInstanceDependencies === null || exposedInstanceDependencies === void 0 ? void 0 : (_exposedInstanceDependencies_launchDarkly = exposedInstanceDependencies.launchDarkly) === null || _exposedInstanceDependencies_launchDarkly === void 0 ? void 0 : _exposedInstanceDependencies_launchDarkly.ldService;
|
|
135
|
+
const hostSupportsVersionedLDClient = typeof (hostLDService === null || hostLDService === void 0 ? void 0 : hostLDService.getVersionClient) === 'function';
|
|
136
|
+
const ldService = bundleInfo.mfeHasCompatibleLaunchDarklyVersion || bundleInfo.mfeSupportsVersionedLDClient && hostSupportsVersionedLDClient ? hostLDService : undefined;
|
|
135
137
|
return {
|
|
136
138
|
default: webComponent({
|
|
137
139
|
basename,
|
package/dist/loader.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/loader.tsx"],"sourcesContent":["import { ErrorBoundary } from '@servicetitan/error-boundary';\nimport { type LDService } from '@servicetitan/launchdarkly-service';\nimport { Log } from '@servicetitan/log-service';\nimport { useOptionalDependencies } from '@servicetitan/react-ioc';\nimport { ExposedDependencies } from '@servicetitan/startup-utils';\nimport {\n ReactElement,\n ReactNode,\n Ref,\n Suspense,\n forwardRef,\n lazy,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n} from 'react';\nimport {\n EXPOSED_DEPENDENCIES_TOKEN,\n EXPOSED_INSTANCE_DEPENDENCIES_TOKEN,\n ExposedInstanceDependencies,\n GetJsonError,\n} from './common';\nimport { MFEContextData } from './contexts/mfe-data-context';\nimport { Delayed } from './delayed';\nimport { EVENT_BUS_TOKEN, EventBus } from './event-bus';\nimport { EXPOSED_DEPENDENCIES, EXPOSED_INSTANCE_DEPENDENCIES } from './globals';\nimport {\n BundleInfo,\n getBundleInfo,\n getLDServiceToken,\n loadScripts,\n validateBundleInfo,\n webComponent,\n} from './utils';\n\nexport type LoaderRef = EventBus;\n\nexport type FallbackNode = NonNullable<ReactNode> | null;\n\nexport interface UnrestrictedLoaderProps<T = {}> {\n src: string;\n fallbackSrc?: string;\n /** Values in the object will be stringified and then parsed before being delivered to the MFE via props or context. */\n data?: MFEContextData<T>;\n basename?: string;\n loadingFallback?: FallbackNode;\n loadingFallbackDelayed?: boolean;\n errorFallback?: FallbackNode;\n className?: string;\n retries?: number;\n isHeadless?: boolean;\n cache?: boolean | number;\n onRequestError?(error: GetJsonError): boolean;\n}\n\nexport type LoaderProps<T> = Pick<\n UnrestrictedLoaderProps<T>,\n | 'src'\n | 'fallbackSrc'\n | 'data'\n | 'basename'\n | 'loadingFallback'\n | 'loadingFallbackDelayed'\n | 'errorFallback'\n | 'className'\n | 'retries'\n | 'cache'\n | 'onRequestError'\n>;\n\nexport type LoaderDataProps = Pick<UnrestrictedLoaderProps, 'data' | 'className'> & {\n LoadingFallback: () => JSX.Element;\n};\n\nconst UnrestrictedLoader = <T,>(props: UnrestrictedLoaderProps<T>, ref: Ref<LoaderRef>) => {\n const { cache = -1, basename, fallbackSrc, isHeadless, onRequestError, retries, src } = props;\n const { loadingFallback, loadingFallbackDelayed = true } = props;\n\n const bus = useEventBus();\n const [logService, exposedDependencies = EXPOSED_DEPENDENCIES, eventBus = bus] =\n useOptionalDependencies(Log, EXPOSED_DEPENDENCIES_TOKEN, EVENT_BUS_TOKEN);\n let [exposedInstanceDependencies = EXPOSED_INSTANCE_DEPENDENCIES] = useOptionalDependencies(\n EXPOSED_INSTANCE_DEPENDENCIES_TOKEN\n );\n const [ldService] = useOptionalDependencies(getLDServiceToken() ?? Symbol());\n\n const LoadingFallback = useMemo(() => {\n const message = `Loading${isLocalHost(src) ? ` ${src}` : ''}...`;\n return getFallback(loadingFallback, message, { delayed: loadingFallbackDelayed });\n }, [loadingFallback, loadingFallbackDelayed, src]);\n\n const ErrorFallback = useMemo(() => {\n const message = `Something went wrong${isLocalHost(src) ? ` loading ${src}` : ''}`;\n return getFallback(props.errorFallback, message);\n }, [props.errorFallback, src]);\n\n exposedInstanceDependencies = useMemo(\n () => ensureLDService(exposedInstanceDependencies, ldService),\n [exposedInstanceDependencies, ldService]\n );\n\n const Loader = useMemo(() => {\n const cancelation = new AbortController();\n return lazyLoader({\n basename,\n cache,\n cancelation,\n exposedDependencies,\n exposedInstanceDependencies,\n eventBus,\n fallbackSrc,\n isHeadless,\n logService,\n onRequestError,\n retries,\n src,\n });\n }, [\n basename,\n cache,\n exposedDependencies,\n exposedInstanceDependencies,\n eventBus,\n fallbackSrc,\n isHeadless,\n logService,\n onRequestError,\n retries,\n src,\n ]);\n\n useImperativeHandle(ref, () => eventBus, [eventBus]);\n\n return (\n <ErrorBoundary moduleName={src} fallback={ErrorFallback}>\n <Suspense fallback={<LoadingFallback />}>\n <Loader\n data={props.data ?? {}}\n className={props.className}\n LoadingFallback={LoadingFallback}\n />\n </Suspense>\n </ErrorBoundary>\n );\n};\n\nexport const Loader = forwardRef(UnrestrictedLoader) as <T = {}>(\n props: LoaderProps<NoInfer<T>> & { ref?: Ref<LoaderRef> }\n) => ReturnType<typeof UnrestrictedLoader>;\n\ntype LazyLoaderProps = UnrestrictedLoaderProps<any> & {\n cancelation: AbortController;\n exposedDependencies?: ExposedDependencies;\n exposedInstanceDependencies?: ExposedInstanceDependencies;\n eventBus: EventBus;\n logService?: Log;\n cache: Required<UnrestrictedLoaderProps<any>>['cache'];\n};\n\nfunction lazyLoader(props: LazyLoaderProps) {\n const { cancelation } = props;\n\n const LazyWebComponent = lazyWebComponent(props);\n\n return (props: LoaderDataProps) => {\n useEffect(() => {\n return () => {\n cancelation.abort();\n };\n }, []);\n\n return (\n <LazyWebComponent\n data={props.data}\n className={props.className}\n LoadingFallback={props.LoadingFallback}\n />\n );\n };\n}\n\nfunction lazyWebComponent(props: LazyLoaderProps) {\n const {\n basename,\n cache,\n cancelation,\n exposedDependencies,\n exposedInstanceDependencies,\n eventBus,\n fallbackSrc,\n isHeadless,\n logService,\n onRequestError,\n retries,\n src,\n } = props;\n\n return lazy<(_: LoaderDataProps) => JSX.Element | null>(async () => {\n let bundleInfo: BundleInfo;\n try {\n bundleInfo = await getBundleInfo({\n cache,\n mainPackageUrl: src,\n fallbackPackageUrl: fallbackSrc,\n isHeadless,\n exposedDependencies,\n exposedInstanceDependencies,\n signal: cancelation.signal,\n retries,\n onRequestError,\n });\n } catch (e) {\n if (cancelation.signal.aborted) {\n return {\n default: () => null,\n };\n }\n\n throw e;\n }\n\n validateBundleInfo(bundleInfo, {\n exposedDependencies,\n exposedInstanceDependencies,\n logService,\n packageUrl: src,\n });\n\n await loadScripts(bundleInfo);\n\n const ldService = bundleInfo.mfeHasCompatibleLaunchDarklyVersion\n ? exposedInstanceDependencies?.launchDarkly?.ldService\n : undefined;\n\n return {\n default: webComponent({\n basename,\n bundleInfo,\n eventBus,\n exposedDependencies,\n exposedInstanceDependencies,\n ldService,\n logService,\n }),\n };\n });\n}\n\nfunction getFallback(\n node: FallbackNode | undefined,\n message: string,\n { delayed = false }: { delayed?: boolean } = {}\n) {\n const fallbackNode = node !== undefined ? (node as ReactElement) : <h2>{message}</h2>;\n return delayed ? () => <Delayed>{fallbackNode}</Delayed> : () => fallbackNode;\n}\n\nfunction isLocalHost(source: string) {\n return ['localhost', '127.0.0.1'].some(host => source.indexOf(host) >= 0);\n}\n\nfunction ensureLDService(\n exposedInstanceDependencies?: ExposedInstanceDependencies,\n ldService?: LDService\n) {\n const launchDarkly = exposedInstanceDependencies?.launchDarkly;\n if (launchDarkly?.version && !launchDarkly.ldService && ldService) {\n return { ...exposedInstanceDependencies, launchDarkly: { ...launchDarkly, ldService } };\n }\n return exposedInstanceDependencies;\n}\n\nfunction useEventBus() {\n return useRef(new EventBus()).current;\n}\n"],"names":["ErrorBoundary","Log","useOptionalDependencies","Suspense","forwardRef","lazy","useEffect","useImperativeHandle","useMemo","useRef","EXPOSED_DEPENDENCIES_TOKEN","EXPOSED_INSTANCE_DEPENDENCIES_TOKEN","Delayed","EVENT_BUS_TOKEN","EventBus","EXPOSED_DEPENDENCIES","EXPOSED_INSTANCE_DEPENDENCIES","getBundleInfo","getLDServiceToken","loadScripts","validateBundleInfo","webComponent","UnrestrictedLoader","props","ref","cache","basename","fallbackSrc","isHeadless","onRequestError","retries","src","loadingFallback","loadingFallbackDelayed","bus","useEventBus","logService","exposedDependencies","eventBus","exposedInstanceDependencies","ldService","Symbol","LoadingFallback","message","isLocalHost","getFallback","delayed","ErrorFallback","errorFallback","ensureLDService","Loader","cancelation","AbortController","lazyLoader","moduleName","fallback","data","className","LazyWebComponent","lazyWebComponent","abort","bundleInfo","mainPackageUrl","fallbackPackageUrl","signal","e","aborted","default","packageUrl","mfeHasCompatibleLaunchDarklyVersion","launchDarkly","undefined","node","fallbackNode","h2","source","some","host","indexOf","version","current"],"mappings":";AAAA,SAASA,aAAa,QAAQ,+BAA+B;AAE7D,SAASC,GAAG,QAAQ,4BAA4B;AAChD,SAASC,uBAAuB,QAAQ,0BAA0B;AAElE,SAIIC,QAAQ,EACRC,UAAU,EACVC,IAAI,EACJC,SAAS,EACTC,mBAAmB,EACnBC,OAAO,EACPC,MAAM,QACH,QAAQ;AACf,SACIC,0BAA0B,EAC1BC,mCAAmC,QAGhC,WAAW;AAElB,SAASC,OAAO,QAAQ,YAAY;AACpC,SAASC,eAAe,EAAEC,QAAQ,QAAQ,cAAc;AACxD,SAASC,oBAAoB,EAAEC,6BAA6B,QAAQ,YAAY;AAChF,SAEIC,aAAa,EACbC,iBAAiB,EACjBC,WAAW,EACXC,kBAAkB,EAClBC,YAAY,QACT,UAAU;AAyCjB,MAAMC,qBAAqB,CAAKC,OAAmCC;QAUnBN,oBAqDtBK;IA9DtB,MAAM,EAAEE,QAAQ,CAAC,CAAC,EAAEC,QAAQ,EAAEC,WAAW,EAAEC,UAAU,EAAEC,cAAc,EAAEC,OAAO,EAAEC,GAAG,E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AAYqB,WAAWQ,mCAAmC,GAC1D9B,wCAAAA,mDAAAA,4CAAAA,4BAA6B+B,YAAY,cAAzC/B,gEAAAA,0CAA2CC,SAAS,GACpD+B;QAEN,OAAO;YACHJ,SAAS9C,aAAa;gBAClBK;gBACAmC;gBACAvB;gBACAD;gBACAE;gBACAC;gBACAJ;YACJ;QACJ;IACJ;AACJ;AAEA,SAASS,YACL2B,IAA8B,EAC9B7B,OAAe,EACf,EAAEG,UAAU,KAAK,EAAyB,GAAG,CAAC,CAAC;IAE/C,MAAM2B,eAAeD,SAASD,YAAaC,qBAAwB,KAACE;kBAAI/B;;IACxE,OAAOG,UAAU,kBAAM,KAAClC;sBAAS6D;aAA0B,IAAMA;AACrE;AAEA,SAAS7B,YAAY+B,MAAc;IAC/B,OAAO;QAAC;QAAa;KAAY,CAACC,IAAI,CAACC,CAAAA,OAAQF,OAAOG,OAAO,CAACD,SAAS;AAC3E;AAEA,SAAS5B,gBACLV,2BAAyD,EACzDC,SAAqB;IAErB,MAAM8B,eAAe/B,wCAAAA,kDAAAA,4BAA6B+B,YAAY;IAC9D,IAAIA,CAAAA,yBAAAA,mCAAAA,aAAcS,OAAO,KAAI,CAACT,aAAa9B,SAAS,IAAIA,WAAW;QAC/D,OAAO;YAAE,GAAGD,2BAA2B;YAAE+B,cAAc;gBAAE,GAAGA,YAAY;gBAAE9B;YAAU;QAAE;IAC1F;IACA,OAAOD;AACX;AAEA,SAASJ;IACL,OAAO1B,OAAO,IAAIK,YAAYkE,OAAO;AACzC"}
|
|
1
|
+
{"version":3,"sources":["../src/loader.tsx"],"sourcesContent":["import { ErrorBoundary } from '@servicetitan/error-boundary';\nimport { type LDService } from '@servicetitan/launchdarkly-service';\nimport { Log } from '@servicetitan/log-service';\nimport { useOptionalDependencies } from '@servicetitan/react-ioc';\nimport { ExposedDependencies } from '@servicetitan/startup-utils';\nimport {\n ReactElement,\n ReactNode,\n Ref,\n Suspense,\n forwardRef,\n lazy,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n} from 'react';\nimport {\n EXPOSED_DEPENDENCIES_TOKEN,\n EXPOSED_INSTANCE_DEPENDENCIES_TOKEN,\n ExposedInstanceDependencies,\n GetJsonError,\n} from './common';\nimport { MFEContextData } from './contexts/mfe-data-context';\nimport { Delayed } from './delayed';\nimport { EVENT_BUS_TOKEN, EventBus } from './event-bus';\nimport { EXPOSED_DEPENDENCIES, EXPOSED_INSTANCE_DEPENDENCIES } from './globals';\nimport {\n BundleInfo,\n getBundleInfo,\n getLDServiceToken,\n loadScripts,\n validateBundleInfo,\n webComponent,\n} from './utils';\n\nexport type LoaderRef = EventBus;\n\nexport type FallbackNode = NonNullable<ReactNode> | null;\n\nexport interface UnrestrictedLoaderProps<T = {}> {\n src: string;\n fallbackSrc?: string;\n /** Values in the object will be stringified and then parsed before being delivered to the MFE via props or context. */\n data?: MFEContextData<T>;\n basename?: string;\n loadingFallback?: FallbackNode;\n loadingFallbackDelayed?: boolean;\n errorFallback?: FallbackNode;\n className?: string;\n retries?: number;\n isHeadless?: boolean;\n cache?: boolean | number;\n onRequestError?(error: GetJsonError): boolean;\n}\n\nexport type LoaderProps<T> = Pick<\n UnrestrictedLoaderProps<T>,\n | 'src'\n | 'fallbackSrc'\n | 'data'\n | 'basename'\n | 'loadingFallback'\n | 'loadingFallbackDelayed'\n | 'errorFallback'\n | 'className'\n | 'retries'\n | 'cache'\n | 'onRequestError'\n>;\n\nexport type LoaderDataProps = Pick<UnrestrictedLoaderProps, 'data' | 'className'> & {\n LoadingFallback: () => JSX.Element;\n};\n\nconst UnrestrictedLoader = <T,>(props: UnrestrictedLoaderProps<T>, ref: Ref<LoaderRef>) => {\n const { cache = -1, basename, fallbackSrc, isHeadless, onRequestError, retries, src } = props;\n const { loadingFallback, loadingFallbackDelayed = true } = props;\n\n const bus = useEventBus();\n const [logService, exposedDependencies = EXPOSED_DEPENDENCIES, eventBus = bus] =\n useOptionalDependencies(Log, EXPOSED_DEPENDENCIES_TOKEN, EVENT_BUS_TOKEN);\n let [exposedInstanceDependencies = EXPOSED_INSTANCE_DEPENDENCIES] = useOptionalDependencies(\n EXPOSED_INSTANCE_DEPENDENCIES_TOKEN\n );\n const [ldService] = useOptionalDependencies(getLDServiceToken() ?? Symbol());\n\n const LoadingFallback = useMemo(() => {\n const message = `Loading${isLocalHost(src) ? ` ${src}` : ''}...`;\n return getFallback(loadingFallback, message, { delayed: loadingFallbackDelayed });\n }, [loadingFallback, loadingFallbackDelayed, src]);\n\n const ErrorFallback = useMemo(() => {\n const message = `Something went wrong${isLocalHost(src) ? ` loading ${src}` : ''}`;\n return getFallback(props.errorFallback, message);\n }, [props.errorFallback, src]);\n\n exposedInstanceDependencies = useMemo(\n () => ensureLDService(exposedInstanceDependencies, ldService),\n [exposedInstanceDependencies, ldService]\n );\n\n const Loader = useMemo(() => {\n const cancelation = new AbortController();\n return lazyLoader({\n basename,\n cache,\n cancelation,\n exposedDependencies,\n exposedInstanceDependencies,\n eventBus,\n fallbackSrc,\n isHeadless,\n logService,\n onRequestError,\n retries,\n src,\n });\n }, [\n basename,\n cache,\n exposedDependencies,\n exposedInstanceDependencies,\n eventBus,\n fallbackSrc,\n isHeadless,\n logService,\n onRequestError,\n retries,\n src,\n ]);\n\n useImperativeHandle(ref, () => eventBus, [eventBus]);\n\n return (\n <ErrorBoundary moduleName={src} fallback={ErrorFallback}>\n <Suspense fallback={<LoadingFallback />}>\n <Loader\n data={props.data ?? {}}\n className={props.className}\n LoadingFallback={LoadingFallback}\n />\n </Suspense>\n </ErrorBoundary>\n );\n};\n\nexport const Loader = forwardRef(UnrestrictedLoader) as <T = {}>(\n props: LoaderProps<NoInfer<T>> & { ref?: Ref<LoaderRef> }\n) => ReturnType<typeof UnrestrictedLoader>;\n\ntype LazyLoaderProps = UnrestrictedLoaderProps<any> & {\n cancelation: AbortController;\n exposedDependencies?: ExposedDependencies;\n exposedInstanceDependencies?: ExposedInstanceDependencies;\n eventBus: EventBus;\n logService?: Log;\n cache: Required<UnrestrictedLoaderProps<any>>['cache'];\n};\n\nfunction lazyLoader(props: LazyLoaderProps) {\n const { cancelation } = props;\n\n const LazyWebComponent = lazyWebComponent(props);\n\n return (props: LoaderDataProps) => {\n useEffect(() => {\n return () => {\n cancelation.abort();\n };\n }, []);\n\n return (\n <LazyWebComponent\n data={props.data}\n className={props.className}\n LoadingFallback={props.LoadingFallback}\n />\n );\n };\n}\n\nfunction lazyWebComponent(props: LazyLoaderProps) {\n const {\n basename,\n cache,\n cancelation,\n exposedDependencies,\n exposedInstanceDependencies,\n eventBus,\n fallbackSrc,\n isHeadless,\n logService,\n onRequestError,\n retries,\n src,\n } = props;\n\n return lazy<(_: LoaderDataProps) => JSX.Element | null>(async () => {\n let bundleInfo: BundleInfo;\n try {\n bundleInfo = await getBundleInfo({\n cache,\n mainPackageUrl: src,\n fallbackPackageUrl: fallbackSrc,\n isHeadless,\n exposedDependencies,\n exposedInstanceDependencies,\n signal: cancelation.signal,\n retries,\n onRequestError,\n });\n } catch (e) {\n if (cancelation.signal.aborted) {\n return {\n default: () => null,\n };\n }\n\n throw e;\n }\n\n validateBundleInfo(bundleInfo, {\n exposedDependencies,\n exposedInstanceDependencies,\n logService,\n packageUrl: src,\n });\n\n await loadScripts(bundleInfo);\n\n const hostLDService = exposedInstanceDependencies?.launchDarkly?.ldService;\n const hostSupportsVersionedLDClient = typeof hostLDService?.getVersionClient === 'function';\n const ldService =\n bundleInfo.mfeHasCompatibleLaunchDarklyVersion ||\n (bundleInfo.mfeSupportsVersionedLDClient && hostSupportsVersionedLDClient)\n ? hostLDService\n : undefined;\n\n return {\n default: webComponent({\n basename,\n bundleInfo,\n eventBus,\n exposedDependencies,\n exposedInstanceDependencies,\n ldService,\n logService,\n }),\n };\n });\n}\n\nfunction getFallback(\n node: FallbackNode | undefined,\n message: string,\n { delayed = false }: { delayed?: boolean } = {}\n) {\n const fallbackNode = node !== undefined ? (node as ReactElement) : <h2>{message}</h2>;\n return delayed ? () => <Delayed>{fallbackNode}</Delayed> : () => fallbackNode;\n}\n\nfunction isLocalHost(source: string) {\n return ['localhost', '127.0.0.1'].some(host => source.indexOf(host) >= 0);\n}\n\nfunction ensureLDService(\n exposedInstanceDependencies?: ExposedInstanceDependencies,\n ldService?: LDService\n) {\n const launchDarkly = exposedInstanceDependencies?.launchDarkly;\n if (launchDarkly?.version && !launchDarkly.ldService && ldService) {\n return { ...exposedInstanceDependencies, launchDarkly: { ...launchDarkly, ldService } };\n }\n return exposedInstanceDependencies;\n}\n\nfunction useEventBus() {\n return useRef(new EventBus()).current;\n}\n"],"names":["ErrorBoundary","Log","useOptionalDependencies","Suspense","forwardRef","lazy","useEffect","useImperativeHandle","useMemo","useRef","EXPOSED_DEPENDENCIES_TOKEN","EXPOSED_INSTANCE_DEPENDENCIES_TOKEN","Delayed","EVENT_BUS_TOKEN","EventBus","EXPOSED_DEPENDENCIES","EXPOSED_INSTANCE_DEPENDENCIES","getBundleInfo","getLDServiceToken","loadScripts","validateBundleInfo","webComponent","UnrestrictedLoader","props","ref","cache","basename","fallbackSrc","isHeadless","onRequestError","retries","src","loadingFallback","loadingFallbackDelayed","bus","useEventBus","logService","exposedDependencies","eventBus","exposedInstanceDependencies","ldService","Symbol","LoadingFallback","message","isLocalHost","getFallback","delayed","ErrorFallback","errorFallback","ensureLDService","Loader","cancelation","AbortController","lazyLoader","moduleName","fallback","data","className","LazyWebComponent","lazyWebComponent","abort","bundleInfo","mainPackageUrl","fallbackPackageUrl","signal","e","aborted","default","packageUrl","hostLDService","launchDarkly","hostSupportsVersionedLDClient","getVersionClient","mfeHasCompatibleLaunchDarklyVersion","mfeSupportsVersionedLDClient","undefined","node","fallbackNode","h2","source","some","host","indexOf","version","current"],"mappings":";AAAA,SAASA,aAAa,QAAQ,+BAA+B;AAE7D,SAASC,GAAG,QAAQ,4BAA4B;AAChD,SAASC,uBAAuB,QAAQ,0BAA0B;AAElE,SAIIC,QAAQ,EACRC,UAAU,EACVC,IAAI,EACJC,SAAS,EACTC,mBAAm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eAAe/B,wCAAAA,kDAAAA,4BAA6B+B,YAAY;IAC9D,IAAIA,CAAAA,yBAAAA,mCAAAA,aAAca,OAAO,KAAI,CAACb,aAAa9B,SAAS,IAAIA,WAAW;QAC/D,OAAO;YAAE,GAAGD,2BAA2B;YAAE+B,cAAc;gBAAE,GAAGA,YAAY;gBAAE9B;YAAU;QAAE;IAC1F;IACA,OAAOD;AACX;AAEA,SAASJ;IACL,OAAO1B,OAAO,IAAIK,YAAYsE,OAAO;AACzC"}
|
|
@@ -20,6 +20,7 @@ export declare function getBundleInfo({ cache, mainPackageUrl, fallbackPackageUr
|
|
|
20
20
|
mfeSupportsRerendering: boolean;
|
|
21
21
|
mfeHasUniqueChunkNamespace: boolean;
|
|
22
22
|
mfeHasCompatibleLaunchDarklyVersion: boolean | undefined;
|
|
23
|
+
mfeSupportsVersionedLDClient: boolean;
|
|
23
24
|
mismatch: Record<string, {
|
|
24
25
|
host: string;
|
|
25
26
|
package: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-bundle-info.d.ts","sourceRoot":"","sources":["../../src/utils/get-bundle-info.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAwB,MAAM,6BAA6B,CAAC;AAGxF,OAAO,EAAE,2BAA2B,EAAW,YAAY,EAAE,MAAM,WAAW,CAAC;AAI/E,OAAO,EAAE,WAAW,EAAkB,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"get-bundle-info.d.ts","sourceRoot":"","sources":["../../src/utils/get-bundle-info.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAwB,MAAM,6BAA6B,CAAC;AAGxF,OAAO,EAAE,2BAA2B,EAAW,YAAY,EAAE,MAAM,WAAW,CAAC;AAI/E,OAAO,EAAE,WAAW,EAAkB,MAAM,oBAAoB,CAAC;AAMjE,MAAM,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,aAAa,CAAC,CAAC,CAAC;AAEnE,UAAU,kBAAkB;IACxB,KAAK,EAAE,OAAO,GAAG,MAAM,CAAC;IACxB,mBAAmB,CAAC,EAAE,mBAAmB,CAAC;IAC1C,2BAA2B,CAAC,EAAE,2BAA2B,CAAC;IAC1D,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,CAAC;IAC/C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,WAAW,CAAC;CACxB;AAED,wBAAsB,aAAa,CAAC,EAChC,KAAK,EACL,cAAc,EACd,kBAAkB,EAClB,mBAAwB,EACxB,2BAAgC,EAChC,UAAU,EACV,MAAM,EACN,OAAO,EACP,cAAc,GACjB,EAAE,kBAAkB;;;;;;;;;;;;;;;;;GA+FpB"}
|
|
@@ -8,6 +8,7 @@ import { getEntrypoints } from './get-entry-points';
|
|
|
8
8
|
import { getMFEHasCompatibleLaunchDarklyVersion } from './get-mfe-has-compatible-launchdarkly-version';
|
|
9
9
|
import { getMFEHasUniqueChunkNamespace } from './get-mfe-has-unique-chunk-namespace';
|
|
10
10
|
import { getMFESupportsRerendering } from './get-mfe-supports-rerendering';
|
|
11
|
+
import { getMFESupportsVersionedLDClient } from './get-mfe-supports-versioned-ld-client';
|
|
11
12
|
export async function getBundleInfo({ cache, mainPackageUrl, fallbackPackageUrl, exposedDependencies = {}, exposedInstanceDependencies = {}, isHeadless, signal, retries, onRequestError }) {
|
|
12
13
|
var _metadata_entrypoints;
|
|
13
14
|
const { cacheHit, data: metadata, url: packageUrl } = await getCachedMetadata({
|
|
@@ -77,6 +78,7 @@ export async function getBundleInfo({ cache, mainPackageUrl, fallbackPackageUrl,
|
|
|
77
78
|
mfeSupportsRerendering: getMFESupportsRerendering(bundledWith, dependencies),
|
|
78
79
|
mfeHasUniqueChunkNamespace: getMFEHasUniqueChunkNamespace(bundledWith),
|
|
79
80
|
mfeHasCompatibleLaunchDarklyVersion: getMFEHasCompatibleLaunchDarklyVersion(bundledWith, exposedInstanceDependencies),
|
|
81
|
+
mfeSupportsVersionedLDClient: getMFESupportsVersionedLDClient(bundledWith),
|
|
80
82
|
mismatch,
|
|
81
83
|
resolvedBundleType,
|
|
82
84
|
urls,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/get-bundle-info.ts"],"sourcesContent":["import { ExposedDependencies, getVersionMismatches } from '@servicetitan/startup-utils';\nimport get from 'lodash.get';\nimport semver from 'semver';\nimport { ExposedInstanceDependencies, getJson, GetJsonError } from '../common';\nimport type { Metadata } from '../types';\nimport { getCacheSetting } from './get-cache-setting';\nimport { getCachedMetadata } from './get-cached-metadata';\nimport { EntryPoints, getEntrypoints } from './get-entry-points';\nimport { getMFEHasCompatibleLaunchDarklyVersion } from './get-mfe-has-compatible-launchdarkly-version';\nimport { getMFEHasUniqueChunkNamespace } from './get-mfe-has-unique-chunk-namespace';\nimport { getMFESupportsRerendering } from './get-mfe-supports-rerendering';\n\nexport type BundleInfo = Awaited<ReturnType<typeof getBundleInfo>>;\n\ninterface GetBundleInfoProps {\n cache: boolean | number;\n exposedDependencies?: ExposedDependencies;\n exposedInstanceDependencies?: ExposedInstanceDependencies;\n fallbackPackageUrl?: string;\n isHeadless?: boolean;\n mainPackageUrl: string;\n onRequestError?: (error: GetJsonError) => void;\n retries?: number;\n signal?: AbortSignal;\n}\n\nexport async function getBundleInfo({\n cache,\n mainPackageUrl,\n fallbackPackageUrl,\n exposedDependencies = {},\n exposedInstanceDependencies = {},\n isHeadless,\n signal,\n retries,\n onRequestError,\n}: GetBundleInfoProps) {\n const {\n cacheHit,\n data: metadata,\n url: packageUrl,\n } = await getCachedMetadata({\n cache,\n fallbackPackageUrl,\n mainPackageUrl,\n onRequestError,\n retries,\n signal,\n });\n\n const { bundledWith, name, sharedDependencies } = metadata;\n const exactPackageUrl = packageUrl.replace('/dist/metadata.json', '');\n const requestCache = getCacheSetting(exactPackageUrl);\n\n let dependencies: NonNullable<Metadata['dependencies']>;\n if (metadata.dependencies) {\n dependencies = metadata.dependencies;\n } else {\n const { data: packageJson } = await getJson(`${exactPackageUrl}/package.json`, {\n cache: requestCache,\n retries,\n signal,\n });\n\n dependencies = packageJson.dependencies;\n }\n\n let mismatch: ReturnType<typeof getVersionMismatches>;\n let resolvedBundleType: 'headless' | 'light' | 'full';\n\n if (isHeadless) {\n resolvedBundleType = 'headless';\n } else {\n mismatch = getVersionMismatches(exposedDependencies, dependencies, sharedDependencies);\n const startupVersion = bundledWith?.['@servicetitan/startup'];\n const supportLightBundles = !!startupVersion && semver.gte(startupVersion, '17.0.0');\n const embed = !mismatch && supportLightBundles;\n resolvedBundleType = embed ? 'light' : 'full';\n }\n\n const bundleBaseUrl = `${exactPackageUrl}/dist/bundle/${resolvedBundleType}`;\n\n let entrypoints: EntryPoints;\n if (metadata.entrypoints?.[resolvedBundleType]) {\n entrypoints = metadata.entrypoints[resolvedBundleType];\n } else {\n entrypoints = await getEntrypoints(`${bundleBaseUrl}/entrypoints.json`, requestCache);\n }\n\n const disposer = () => {\n if (resolvedBundleType === 'light') {\n const path = Object.values<string>(sharedDependencies).shift();\n if (path) {\n get(window, path).getStorage().clear(name);\n }\n }\n };\n\n let baseUrl = bundleBaseUrl;\n // Per-MFE dev-server port only happens during local development\n if (process.env.NODE_ENV !== 'production' && entrypoints.port) {\n const url = new URL(baseUrl);\n url.port = String(entrypoints.port);\n baseUrl = url.toString();\n }\n\n const urls: EntryPoints = {\n css: entrypoints.css.map(path => `${baseUrl}/${path}`),\n js: entrypoints.js.map(path => `${baseUrl}/${path}`),\n };\n\n const elementName = resolvedBundleType === 'headless' ? `headless-${name}` : name;\n\n return {\n bundledWith,\n cacheHit,\n disposer,\n mfeSupportsRerendering: getMFESupportsRerendering(bundledWith, dependencies),\n mfeHasUniqueChunkNamespace: getMFEHasUniqueChunkNamespace(bundledWith),\n mfeHasCompatibleLaunchDarklyVersion: getMFEHasCompatibleLaunchDarklyVersion(\n bundledWith,\n exposedInstanceDependencies\n ),\n mismatch,\n resolvedBundleType,\n urls,\n WebComponent: elementName,\n version: metadata.version,\n module: entrypoints.module,\n };\n}\n"],"names":["getVersionMismatches","get","semver","getJson","getCacheSetting","getCachedMetadata","getEntrypoints","getMFEHasCompatibleLaunchDarklyVersion","getMFEHasUniqueChunkNamespace","getMFESupportsRerendering","getBundleInfo","cache","mainPackageUrl","fallbackPackageUrl","exposedDependencies","exposedInstanceDependencies","isHeadless","signal","retries","onRequestError","metadata","cacheHit","data","url","packageUrl","bundledWith","name","sharedDependencies","exactPackageUrl","replace","requestCache","dependencies","packageJson","mismatch","resolvedBundleType","startupVersion","supportLightBundles","gte","embed","bundleBaseUrl","entrypoints","disposer","path","Object","values","shift","window","getStorage","clear","baseUrl","process","env","NODE_ENV","port","URL","String","toString","urls","css","map","js","elementName","mfeSupportsRerendering","mfeHasUniqueChunkNamespace","mfeHasCompatibleLaunchDarklyVersion","WebComponent","version","module"],"mappings":"AAAA,SAA8BA,oBAAoB,QAAQ,8BAA8B;AACxF,OAAOC,SAAS,aAAa;AAC7B,OAAOC,YAAY,SAAS;AAC5B,SAAsCC,OAAO,QAAsB,YAAY;AAE/E,SAASC,eAAe,QAAQ,sBAAsB;AACtD,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D,SAAsBC,cAAc,QAAQ,qBAAqB;AACjE,SAASC,sCAAsC,QAAQ,gDAAgD;AACvG,SAASC,6BAA6B,QAAQ,uCAAuC;AACrF,SAASC,yBAAyB,QAAQ,iCAAiC;
|
|
1
|
+
{"version":3,"sources":["../../src/utils/get-bundle-info.ts"],"sourcesContent":["import { ExposedDependencies, getVersionMismatches } from '@servicetitan/startup-utils';\nimport get from 'lodash.get';\nimport semver from 'semver';\nimport { ExposedInstanceDependencies, getJson, GetJsonError } from '../common';\nimport type { Metadata } from '../types';\nimport { getCacheSetting } from './get-cache-setting';\nimport { getCachedMetadata } from './get-cached-metadata';\nimport { EntryPoints, getEntrypoints } from './get-entry-points';\nimport { getMFEHasCompatibleLaunchDarklyVersion } from './get-mfe-has-compatible-launchdarkly-version';\nimport { getMFEHasUniqueChunkNamespace } from './get-mfe-has-unique-chunk-namespace';\nimport { getMFESupportsRerendering } from './get-mfe-supports-rerendering';\nimport { getMFESupportsVersionedLDClient } from './get-mfe-supports-versioned-ld-client';\n\nexport type BundleInfo = Awaited<ReturnType<typeof getBundleInfo>>;\n\ninterface GetBundleInfoProps {\n cache: boolean | number;\n exposedDependencies?: ExposedDependencies;\n exposedInstanceDependencies?: ExposedInstanceDependencies;\n fallbackPackageUrl?: string;\n isHeadless?: boolean;\n mainPackageUrl: string;\n onRequestError?: (error: GetJsonError) => void;\n retries?: number;\n signal?: AbortSignal;\n}\n\nexport async function getBundleInfo({\n cache,\n mainPackageUrl,\n fallbackPackageUrl,\n exposedDependencies = {},\n exposedInstanceDependencies = {},\n isHeadless,\n signal,\n retries,\n onRequestError,\n}: GetBundleInfoProps) {\n const {\n cacheHit,\n data: metadata,\n url: packageUrl,\n } = await getCachedMetadata({\n cache,\n fallbackPackageUrl,\n mainPackageUrl,\n onRequestError,\n retries,\n signal,\n });\n\n const { bundledWith, name, sharedDependencies } = metadata;\n const exactPackageUrl = packageUrl.replace('/dist/metadata.json', '');\n const requestCache = getCacheSetting(exactPackageUrl);\n\n let dependencies: NonNullable<Metadata['dependencies']>;\n if (metadata.dependencies) {\n dependencies = metadata.dependencies;\n } else {\n const { data: packageJson } = await getJson(`${exactPackageUrl}/package.json`, {\n cache: requestCache,\n retries,\n signal,\n });\n\n dependencies = packageJson.dependencies;\n }\n\n let mismatch: ReturnType<typeof getVersionMismatches>;\n let resolvedBundleType: 'headless' | 'light' | 'full';\n\n if (isHeadless) {\n resolvedBundleType = 'headless';\n } else {\n mismatch = getVersionMismatches(exposedDependencies, dependencies, sharedDependencies);\n const startupVersion = bundledWith?.['@servicetitan/startup'];\n const supportLightBundles = !!startupVersion && semver.gte(startupVersion, '17.0.0');\n const embed = !mismatch && supportLightBundles;\n resolvedBundleType = embed ? 'light' : 'full';\n }\n\n const bundleBaseUrl = `${exactPackageUrl}/dist/bundle/${resolvedBundleType}`;\n\n let entrypoints: EntryPoints;\n if (metadata.entrypoints?.[resolvedBundleType]) {\n entrypoints = metadata.entrypoints[resolvedBundleType];\n } else {\n entrypoints = await getEntrypoints(`${bundleBaseUrl}/entrypoints.json`, requestCache);\n }\n\n const disposer = () => {\n if (resolvedBundleType === 'light') {\n const path = Object.values<string>(sharedDependencies).shift();\n if (path) {\n get(window, path).getStorage().clear(name);\n }\n }\n };\n\n let baseUrl = bundleBaseUrl;\n // Per-MFE dev-server port only happens during local development\n if (process.env.NODE_ENV !== 'production' && entrypoints.port) {\n const url = new URL(baseUrl);\n url.port = String(entrypoints.port);\n baseUrl = url.toString();\n }\n\n const urls: EntryPoints = {\n css: entrypoints.css.map(path => `${baseUrl}/${path}`),\n js: entrypoints.js.map(path => `${baseUrl}/${path}`),\n };\n\n const elementName = resolvedBundleType === 'headless' ? `headless-${name}` : name;\n\n return {\n bundledWith,\n cacheHit,\n disposer,\n mfeSupportsRerendering: getMFESupportsRerendering(bundledWith, dependencies),\n mfeHasUniqueChunkNamespace: getMFEHasUniqueChunkNamespace(bundledWith),\n mfeHasCompatibleLaunchDarklyVersion: getMFEHasCompatibleLaunchDarklyVersion(\n bundledWith,\n exposedInstanceDependencies\n ),\n mfeSupportsVersionedLDClient: getMFESupportsVersionedLDClient(bundledWith),\n mismatch,\n resolvedBundleType,\n urls,\n WebComponent: elementName,\n version: metadata.version,\n module: entrypoints.module,\n };\n}\n"],"names":["getVersionMismatches","get","semver","getJson","getCacheSetting","getCachedMetadata","getEntrypoints","getMFEHasCompatibleLaunchDarklyVersion","getMFEHasUniqueChunkNamespace","getMFESupportsRerendering","getMFESupportsVersionedLDClient","getBundleInfo","cache","mainPackageUrl","fallbackPackageUrl","exposedDependencies","exposedInstanceDependencies","isHeadless","signal","retries","onRequestError","metadata","cacheHit","data","url","packageUrl","bundledWith","name","sharedDependencies","exactPackageUrl","replace","requestCache","dependencies","packageJson","mismatch","resolvedBundleType","startupVersion","supportLightBundles","gte","embed","bundleBaseUrl","entrypoints","disposer","path","Object","values","shift","window","getStorage","clear","baseUrl","process","env","NODE_ENV","port","URL","String","toString","urls","css","map","js","elementName","mfeSupportsRerendering","mfeHasUniqueChunkNamespace","mfeHasCompatibleLaunchDarklyVersion","mfeSupportsVersionedLDClient","WebComponent","version","module"],"mappings":"AAAA,SAA8BA,oBAAoB,QAAQ,8BAA8B;AACxF,OAAOC,SAAS,aAAa;AAC7B,OAAOC,YAAY,SAAS;AAC5B,SAAsCC,OAAO,QAAsB,YAAY;AAE/E,SAASC,eAAe,QAAQ,sBAAsB;AACtD,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D,SAAsBC,cAAc,QAAQ,qBAAqB;AACjE,SAASC,sCAAsC,QAAQ,gDAAgD;AACvG,SAASC,6BAA6B,QAAQ,uCAAuC;AACrF,SAASC,yBAAyB,QAAQ,iCAAiC;AAC3E,SAASC,+BAA+B,QAAQ,yCAAyC;AAgBzF,OAAO,eAAeC,cAAc,EAChCC,KAAK,EACLC,cAAc,EACdC,kBAAkB,EAClBC,sBAAsB,CAAC,CAAC,EACxBC,8BAA8B,CAAC,CAAC,EAChCC,UAAU,EACVC,MAAM,EACNC,OAAO,EACPC,cAAc,EACG;QA+CbC;IA9CJ,MAAM,EACFC,QAAQ,EACRC,MAAMF,QAAQ,EACdG,KAAKC,UAAU,EAClB,GAAG,MAAMpB,kBAAkB;QACxBO;QACAE;QACAD;QACAO;QACAD;QACAD;IACJ;IAEA,MAAM,EAAEQ,WAAW,EAAEC,IAAI,EAAEC,kBAAkB,EAAE,GAAGP;IAClD,MAAMQ,kBAAkBJ,WAAWK,OAAO,CAAC,uBAAuB;IAClE,MAAMC,eAAe3B,gBAAgByB;IAErC,IAAIG;IACJ,IAAIX,SAAS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CJ,UAAU1B,IAAIiC,QAAQ;IAC1B;IAEA,MAAMC,OAAoB;QACtBC,KAAKlB,YAAYkB,GAAG,CAACC,GAAG,CAACjB,CAAAA,OAAQ,GAAGO,QAAQ,CAAC,EAAEP,MAAM;QACrDkB,IAAIpB,YAAYoB,EAAE,CAACD,GAAG,CAACjB,CAAAA,OAAQ,GAAGO,QAAQ,CAAC,EAAEP,MAAM;IACvD;IAEA,MAAMmB,cAAc3B,uBAAuB,aAAa,CAAC,SAAS,EAAER,MAAM,GAAGA;IAE7E,OAAO;QACHD;QACAJ;QACAoB;QACAqB,wBAAwBtD,0BAA0BiB,aAAaM;QAC/DgC,4BAA4BxD,8BAA8BkB;QAC1DuC,qCAAqC1D,uCACjCmB,aACAV;QAEJkD,8BAA8BxD,gCAAgCgB;QAC9DQ;QACAC;QACAuB;QACAS,cAAcL;QACdM,SAAS/C,SAAS+C,OAAO;QACzBC,QAAQ5B,YAAY4B,MAAM;IAC9B;AACJ"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"get-mfe-supports-versioned-ld-client.d.ts","sourceRoot":"","sources":["../../src/utils/get-mfe-supports-versioned-ld-client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAOzC,wBAAgB,+BAA+B,CAAC,WAAW,EAAE,QAAQ,CAAC,aAAa,CAAC,WAGnF"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import semver from 'semver';
|
|
2
|
+
/*
|
|
3
|
+
* Check if the MFE's @servicetitan/launchdarkly-service is new enough to prefer
|
|
4
|
+
* LDService.getVersionClient over LDService.getClient, and so can safely receive a
|
|
5
|
+
* host-provided LDService even when the LaunchDarkly SDK versions don't match exactly.
|
|
6
|
+
*/ export function getMFESupportsVersionedLDClient(bundledWith) {
|
|
7
|
+
const version = bundledWith === null || bundledWith === void 0 ? void 0 : bundledWith['@servicetitan/launchdarkly-service'];
|
|
8
|
+
return !!version && semver.gte(version, '40.0.0');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=get-mfe-supports-versioned-ld-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils/get-mfe-supports-versioned-ld-client.ts"],"sourcesContent":["import semver from 'semver';\nimport type { Metadata } from '../types';\n\n/*\n * Check if the MFE's @servicetitan/launchdarkly-service is new enough to prefer\n * LDService.getVersionClient over LDService.getClient, and so can safely receive a\n * host-provided LDService even when the LaunchDarkly SDK versions don't match exactly.\n */\nexport function getMFESupportsVersionedLDClient(bundledWith: Metadata['bundledWith']) {\n const version = bundledWith?.['@servicetitan/launchdarkly-service'];\n return !!version && semver.gte(version, '40.0.0');\n}\n"],"names":["semver","getMFESupportsVersionedLDClient","bundledWith","version","gte"],"mappings":"AAAA,OAAOA,YAAY,SAAS;AAG5B;;;;CAIC,GACD,OAAO,SAASC,gCAAgCC,WAAoC;IAChF,MAAMC,UAAUD,wBAAAA,kCAAAA,WAAa,CAAC,qCAAqC;IACnE,OAAO,CAAC,CAACC,WAAWH,OAAOI,GAAG,CAACD,SAAS;AAC5C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-scripts.d.ts","sourceRoot":"","sources":["../../src/utils/load-scripts.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"load-scripts.d.ts","sourceRoot":"","sources":["../../src/utils/load-scripts.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE/C,wBAAgB,WAAW,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,EAAE,UAAU,mBAwDrE"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { createNetworkError } from '../common';
|
|
1
2
|
export function loadScripts({ urls, WebComponent, module }) {
|
|
2
3
|
return Promise.all(urls.js.map((url)=>{
|
|
3
4
|
const script = Array.from(document.scripts).find(({ src })=>src === url);
|
|
4
5
|
if (!script) {
|
|
5
|
-
return new Promise((resolve)=>{
|
|
6
|
+
return new Promise((resolve, reject)=>{
|
|
6
7
|
const script = document.createElement('script');
|
|
7
8
|
if (module) {
|
|
8
9
|
script.type = 'module';
|
|
@@ -13,20 +14,35 @@ export function loadScripts({ urls, WebComponent, module }) {
|
|
|
13
14
|
script.onload = ()=>{
|
|
14
15
|
script.dataset.webComponent = WebComponent;
|
|
15
16
|
script.onload = null;
|
|
17
|
+
script.onerror = null;
|
|
16
18
|
resolve();
|
|
17
19
|
};
|
|
20
|
+
script.onerror = ()=>{
|
|
21
|
+
/*
|
|
22
|
+
* Remove the failed script so a later remount can retry
|
|
23
|
+
* instead of waiting on it forever.
|
|
24
|
+
*/ script.remove();
|
|
25
|
+
reject(createNetworkError(`Failed to load script: "${url}".`));
|
|
26
|
+
};
|
|
18
27
|
script.src = url;
|
|
19
28
|
document.body.append(script);
|
|
20
29
|
});
|
|
21
30
|
}
|
|
22
31
|
if (!script.dataset.webComponent) {
|
|
23
|
-
return new Promise((resolve)=>{
|
|
32
|
+
return new Promise((resolve, reject)=>{
|
|
24
33
|
const originalOnload = script.onload;
|
|
34
|
+
const originalOnerror = script.onerror;
|
|
25
35
|
script.onload = (...args)=>{
|
|
26
36
|
originalOnload === null || originalOnload === void 0 ? void 0 : originalOnload.call(script, ...args);
|
|
27
37
|
script.onload = null;
|
|
38
|
+
script.onerror = null;
|
|
28
39
|
resolve();
|
|
29
40
|
};
|
|
41
|
+
script.onerror = (...args)=>{
|
|
42
|
+
originalOnerror === null || originalOnerror === void 0 ? void 0 : originalOnerror.call(script, ...args);
|
|
43
|
+
script.remove();
|
|
44
|
+
reject(createNetworkError(`Failed to load script: "${url}".`));
|
|
45
|
+
};
|
|
30
46
|
});
|
|
31
47
|
}
|
|
32
48
|
return Promise.resolve();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/load-scripts.ts"],"sourcesContent":["import { BundleInfo } from './get-bundle-info';\n\nexport function loadScripts({ urls, WebComponent, module }: BundleInfo) {\n return Promise.all(\n urls.js.map(url => {\n const script = Array.from(document.scripts).find(({ src }) => src === url);\n if (!script) {\n return new Promise<void>(resolve => {\n const script = document.createElement('script');\n\n if (module) {\n script.type = 'module';\n } else {\n script.async = true;\n }\n\n script.crossOrigin = 'anonymous';\n script.onload = () => {\n script.dataset.webComponent = WebComponent;\n script.onload = null;\n resolve();\n };\n script.src = url;\n\n document.body.append(script);\n });\n }\n\n if (!script.dataset.webComponent) {\n return new Promise<void>(resolve => {\n const originalOnload = script.onload;\n script.onload = (...args) => {\n originalOnload?.call(script, ...args);\n script.onload = null;\n resolve();\n };\n });\n }\n\n return Promise.resolve();\n })\n );\n}\n"],"names":["loadScripts","urls","WebComponent","module","Promise","all","js","map","url","script","Array","from","document","scripts","find","src","resolve","createElement","type","async","crossOrigin","onload","dataset","webComponent","body","append","originalOnload","args","call"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../src/utils/load-scripts.ts"],"sourcesContent":["import { createNetworkError } from '../common';\nimport { BundleInfo } from './get-bundle-info';\n\nexport function loadScripts({ urls, WebComponent, module }: BundleInfo) {\n return Promise.all(\n urls.js.map(url => {\n const script = Array.from(document.scripts).find(({ src }) => src === url);\n if (!script) {\n return new Promise<void>((resolve, reject) => {\n const script = document.createElement('script');\n\n if (module) {\n script.type = 'module';\n } else {\n script.async = true;\n }\n\n script.crossOrigin = 'anonymous';\n script.onload = () => {\n script.dataset.webComponent = WebComponent;\n script.onload = null;\n script.onerror = null;\n resolve();\n };\n script.onerror = () => {\n /*\n * Remove the failed script so a later remount can retry\n * instead of waiting on it forever.\n */\n script.remove();\n reject(createNetworkError(`Failed to load script: \"${url}\".`));\n };\n script.src = url;\n\n document.body.append(script);\n });\n }\n\n if (!script.dataset.webComponent) {\n return new Promise<void>((resolve, reject) => {\n const originalOnload = script.onload;\n const originalOnerror = script.onerror;\n script.onload = (...args) => {\n originalOnload?.call(script, ...args);\n script.onload = null;\n script.onerror = null;\n resolve();\n };\n script.onerror = (...args) => {\n originalOnerror?.call(script, ...args);\n script.remove();\n reject(createNetworkError(`Failed to load script: \"${url}\".`));\n };\n });\n }\n\n return Promise.resolve();\n })\n );\n}\n"],"names":["createNetworkError","loadScripts","urls","WebComponent","module","Promise","all","js","map","url","script","Array","from","document","scripts","find","src","resolve","reject","createElement","type","async","crossOrigin","onload","dataset","webComponent","onerror","remove","body","append","originalOnload","originalOnerror","args","call"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,YAAY;AAG/C,OAAO,SAASC,YAAY,EAAEC,IAAI,EAAEC,YAAY,EAAEC,MAAM,EAAc;IAClE,OAAOC,QAAQC,GAAG,CACdJ,KAAKK,EAAE,CAACC,GAAG,CAACC,CAAAA;QACR,MAAMC,SAASC,MAAMC,IAAI,CAACC,SAASC,OAAO,EAAEC,IAAI,CAAC,CAAC,EAAEC,GAAG,EAAE,GAAKA,QAAQP;QACtE,IAAI,CAACC,QAAQ;YACT,OAAO,IAAIL,QAAc,CAACY,SAASC;gBAC/B,MAAMR,SAASG,SAASM,aAAa,CAAC;gBAEtC,IAAIf,QAAQ;oBACRM,OAAOU,IAAI,GAAG;gBAClB,OAAO;oBACHV,OAAOW,KAAK,GAAG;gBACnB;gBAEAX,OAAOY,WAAW,GAAG;gBACrBZ,OAAOa,MAAM,GAAG;oBACZb,OAAOc,OAAO,CAACC,YAAY,GAAGtB;oBAC9BO,OAAOa,MAAM,GAAG;oBAChBb,OAAOgB,OAAO,GAAG;oBACjBT;gBACJ;gBACAP,OAAOgB,OAAO,GAAG;oBACb;;;yBAGC,GACDhB,OAAOiB,MAAM;oBACbT,OAAOlB,mBAAmB,CAAC,wBAAwB,EAAES,IAAI,EAAE,CAAC;gBAChE;gBACAC,OAAOM,GAAG,GAAGP;gBAEbI,SAASe,IAAI,CAACC,MAAM,CAACnB;YACzB;QACJ;QAEA,IAAI,CAACA,OAAOc,OAAO,CAACC,YAAY,EAAE;YAC9B,OAAO,IAAIpB,QAAc,CAACY,SAASC;gBAC/B,MAAMY,iBAAiBpB,OAAOa,MAAM;gBACpC,MAAMQ,kBAAkBrB,OAAOgB,OAAO;gBACtChB,OAAOa,MAAM,GAAG,CAAC,GAAGS;oBAChBF,2BAAAA,qCAAAA,eAAgBG,IAAI,CAACvB,WAAWsB;oBAChCtB,OAAOa,MAAM,GAAG;oBAChBb,OAAOgB,OAAO,GAAG;oBACjBT;gBACJ;gBACAP,OAAOgB,OAAO,GAAG,CAAC,GAAGM;oBACjBD,4BAAAA,sCAAAA,gBAAiBE,IAAI,CAACvB,WAAWsB;oBACjCtB,OAAOiB,MAAM;oBACbT,OAAOlB,mBAAmB,CAAC,wBAAwB,EAAES,IAAI,EAAE,CAAC;gBAChE;YACJ;QACJ;QAEA,OAAOJ,QAAQY,OAAO;IAC1B;AAER"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@servicetitan/web-components",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "40.0.0",
|
|
4
4
|
"description": "Framework to build, register, and load Microfrontends into host applications",
|
|
5
5
|
"homepage": "https://docs.st.dev/docs/frontend/uikit/web-components",
|
|
6
6
|
"repository": {
|
|
@@ -31,19 +31,19 @@
|
|
|
31
31
|
"src"
|
|
32
32
|
],
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@servicetitan/error-boundary": "
|
|
35
|
-
"@servicetitan/startup-utils": "
|
|
34
|
+
"@servicetitan/error-boundary": "40.0.0",
|
|
35
|
+
"@servicetitan/startup-utils": "40.0.0",
|
|
36
36
|
"lodash.get": "~4.4.2",
|
|
37
37
|
"mitt": "~3.0.1",
|
|
38
38
|
"semver": "~7.8.5"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
|
-
"@servicetitan/anvil2": "^3.13.
|
|
41
|
+
"@servicetitan/anvil2": "^3.13.7",
|
|
42
42
|
"@servicetitan/design-system": "~14.5.3",
|
|
43
|
-
"@servicetitan/launchdarkly-service": "
|
|
44
|
-
"@servicetitan/log-service": "
|
|
45
|
-
"@servicetitan/react-ioc": "
|
|
46
|
-
"@testing-library/dom": "^10.4.
|
|
43
|
+
"@servicetitan/launchdarkly-service": "40.0.0",
|
|
44
|
+
"@servicetitan/log-service": "40.0.0",
|
|
45
|
+
"@servicetitan/react-ioc": "40.0.0",
|
|
46
|
+
"@testing-library/dom": "^10.4.2",
|
|
47
47
|
"@testing-library/jest-dom": "^7.0.1",
|
|
48
48
|
"@testing-library/react": "^16.3.3",
|
|
49
49
|
"@types/history": "~4.7.10",
|
|
@@ -52,7 +52,6 @@
|
|
|
52
52
|
"@types/react-dom": "~18.3.0",
|
|
53
53
|
"@types/semver": "~7.7.1",
|
|
54
54
|
"history": "~4.10.1",
|
|
55
|
-
"launchdarkly-react-client-sdk": "3.6.1",
|
|
56
55
|
"react": "~18.3.1",
|
|
57
56
|
"react-dom": "~18.3.1",
|
|
58
57
|
"shadow-dom-testing-library": "^1.14.1"
|
|
@@ -60,9 +59,9 @@
|
|
|
60
59
|
"peerDependencies": {
|
|
61
60
|
"@servicetitan/anvil2": ">=1.5.0",
|
|
62
61
|
"@servicetitan/design-system": ">=14.5.3",
|
|
63
|
-
"@servicetitan/launchdarkly-service": "
|
|
64
|
-
"@servicetitan/log-service": "
|
|
65
|
-
"@servicetitan/react-ioc": "
|
|
62
|
+
"@servicetitan/launchdarkly-service": "40.0.0",
|
|
63
|
+
"@servicetitan/log-service": "40.0.0",
|
|
64
|
+
"@servicetitan/react-ioc": "40.0.0",
|
|
66
65
|
"history": "~4.10.1",
|
|
67
66
|
"react": ">=17.0.2",
|
|
68
67
|
"react-dom": ">=17.0.2"
|
|
@@ -18,12 +18,14 @@ import { Loader, LoaderProps, UnrestrictedLoaderProps } from '../loader';
|
|
|
18
18
|
import { Metadata } from '../types';
|
|
19
19
|
import { getMFEHasCompatibleLaunchDarklyVersion } from '../utils/get-mfe-has-compatible-launchdarkly-version';
|
|
20
20
|
import { getMFEHasUniqueChunkNamespace } from '../utils/get-mfe-has-unique-chunk-namespace';
|
|
21
|
+
import { getMFESupportsVersionedLDClient } from '../utils/get-mfe-supports-versioned-ld-client';
|
|
21
22
|
|
|
22
23
|
jest.mock('@servicetitan/startup-utils', () => ({
|
|
23
24
|
getVersionMismatches: jest.fn(),
|
|
24
25
|
}));
|
|
25
26
|
jest.mock('../utils/get-mfe-has-compatible-launchdarkly-version');
|
|
26
27
|
jest.mock('../utils/get-mfe-has-unique-chunk-namespace');
|
|
28
|
+
jest.mock('../utils/get-mfe-supports-versioned-ld-client');
|
|
27
29
|
|
|
28
30
|
describe('[web-components] Loader', () => {
|
|
29
31
|
const localHosts = ['localhost', '127.0.0.1'];
|
|
@@ -48,6 +50,7 @@ describe('[web-components] Loader', () => {
|
|
|
48
50
|
|
|
49
51
|
let props: LoaderProps<any>;
|
|
50
52
|
let onloadRef: Function | null;
|
|
53
|
+
let onerrorRef: Function | null;
|
|
51
54
|
let singletons: ProviderProps['singletons'];
|
|
52
55
|
let getJsonMockFns: Record<string, Function>;
|
|
53
56
|
|
|
@@ -62,8 +65,8 @@ describe('[web-components] Loader', () => {
|
|
|
62
65
|
window.customElements.define(WEB_COMPONENT_NAME, WebComponent);
|
|
63
66
|
|
|
64
67
|
/*
|
|
65
|
-
* mock <script>'s onload so that we can call
|
|
66
|
-
* because
|
|
68
|
+
* mock <script>'s onload/onerror so that we can call them directly from the test,
|
|
69
|
+
* because they won't call themselves in the test environment
|
|
67
70
|
*/
|
|
68
71
|
Object.defineProperty(HTMLScriptElement.prototype, 'onload', {
|
|
69
72
|
get() {
|
|
@@ -74,6 +77,15 @@ describe('[web-components] Loader', () => {
|
|
|
74
77
|
this._onload = onload;
|
|
75
78
|
},
|
|
76
79
|
});
|
|
80
|
+
Object.defineProperty(HTMLScriptElement.prototype, 'onerror', {
|
|
81
|
+
get() {
|
|
82
|
+
return this._onerror;
|
|
83
|
+
},
|
|
84
|
+
set(onerror: Function) {
|
|
85
|
+
onerrorRef = onerror;
|
|
86
|
+
this._onerror = onerror;
|
|
87
|
+
},
|
|
88
|
+
});
|
|
77
89
|
});
|
|
78
90
|
|
|
79
91
|
function initializeGetJsonMockFns(url = baseUrl) {
|
|
@@ -113,6 +125,7 @@ describe('[web-components] Loader', () => {
|
|
|
113
125
|
setStartupVersion('27.2.0');
|
|
114
126
|
props = { src: baseUrl, cache: false };
|
|
115
127
|
onloadRef = null;
|
|
128
|
+
onerrorRef = null;
|
|
116
129
|
singletons = [];
|
|
117
130
|
initializeGetJsonMockFns();
|
|
118
131
|
|
|
@@ -125,6 +138,7 @@ describe('[web-components] Loader', () => {
|
|
|
125
138
|
jest.mocked(getMFEHasCompatibleLaunchDarklyVersion).mockReturnValue(true);
|
|
126
139
|
jest.mocked(getVersionMismatches).mockReturnValue(undefined);
|
|
127
140
|
jest.mocked(getMFEHasUniqueChunkNamespace).mockReturnValue(true);
|
|
141
|
+
jest.mocked(getMFESupportsVersionedLDClient).mockReturnValue(false);
|
|
128
142
|
});
|
|
129
143
|
|
|
130
144
|
const Root = () => (
|
|
@@ -152,6 +166,52 @@ describe('[web-components] Loader', () => {
|
|
|
152
166
|
expect(common.getJson).toHaveBeenCalledTimes(1);
|
|
153
167
|
}
|
|
154
168
|
|
|
169
|
+
function itRendersErrorFallback(triggerFailure?: () => void | Promise<void>) {
|
|
170
|
+
beforeEach(() => {
|
|
171
|
+
jest.spyOn(console, 'error').mockImplementation(jest.fn); // suppress error boundary logging
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
test('renders default error fallback', async () => {
|
|
175
|
+
subject();
|
|
176
|
+
await triggerFailure?.();
|
|
177
|
+
|
|
178
|
+
await waitFor(() =>
|
|
179
|
+
expect(screen.getByText('Something went wrong')).toBeInTheDocument()
|
|
180
|
+
);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
describe.each(localHosts)('when src contains "%s"', host => {
|
|
184
|
+
beforeEach(() => {
|
|
185
|
+
props.src = `http://${host}/mfe`;
|
|
186
|
+
initializeGetJsonMockFns(props.src);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
test('appends src to error fallback', async () => {
|
|
190
|
+
subject();
|
|
191
|
+
await triggerFailure?.();
|
|
192
|
+
|
|
193
|
+
await waitFor(() =>
|
|
194
|
+
expect(
|
|
195
|
+
screen.getByText(`Something went wrong loading ${props.src}`)
|
|
196
|
+
).toBeInTheDocument()
|
|
197
|
+
);
|
|
198
|
+
});
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
describe('when an errorFallback is provided', () => {
|
|
202
|
+
beforeEach(() => {
|
|
203
|
+
props.errorFallback = <div>bar</div>;
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
test('renders provided error fallback', async () => {
|
|
207
|
+
subject();
|
|
208
|
+
await triggerFailure?.();
|
|
209
|
+
|
|
210
|
+
await waitFor(() => expect(screen.getByText('bar')).toBeInTheDocument());
|
|
211
|
+
});
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
155
215
|
describe.each(localHosts)('when src contains "%s"', host => {
|
|
156
216
|
beforeEach(() => {
|
|
157
217
|
props.src = `http://${host}/mfe`;
|
|
@@ -211,49 +271,13 @@ describe('[web-components] Loader', () => {
|
|
|
211
271
|
|
|
212
272
|
describe('when the loadingFallback throws an error', () => {
|
|
213
273
|
beforeEach(() => {
|
|
214
|
-
jest.spyOn(console, 'error').mockImplementation(jest.fn); // suppress console output
|
|
215
274
|
const ThrowError: FC = () => {
|
|
216
275
|
throw new Error('woops');
|
|
217
276
|
};
|
|
218
277
|
props.loadingFallback = <ThrowError />;
|
|
219
278
|
});
|
|
220
279
|
|
|
221
|
-
|
|
222
|
-
subject();
|
|
223
|
-
|
|
224
|
-
await waitFor(() =>
|
|
225
|
-
expect(screen.getByText('Something went wrong')).toBeInTheDocument()
|
|
226
|
-
);
|
|
227
|
-
});
|
|
228
|
-
|
|
229
|
-
describe.each(localHosts)('when src contains "%s"', host => {
|
|
230
|
-
beforeEach(() => {
|
|
231
|
-
props.src = `http://${host}/mfe`;
|
|
232
|
-
initializeGetJsonMockFns(props.src);
|
|
233
|
-
});
|
|
234
|
-
|
|
235
|
-
test('appends src to error fallback', async () => {
|
|
236
|
-
subject();
|
|
237
|
-
|
|
238
|
-
await waitFor(() =>
|
|
239
|
-
expect(
|
|
240
|
-
screen.getByText(`Something went wrong loading ${props.src}`)
|
|
241
|
-
).toBeInTheDocument()
|
|
242
|
-
);
|
|
243
|
-
});
|
|
244
|
-
});
|
|
245
|
-
|
|
246
|
-
describe('when an errorFallback is provided', () => {
|
|
247
|
-
beforeEach(() => {
|
|
248
|
-
props.errorFallback = <div>bar</div>;
|
|
249
|
-
});
|
|
250
|
-
|
|
251
|
-
test('renders provided error fallback', async () => {
|
|
252
|
-
subject();
|
|
253
|
-
|
|
254
|
-
await waitFor(() => expect(screen.getByText('bar')).toBeInTheDocument());
|
|
255
|
-
});
|
|
256
|
-
});
|
|
280
|
+
itRendersErrorFallback();
|
|
257
281
|
});
|
|
258
282
|
|
|
259
283
|
describe('when loadingFallback is not delayed', () => {
|
|
@@ -711,9 +735,10 @@ describe('[web-components] Loader', () => {
|
|
|
711
735
|
});
|
|
712
736
|
|
|
713
737
|
describe('when ldService is provided via EXPOSED_INSTANCE_DEPENDENCIES', () => {
|
|
714
|
-
|
|
738
|
+
let ldService: { getVersionClient?: jest.Mock };
|
|
715
739
|
|
|
716
740
|
beforeEach(() => {
|
|
741
|
+
ldService = {};
|
|
717
742
|
singletons?.push({
|
|
718
743
|
provide: EXPOSED_INSTANCE_DEPENDENCIES_TOKEN,
|
|
719
744
|
useValue: { launchDarkly: { version: '1.0', ldService } },
|
|
@@ -730,9 +755,32 @@ describe('[web-components] Loader', () => {
|
|
|
730
755
|
jest.mocked(getMFEHasCompatibleLaunchDarklyVersion).mockReturnValue(false);
|
|
731
756
|
});
|
|
732
757
|
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
758
|
+
function itDoesNotProvideLDService() {
|
|
759
|
+
test('does not provide ldService to the web component', async () => {
|
|
760
|
+
await webComponentReadySetup();
|
|
761
|
+
expect(webComponentState.ldService).toBeUndefined();
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
itDoesNotProvideLDService();
|
|
766
|
+
|
|
767
|
+
describe('when MFE supports a versioned LD client', () => {
|
|
768
|
+
beforeEach(() => {
|
|
769
|
+
jest.mocked(getMFESupportsVersionedLDClient).mockReturnValue(true);
|
|
770
|
+
});
|
|
771
|
+
|
|
772
|
+
itDoesNotProvideLDService();
|
|
773
|
+
|
|
774
|
+
describe("when the host's LDService supports a versioned client", () => {
|
|
775
|
+
beforeEach(() => {
|
|
776
|
+
ldService.getVersionClient = jest.fn();
|
|
777
|
+
});
|
|
778
|
+
|
|
779
|
+
test('provides ldService to the web component', async () => {
|
|
780
|
+
await webComponentReadySetup();
|
|
781
|
+
expect(webComponentState.ldService).toEqual(ldService);
|
|
782
|
+
});
|
|
783
|
+
});
|
|
736
784
|
});
|
|
737
785
|
});
|
|
738
786
|
});
|
|
@@ -863,11 +911,6 @@ describe('[web-components] Loader', () => {
|
|
|
863
911
|
document.body.appendChild(script);
|
|
864
912
|
});
|
|
865
913
|
|
|
866
|
-
test("the script tag's original onload is called", async () => {
|
|
867
|
-
await webComponentReadySetup();
|
|
868
|
-
expect(originalOnloadSpy).toHaveBeenCalled();
|
|
869
|
-
});
|
|
870
|
-
|
|
871
914
|
test('onload handler gets unassigned after it gets called', async () => {
|
|
872
915
|
await webComponentReadySetup();
|
|
873
916
|
expect(onloadRef).toBeNull();
|
|
@@ -980,6 +1023,28 @@ describe('[web-components] Loader', () => {
|
|
|
980
1023
|
});
|
|
981
1024
|
});
|
|
982
1025
|
|
|
1026
|
+
describe('when the script tag fails to load', () => {
|
|
1027
|
+
beforeEach(() => {
|
|
1028
|
+
jest.spyOn(console, 'error').mockImplementation(jest.fn); // suppress error boundary logging
|
|
1029
|
+
});
|
|
1030
|
+
|
|
1031
|
+
async function triggerScriptError() {
|
|
1032
|
+
await waitFor(() => onerrorRef !== null);
|
|
1033
|
+
act(() => {
|
|
1034
|
+
onerrorRef!();
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
itRendersErrorFallback(triggerScriptError);
|
|
1039
|
+
|
|
1040
|
+
test('does not hang on the loading fallback', async () => {
|
|
1041
|
+
subject();
|
|
1042
|
+
await triggerScriptError();
|
|
1043
|
+
|
|
1044
|
+
await waitFor(() => expect(screen.queryByText(/loading/i)).not.toBeInTheDocument());
|
|
1045
|
+
});
|
|
1046
|
+
});
|
|
1047
|
+
|
|
983
1048
|
describe('when cache is enabled', () => {
|
|
984
1049
|
beforeAll(() => {
|
|
985
1050
|
jest.useFakeTimers();
|
package/src/common.ts
CHANGED
|
@@ -47,7 +47,7 @@ interface GetJsonOptions extends RequestInit {
|
|
|
47
47
|
onRequestError?(error: GetJsonError): void;
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
function createNetworkError(message: string) {
|
|
50
|
+
export function createNetworkError(message: string) {
|
|
51
51
|
const error = new Error(message);
|
|
52
52
|
|
|
53
53
|
error.name = 'NetworkError';
|
package/src/loader.tsx
CHANGED
|
@@ -229,9 +229,13 @@ function lazyWebComponent(props: LazyLoaderProps) {
|
|
|
229
229
|
|
|
230
230
|
await loadScripts(bundleInfo);
|
|
231
231
|
|
|
232
|
-
const
|
|
233
|
-
|
|
234
|
-
|
|
232
|
+
const hostLDService = exposedInstanceDependencies?.launchDarkly?.ldService;
|
|
233
|
+
const hostSupportsVersionedLDClient = typeof hostLDService?.getVersionClient === 'function';
|
|
234
|
+
const ldService =
|
|
235
|
+
bundleInfo.mfeHasCompatibleLaunchDarklyVersion ||
|
|
236
|
+
(bundleInfo.mfeSupportsVersionedLDClient && hostSupportsVersionedLDClient)
|
|
237
|
+
? hostLDService
|
|
238
|
+
: undefined;
|
|
235
239
|
|
|
236
240
|
return {
|
|
237
241
|
default: webComponent({
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { Metadata } from '../../types';
|
|
2
|
+
import { getMFESupportsVersionedLDClient } from '../get-mfe-supports-versioned-ld-client';
|
|
3
|
+
|
|
4
|
+
describe(`[web-components] ${getMFESupportsVersionedLDClient.name}`, () => {
|
|
5
|
+
let bundledWith: NonNullable<Metadata['bundledWith']>;
|
|
6
|
+
|
|
7
|
+
beforeEach(() => {
|
|
8
|
+
bundledWith = {};
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
const subject = () => getMFESupportsVersionedLDClient(bundledWith);
|
|
12
|
+
|
|
13
|
+
function itReturns(value: boolean) {
|
|
14
|
+
test(`returns ${value}`, () => {
|
|
15
|
+
expect(subject()).toBe(value);
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
itReturns(false);
|
|
20
|
+
|
|
21
|
+
describe('when bundledWith @servicetitan/launchdarkly-service is below the threshold version', () => {
|
|
22
|
+
beforeEach(() => (bundledWith['@servicetitan/launchdarkly-service'] = '39.5.0'));
|
|
23
|
+
|
|
24
|
+
itReturns(false);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
describe('when bundledWith @servicetitan/launchdarkly-service meets the threshold version', () => {
|
|
28
|
+
beforeEach(() => (bundledWith['@servicetitan/launchdarkly-service'] = '40.0.0'));
|
|
29
|
+
|
|
30
|
+
itReturns(true);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe('when bundledWith @servicetitan/launchdarkly-service exceeds the threshold version', () => {
|
|
34
|
+
beforeEach(() => (bundledWith['@servicetitan/launchdarkly-service'] = '41.0.0'));
|
|
35
|
+
|
|
36
|
+
itReturns(true);
|
|
37
|
+
});
|
|
38
|
+
});
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import '@testing-library/jest-dom';
|
|
2
|
+
import { BundleInfo } from '../get-bundle-info';
|
|
3
|
+
import { loadScripts } from '../load-scripts';
|
|
4
|
+
|
|
5
|
+
describe('[web-components] loadScripts', () => {
|
|
6
|
+
const url = 'https://unpkg.servicetitan.com/mfe/dist/bundle/light/light.js';
|
|
7
|
+
const webComponentName = 'my-mfe';
|
|
8
|
+
|
|
9
|
+
let bundleInfo: BundleInfo;
|
|
10
|
+
let onloadRef: (() => void) | null;
|
|
11
|
+
let onerrorRef: (() => void) | null;
|
|
12
|
+
|
|
13
|
+
beforeAll(() => {
|
|
14
|
+
/*
|
|
15
|
+
* mock <script>'s onload/onerror so that we can call them directly from the test,
|
|
16
|
+
* because they won't call themselves in the test environment
|
|
17
|
+
*/
|
|
18
|
+
Object.defineProperty(HTMLScriptElement.prototype, 'onload', {
|
|
19
|
+
configurable: true,
|
|
20
|
+
get() {
|
|
21
|
+
return this._onload;
|
|
22
|
+
},
|
|
23
|
+
set(onload) {
|
|
24
|
+
onloadRef = onload;
|
|
25
|
+
this._onload = onload;
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
Object.defineProperty(HTMLScriptElement.prototype, 'onerror', {
|
|
29
|
+
configurable: true,
|
|
30
|
+
get() {
|
|
31
|
+
return this._onerror;
|
|
32
|
+
},
|
|
33
|
+
set(onerror) {
|
|
34
|
+
onerrorRef = onerror;
|
|
35
|
+
this._onerror = onerror;
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
beforeEach(() => {
|
|
41
|
+
document.querySelectorAll('script').forEach(script => script.remove());
|
|
42
|
+
onloadRef = null;
|
|
43
|
+
onerrorRef = null;
|
|
44
|
+
bundleInfo = {
|
|
45
|
+
bundledWith: undefined,
|
|
46
|
+
cacheHit: undefined,
|
|
47
|
+
disposer: () => {},
|
|
48
|
+
mfeSupportsRerendering: false,
|
|
49
|
+
mfeHasUniqueChunkNamespace: false,
|
|
50
|
+
mfeHasCompatibleLaunchDarklyVersion: false,
|
|
51
|
+
mismatch: undefined,
|
|
52
|
+
resolvedBundleType: 'light',
|
|
53
|
+
urls: { js: [url], css: [] },
|
|
54
|
+
WebComponent: webComponentName,
|
|
55
|
+
version: undefined,
|
|
56
|
+
module: undefined,
|
|
57
|
+
};
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
const subject = () => loadScripts(bundleInfo);
|
|
61
|
+
|
|
62
|
+
function scriptTag() {
|
|
63
|
+
return document.querySelector(`script[src="${url}"]`) as HTMLScriptElement | null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
test('creates a script tag for the js url', () => {
|
|
67
|
+
subject();
|
|
68
|
+
|
|
69
|
+
expect(scriptTag()).toBeInTheDocument();
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test('sets crossOrigin to anonymous', () => {
|
|
73
|
+
subject();
|
|
74
|
+
|
|
75
|
+
expect(scriptTag()).toHaveAttribute('crossorigin', 'anonymous');
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
describe('when the script loads successfully', () => {
|
|
79
|
+
const subject = () => {
|
|
80
|
+
const promise = loadScripts(bundleInfo);
|
|
81
|
+
onloadRef!();
|
|
82
|
+
return promise;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
test('resolves', async () => {
|
|
86
|
+
await expect(subject()).resolves.toEqual([undefined]);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test('marks the script tag with the web component name', async () => {
|
|
90
|
+
await subject();
|
|
91
|
+
|
|
92
|
+
expect(scriptTag()).toHaveAttribute('data-web-component', webComponentName);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
test('unassigns the onload and onerror handlers', async () => {
|
|
96
|
+
await subject();
|
|
97
|
+
|
|
98
|
+
expect(scriptTag()!.onload).toBeNull();
|
|
99
|
+
expect(scriptTag()!.onerror).toBeNull();
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
describe('when the script fails to load', () => {
|
|
104
|
+
const subject = () => {
|
|
105
|
+
const promise = loadScripts(bundleInfo);
|
|
106
|
+
onerrorRef!();
|
|
107
|
+
return promise;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
test('rejects with a network error', async () => {
|
|
111
|
+
await expect(subject()).rejects.toThrow(`Failed to load script: "${url}".`);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test('removes the failed script tag from the DOM', async () => {
|
|
115
|
+
await subject().catch(() => {});
|
|
116
|
+
|
|
117
|
+
expect(scriptTag()).not.toBeInTheDocument();
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
describe('when a script tag for this bundle already exists without a webComponent data attribute', () => {
|
|
122
|
+
let originalOnloadSpy: jest.Mock;
|
|
123
|
+
let originalOnerrorSpy: jest.Mock;
|
|
124
|
+
|
|
125
|
+
beforeEach(() => {
|
|
126
|
+
originalOnloadSpy = jest.fn();
|
|
127
|
+
originalOnerrorSpy = jest.fn();
|
|
128
|
+
|
|
129
|
+
const script = document.createElement('script');
|
|
130
|
+
script.src = url;
|
|
131
|
+
script.onload = originalOnloadSpy;
|
|
132
|
+
script.onerror = originalOnerrorSpy;
|
|
133
|
+
document.body.appendChild(script);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
const subject = () => {
|
|
137
|
+
const promise = loadScripts(bundleInfo);
|
|
138
|
+
onloadRef!();
|
|
139
|
+
return promise;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
test('calls the original onload handler', async () => {
|
|
143
|
+
await subject();
|
|
144
|
+
|
|
145
|
+
expect(originalOnloadSpy).toHaveBeenCalled();
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
describe('when the script fails to load', () => {
|
|
149
|
+
const subject = () => {
|
|
150
|
+
const promise = loadScripts(bundleInfo);
|
|
151
|
+
onerrorRef!();
|
|
152
|
+
return promise;
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
test('calls the original onerror handler', async () => {
|
|
156
|
+
await subject().catch(() => {});
|
|
157
|
+
|
|
158
|
+
expect(originalOnerrorSpy).toHaveBeenCalled();
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
test('rejects with a network error', async () => {
|
|
162
|
+
await expect(subject()).rejects.toThrow(`Failed to load script: "${url}".`);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test('removes the failed script tag from the DOM', async () => {
|
|
166
|
+
await subject().catch(() => {});
|
|
167
|
+
|
|
168
|
+
expect(scriptTag()).not.toBeInTheDocument();
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
});
|
|
@@ -9,6 +9,7 @@ import { EntryPoints, getEntrypoints } from './get-entry-points';
|
|
|
9
9
|
import { getMFEHasCompatibleLaunchDarklyVersion } from './get-mfe-has-compatible-launchdarkly-version';
|
|
10
10
|
import { getMFEHasUniqueChunkNamespace } from './get-mfe-has-unique-chunk-namespace';
|
|
11
11
|
import { getMFESupportsRerendering } from './get-mfe-supports-rerendering';
|
|
12
|
+
import { getMFESupportsVersionedLDClient } from './get-mfe-supports-versioned-ld-client';
|
|
12
13
|
|
|
13
14
|
export type BundleInfo = Awaited<ReturnType<typeof getBundleInfo>>;
|
|
14
15
|
|
|
@@ -121,6 +122,7 @@ export async function getBundleInfo({
|
|
|
121
122
|
bundledWith,
|
|
122
123
|
exposedInstanceDependencies
|
|
123
124
|
),
|
|
125
|
+
mfeSupportsVersionedLDClient: getMFESupportsVersionedLDClient(bundledWith),
|
|
124
126
|
mismatch,
|
|
125
127
|
resolvedBundleType,
|
|
126
128
|
urls,
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import semver from 'semver';
|
|
2
|
+
import type { Metadata } from '../types';
|
|
3
|
+
|
|
4
|
+
/*
|
|
5
|
+
* Check if the MFE's @servicetitan/launchdarkly-service is new enough to prefer
|
|
6
|
+
* LDService.getVersionClient over LDService.getClient, and so can safely receive a
|
|
7
|
+
* host-provided LDService even when the LaunchDarkly SDK versions don't match exactly.
|
|
8
|
+
*/
|
|
9
|
+
export function getMFESupportsVersionedLDClient(bundledWith: Metadata['bundledWith']) {
|
|
10
|
+
const version = bundledWith?.['@servicetitan/launchdarkly-service'];
|
|
11
|
+
return !!version && semver.gte(version, '40.0.0');
|
|
12
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createNetworkError } from '../common';
|
|
1
2
|
import { BundleInfo } from './get-bundle-info';
|
|
2
3
|
|
|
3
4
|
export function loadScripts({ urls, WebComponent, module }: BundleInfo) {
|
|
@@ -5,7 +6,7 @@ export function loadScripts({ urls, WebComponent, module }: BundleInfo) {
|
|
|
5
6
|
urls.js.map(url => {
|
|
6
7
|
const script = Array.from(document.scripts).find(({ src }) => src === url);
|
|
7
8
|
if (!script) {
|
|
8
|
-
return new Promise<void>(resolve => {
|
|
9
|
+
return new Promise<void>((resolve, reject) => {
|
|
9
10
|
const script = document.createElement('script');
|
|
10
11
|
|
|
11
12
|
if (module) {
|
|
@@ -18,8 +19,17 @@ export function loadScripts({ urls, WebComponent, module }: BundleInfo) {
|
|
|
18
19
|
script.onload = () => {
|
|
19
20
|
script.dataset.webComponent = WebComponent;
|
|
20
21
|
script.onload = null;
|
|
22
|
+
script.onerror = null;
|
|
21
23
|
resolve();
|
|
22
24
|
};
|
|
25
|
+
script.onerror = () => {
|
|
26
|
+
/*
|
|
27
|
+
* Remove the failed script so a later remount can retry
|
|
28
|
+
* instead of waiting on it forever.
|
|
29
|
+
*/
|
|
30
|
+
script.remove();
|
|
31
|
+
reject(createNetworkError(`Failed to load script: "${url}".`));
|
|
32
|
+
};
|
|
23
33
|
script.src = url;
|
|
24
34
|
|
|
25
35
|
document.body.append(script);
|
|
@@ -27,13 +37,20 @@ export function loadScripts({ urls, WebComponent, module }: BundleInfo) {
|
|
|
27
37
|
}
|
|
28
38
|
|
|
29
39
|
if (!script.dataset.webComponent) {
|
|
30
|
-
return new Promise<void>(resolve => {
|
|
40
|
+
return new Promise<void>((resolve, reject) => {
|
|
31
41
|
const originalOnload = script.onload;
|
|
42
|
+
const originalOnerror = script.onerror;
|
|
32
43
|
script.onload = (...args) => {
|
|
33
44
|
originalOnload?.call(script, ...args);
|
|
34
45
|
script.onload = null;
|
|
46
|
+
script.onerror = null;
|
|
35
47
|
resolve();
|
|
36
48
|
};
|
|
49
|
+
script.onerror = (...args) => {
|
|
50
|
+
originalOnerror?.call(script, ...args);
|
|
51
|
+
script.remove();
|
|
52
|
+
reject(createNetworkError(`Failed to load script: "${url}".`));
|
|
53
|
+
};
|
|
37
54
|
});
|
|
38
55
|
}
|
|
39
56
|
|