@datadog/apps-frontend 0.0.6 → 0.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -11
- package/dist/src/_chunks/chunk-2ZECSTB4.js +7 -0
- package/dist/src/_chunks/chunk-2ZECSTB4.js.map +7 -0
- package/dist/src/deep-links/react/index.js +1 -1
- package/dist/src/embedding/react/index.d.ts +1 -1
- package/dist/src/embedding/react/index.js +1 -1
- package/dist/src/embedding/react/index.js.map +4 -4
- package/dist/src/embedding/react/provider.d.ts +42 -9
- package/dist/src/index.d.ts +1 -2
- package/dist/src/index.js +0 -1
- package/dist/src/index.js.map +4 -4
- package/package.json +2 -2
- package/dist/src/_chunks/chunk-3UFPUAWY.js +0 -7
- package/dist/src/_chunks/chunk-3UFPUAWY.js.map +0 -7
- package/dist/src/_chunks/chunk-MF7HCOXQ.js +0 -7
- package/dist/src/_chunks/chunk-MF7HCOXQ.js.map +0 -7
- package/dist/src/_chunks/chunk-VVRISDII.js +0 -7
- package/dist/src/_chunks/chunk-VVRISDII.js.map +0 -7
- package/dist/src/apps-provider.d.ts +0 -51
package/README.md
CHANGED
|
@@ -6,12 +6,13 @@ Frontend capabilities for Datadog Apps.
|
|
|
6
6
|
npm install @datadog/apps-frontend
|
|
7
7
|
```
|
|
8
8
|
|
|
9
|
-
The package root exposes
|
|
10
|
-
|
|
9
|
+
The package root exposes nothing: React capabilities live in this package's
|
|
10
|
+
subpath entries.
|
|
11
11
|
|
|
12
12
|
- `@datadog/apps-frontend/embedding/react` — `DatadogAppProvider`
|
|
13
|
-
connects an app to its host,
|
|
14
|
-
connection
|
|
13
|
+
connects an app to its host, installs this package's default modules, and
|
|
14
|
+
shares one embedding connection with every module hook beneath it;
|
|
15
|
+
`useDatadogAppEmbedding` reads that connection's state.
|
|
15
16
|
- `@datadog/apps-frontend/inputs/react` — `useDatadogAppInput` reads a typed
|
|
16
17
|
input the host provides.
|
|
17
18
|
- `@datadog/apps-frontend/inputs/schema` — the input schemas themselves, such
|
|
@@ -19,15 +20,15 @@ capabilities are reached through its subpath entries:
|
|
|
19
20
|
|
|
20
21
|
## Usage
|
|
21
22
|
|
|
22
|
-
Mount the
|
|
23
|
-
|
|
24
|
-
|
|
23
|
+
Mount the provider near your app root; it installs this package's default
|
|
24
|
+
modules and shares one embedding connection with every module hook beneath
|
|
25
|
+
it:
|
|
25
26
|
|
|
26
27
|
```tsx
|
|
27
|
-
import {
|
|
28
|
+
import { DatadogAppProvider } from '@datadog/apps-frontend/embedding/react';
|
|
28
29
|
|
|
29
30
|
export function App() {
|
|
30
|
-
return <
|
|
31
|
+
return <DatadogAppProvider>{/* app UI */}</DatadogAppProvider>;
|
|
31
32
|
}
|
|
32
33
|
```
|
|
33
34
|
|
|
@@ -37,9 +38,9 @@ startup capability, not a UI layer: on mount the provider runs each one's
|
|
|
37
38
|
renders untouched:
|
|
38
39
|
|
|
39
40
|
```tsx
|
|
40
|
-
<
|
|
41
|
+
<DatadogAppProvider modules={[someModule({ option: true })]}>
|
|
41
42
|
{/* app UI */}
|
|
42
|
-
</
|
|
43
|
+
</DatadogAppProvider>
|
|
43
44
|
```
|
|
44
45
|
|
|
45
46
|
`disabledModules` accepts exactly the ids of this package's default modules —
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/* Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0.
|
|
2
|
+
* This product includes software developed at Datadog (https://www.datadoghq.com/).
|
|
3
|
+
* Copyright 2019-Present Datadog, Inc.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import{a as u,d as b,g as v}from"./chunk-PA4Z7DNH.js";import{J as h,K as f}from"./chunk-LEEYMNMO.js";var y=Symbol("DatadogAppProviderModule");function A(t,e,n){if(t.length===0)throw new Error("A Datadog App provider module requires an id.");return Object.freeze({id:t,config:Object.freeze({...e}),[y]:n})}function k(t,e){try{console.error(`Installing the "${t}" Datadog App provider module failed; the remaining modules and the app still run.`,e)}catch{}}function F(t,e,n){let a=new Set;for(let o of t){if(a.has(o.id))throw new Error(`DatadogAppProvider received duplicate module "${o.id}".`);a.add(o.id)}let d=Object.freeze({embedding:e,disposeSignal:n});for(let o of t)try{o[y].install(d)}catch(i){k(o.id,i)}}var S=u(),D=b(),P=f({identifier:"datadog.deep-links",version:2,fields:{setDeepLinkState:h.readOnly({inputs:{search:S,fragment:S},result:D})}}),T=v(u(),u()),_=f({identifier:"datadog.deep-links",version:1,fields:{setDeepLinkVariables:h.readOnly({inputs:{variables:T,fragment:S},result:D})}});var C=Object.freeze({search:"",fragment:""});function M(){return typeof globalThis.location>"u"?C:Object.freeze({search:globalThis.location.search,fragment:globalThis.location.hash})}function x(t,e){console.error(`[datadog-apps:deep-links] ${t}`,e??"")}var r=null;function l(){m()}function E({search:t,fragment:e}){return JSON.stringify([t,e])}function m(t=!1){let e=r;if(e===null)return;let n=M(),a=E(n);!t&&e.lastPublishedFingerprint===a||(e.lastPublishedFingerprint=a,R(n))}function R(t){let e=r?.publishers;if(e===void 0)return;let n=e.values().next();n.done===!1&&n.value(t)}function I(t){let e=r?.publishers;if(e===void 0)return!1;let n=e.values().next();return n.done===!1&&n.value===t}function w(t){if(r!==null)return r.publishers.add(t),r;let e=globalThis.history,n=e.pushState,a=e.replaceState,d=new Set([t]),o=()=>{m()},i=function(s,c,g){n.call(e,s,c,g),o()},p=function(s,c,g){a.call(e,s,c,g),o()};try{e.pushState=i,e.replaceState=p,globalThis.addEventListener("popstate",l),globalThis.addEventListener("hashchange",l)}catch(s){throw e.replaceState===p&&(e.replaceState=a),e.pushState===i&&(e.pushState=n),globalThis.removeEventListener("popstate",l),globalThis.removeEventListener("hashchange",l),s}return r={pushState:i,replaceState:p,originalPushState:n,originalReplaceState:a,publishers:d,lastPublishedFingerprint:null},r}function z(t){let e=r;if(e===null||(e.publishers.delete(t),e.publishers.size>0))return;let n=globalThis.history;n.pushState===e.pushState&&(n.pushState=e.originalPushState),n.replaceState===e.replaceState&&(n.replaceState=e.originalReplaceState),globalThis.removeEventListener("popstate",l),globalThis.removeEventListener("hashchange",l),r=null}function L({embedding:t,disposeSignal:e}){if(e.aborted)return;let n=t.getClaim(P),a=({search:i,fragment:p})=>{let s=n.getSnapshot();s.status==="ready"&&s.fields.setDeepLinkState({search:i,fragment:p}).catch(c=>x("The app URL state could not be synchronized to the embedding host.",c))},d=i=>{i.status==="ready"&&I(a)&&m(!0)},o=n.subscribe(()=>{d(n.getSnapshot())});try{w(a)}catch(i){throw o(),i}d(n.getSnapshot()),e.addEventListener("abort",()=>{o(),z(a)},{once:!0})}var O=Object.freeze({});function J(){return A("datadog.deep-links",O,{install({embedding:t,disposeSignal:e}){L({embedding:t,disposeSignal:e})}})}export{F as a,J as b};
|
|
7
|
+
//# sourceMappingURL=chunk-2ZECSTB4.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/embedding/react/config.ts", "../../../src/deep-links/internal/protocol.ts", "../../../src/deep-links/react/module-install.ts", "../../../src/deep-links/react/index.ts"],
|
|
4
|
+
"sourcesContent": ["import type { AppEmbedding } from '../types';\n\nconst providerModuleImplementation: unique symbol = Symbol(\n 'DatadogAppProviderModule',\n);\n\nexport interface DatadogAppProviderModule<\n TId extends string = string,\n TConfig extends Readonly<Record<string, unknown>> = Readonly<\n Record<string, unknown>\n >,\n> {\n readonly id: TId;\n /** This module's readonly settings, as passed to its factory. */\n readonly config: TConfig;\n readonly [providerModuleImplementation]: DatadogAppProviderModuleImplementation;\n}\n\n/**\n * Everything a module receives when the provider installs it on a mount.\n *\n * Deliberately neutral plumbing, made only of things the provider already\n * owns: the shared embedding connection and this mount's dispose signal. The\n * core knows nothing else about modules -- no module-specific fields, and no\n * DOM knowledge at all.\n */\nexport interface DatadogAppProviderModuleHandle {\n /**\n * The embedding connection shared by every mount of this package. A\n * module claims its contracts and subscribes to claim stores from here.\n */\n readonly embedding: AppEmbedding;\n /**\n * Aborted when this mount unmounts, or when React re-runs the provider's\n * effects (StrictMode double-invokes them in development). Modules clean\n * up by listening for this signal.\n */\n readonly disposeSignal: AbortSignal;\n}\n\nexport interface DatadogAppProviderModuleImplementation {\n /**\n * Installs this module's capability for one provider mount.\n *\n * Synchronous: `install` returns once the module's synchronous setup is\n * done. A module owns any async work it starts and must end it when\n * `disposeSignal` aborts.\n *\n * Re-runnable: `install -> dispose -> install` on the same mount is legal\n * and does happen (StrictMode), so a module's install must work again\n * after its dispose path has run.\n */\n install(handle: DatadogAppProviderModuleHandle): undefined;\n}\n\n/** Creates one opaque, configured provider module for package capabilities. */\nexport function createDatadogAppProviderModule<\n const TId extends string,\n const TConfig extends Readonly<Record<string, unknown>>,\n>(\n id: TId,\n config: TConfig,\n implementation: DatadogAppProviderModuleImplementation,\n): DatadogAppProviderModule<TId, TConfig> {\n if (id.length === 0) {\n throw new Error('A Datadog App provider module requires an id.');\n }\n return Object.freeze({\n id,\n config: Object.freeze({ ...config }) as TConfig,\n [providerModuleImplementation]: implementation,\n });\n}\n\n/** Reports an isolated install failure. Guarded like the composite's warn():\n * a hostile console implementation must never break the isolation promise. */\nfunction reportInstallFailure(moduleId: string, error: unknown): void {\n try {\n console.error(\n `Installing the \"${moduleId}\" Datadog App provider module failed; the remaining modules and the app still run.`,\n error,\n );\n } catch {\n // Nothing more can be done here; the remaining modules still install.\n }\n}\n\n/**\n * Installs modules on one provider mount, in list order, and nothing more.\n *\n * Duplicate ids are a wiring bug, not a runtime condition: they throw before\n * anything is installed. Individual install failures are the opposite -- they\n * are isolated and reported, and the remaining modules still install. That\n * asymmetry is deliberate: duplicates mean the author wired the same\n * capability twice and must hear about it immediately, while a failing\n * default module must not take down the app or its sibling modules.\n */\nexport function installDatadogAppProviderModules(\n modules: readonly DatadogAppProviderModule[],\n embedding: AppEmbedding,\n disposeSignal: AbortSignal,\n): void {\n const moduleIds = new Set<string>();\n for (const module of modules) {\n if (moduleIds.has(module.id)) {\n throw new Error(\n `DatadogAppProvider received duplicate module \"${module.id}\".`,\n );\n }\n moduleIds.add(module.id);\n }\n const handle: DatadogAppProviderModuleHandle = Object.freeze({\n embedding,\n disposeSignal,\n });\n for (const module of modules) {\n try {\n module[providerModuleImplementation].install(handle);\n } catch (error: unknown) {\n reportInstallFailure(module.id, error);\n }\n }\n}\n", "import * as z from 'zod/mini';\n\nimport { defineContract, fn } from '../../embedding/contract';\nimport type {\n Contract,\n FunctionField,\n ValueSchema,\n} from '../../embedding/types';\n\nconst stringSchema: ValueSchema<string> = z.string();\nconst undefinedSchema: ValueSchema<undefined> = z.undefined();\n\n/**\n * A one-way mirror of the embedded app's query string and fragment. The host\n * stores the snapshot under `app-links-${id}` and seeds the iframe's starting\n * URL before first navigation. There is no host-to-app value field or ongoing\n * inbound synchronization.\n *\n * V2 carries `location.search` verbatim rather than a dictionary, preserving\n * repeated parameters, ordering, empty values, and encoding.\n */\nexport const datadogAppDeepLinksContract: Contract<{\n setDeepLinkState: FunctionField<\n Readonly<{\n search: ValueSchema<string>;\n fragment: ValueSchema<string>;\n }>,\n ValueSchema<undefined>\n >;\n}> = defineContract({\n identifier: 'datadog.deep-links',\n version: 2,\n fields: {\n setDeepLinkState: fn.readOnly({\n inputs: {\n search: stringSchema,\n fragment: stringSchema,\n },\n result: undefinedSchema,\n }),\n },\n});\n\nconst variablesSchema: ValueSchema<Readonly<Record<string, string>>> = z.record(\n z.string(),\n z.string(),\n);\n\n/** Retained for apps built with the original scalar-query guest runtime. */\nexport const datadogAppDeepLinksV1Contract: Contract<{\n setDeepLinkVariables: FunctionField<\n Readonly<{\n variables: ValueSchema<Readonly<Record<string, string>>>;\n fragment: ValueSchema<string>;\n }>,\n ValueSchema<undefined>\n >;\n}> = defineContract({\n identifier: 'datadog.deep-links',\n version: 1,\n fields: {\n setDeepLinkVariables: fn.readOnly({\n inputs: {\n variables: variablesSchema,\n fragment: stringSchema,\n },\n result: undefinedSchema,\n }),\n },\n});\n", "import type { AppEmbedding, ClaimState } from '../../embedding/types';\nimport { datadogAppDeepLinksContract } from '../internal/protocol';\n\ninterface AppLocationState {\n readonly search: string;\n readonly fragment: string;\n}\n\nconst EMPTY_LOCATION_STATE: AppLocationState = Object.freeze({\n search: '',\n fragment: '',\n});\n\n/**\n * There is no ambient `location` outside a browser (or this guest's iframe\n * realm), so reading it unconditionally would throw. Install only ever runs\n * from a provider effect in a browser, but a non-browser embedding\n * implementation is not forbidden from calling in, so the read stays guarded.\n */\nfunction currentLocationState(): AppLocationState {\n if (typeof globalThis.location === 'undefined') {\n return EMPTY_LOCATION_STATE;\n }\n return Object.freeze({\n search: globalThis.location.search,\n fragment: globalThis.location.hash,\n });\n}\n\nfunction reportDeepLinksError(message: string, error?: unknown): void {\n console.error(`[datadog-apps:deep-links] ${message}`, error ?? '');\n}\n\ntype Publish = (state: AppLocationState) => void;\n\n/**\n * Ref-counted, per-realm history patch. Sibling provider mounts share one\n * embedding connection but each installs this runtime; without coordination,\n * two patches would publish twice and an out-of-order unmount could restore\n * a stale method. One patch is installed on the first install and torn down\n * on the last dispose; every live install's publisher is kept in an ordered\n * set, so a navigation uses the first live claim and disposing that claim\n * falls back to the next remaining one rather than going silent.\n */\ninterface PatchState {\n readonly pushState: History['pushState'];\n readonly replaceState: History['replaceState'];\n readonly originalPushState: History['pushState'];\n readonly originalReplaceState: History['replaceState'];\n /** Live publishers in install order; the first is the active publisher. */\n readonly publishers: Set<Publish>;\n lastPublishedFingerprint: string | null;\n}\nlet patchState: PatchState | null = null;\n\n/**\n * One stable handler, registered once, that publishes through one claim.\n * Fragment-changing history traversal can emit both `popstate` and\n * `hashchange`; the shared location fingerprint suppresses the second event.\n */\nfunction onLocationChange(): void {\n publishCurrentLocation();\n}\n\nfunction locationStateFingerprint({\n search,\n fragment,\n}: AppLocationState): string {\n return JSON.stringify([search, fragment]);\n}\n\nfunction publishCurrentLocation(force = false): void {\n const state = patchState;\n if (state === null) {\n return;\n }\n const locationState = currentLocationState();\n const fingerprint = locationStateFingerprint(locationState);\n if (!force && state.lastPublishedFingerprint === fingerprint) {\n return;\n }\n state.lastPublishedFingerprint = fingerprint;\n publishToActivePublisher(locationState);\n}\n\n/**\n * Publish to the first live publisher only. Sibling provider mounts share\n * one embedding connection and therefore one claim store, so every live\n * publisher holds the same callable -- invoking more than one would publish\n * the same navigation twice. Deleting the active publisher (on its dispose)\n * lets `Set` iteration fall back to the next remaining one, so a navigation\n * is never dropped and never duplicated.\n */\nfunction publishToActivePublisher(state: AppLocationState): void {\n const publishers = patchState?.publishers;\n if (publishers === undefined) {\n return;\n }\n const next = publishers.values().next();\n if (next.done === false) {\n (next.value as Publish)(state);\n }\n}\n\n/**\n * True when `publish` is the active (first) live publisher. Used to gate the\n * per-install ready publication so a startup publication goes out once across\n * siblings, not once per sibling -- the same single-publisher rule the\n * singleton applies to navigation.\n */\nfunction isActivePublisher(publish: Publish): boolean {\n const publishers = patchState?.publishers;\n if (publishers === undefined) {\n return false;\n }\n const next = publishers.values().next();\n return next.done === false && next.value === publish;\n}\n\nfunction acquireHistoryPatch(publish: Publish): PatchState {\n if (patchState !== null) {\n patchState.publishers.add(publish);\n return patchState;\n }\n const history = globalThis.history;\n const originalPushState = history.pushState;\n const originalReplaceState = history.replaceState;\n const publishers = new Set<Publish>([publish]);\n const publishLocalState = (): void => {\n publishCurrentLocation();\n };\n const patchedPushState: History['pushState'] = function (\n data,\n unused,\n url,\n ): void {\n originalPushState.call(history, data, unused, url);\n publishLocalState();\n };\n const patchedReplaceState: History['replaceState'] = function (\n data,\n unused,\n url,\n ): void {\n originalReplaceState.call(history, data, unused, url);\n publishLocalState();\n };\n try {\n history.pushState = patchedPushState;\n history.replaceState = patchedReplaceState;\n globalThis.addEventListener('popstate', onLocationChange);\n globalThis.addEventListener('hashchange', onLocationChange);\n } catch (error) {\n // Acquisition is all-or-nothing. If a hardened realm rejects one of\n // the method assignments after the other succeeded, restore whatever\n // this attempt installed before surfacing the failure.\n if (history.replaceState === patchedReplaceState) {\n history.replaceState = originalReplaceState;\n }\n if (history.pushState === patchedPushState) {\n history.pushState = originalPushState;\n }\n globalThis.removeEventListener('popstate', onLocationChange);\n globalThis.removeEventListener('hashchange', onLocationChange);\n throw error;\n }\n patchState = {\n pushState: patchedPushState,\n replaceState: patchedReplaceState,\n originalPushState,\n originalReplaceState,\n publishers,\n lastPublishedFingerprint: null,\n };\n return patchState;\n}\n\nfunction releaseHistoryPatch(publish: Publish): void {\n const state = patchState;\n if (state === null) {\n return;\n }\n state.publishers.delete(publish);\n if (state.publishers.size > 0) {\n return;\n }\n const history = globalThis.history;\n // Restore only our own still-installed methods: an out-of-order dispose\n // of a sibling that patched later would have overwritten these, and\n // blindly restoring the originals would drop that sibling's patch. The\n // identity check guarantees we only undo our own installation.\n if (history.pushState === state.pushState) {\n history.pushState = state.originalPushState;\n }\n if (history.replaceState === state.replaceState) {\n history.replaceState = state.originalReplaceState;\n }\n globalThis.removeEventListener('popstate', onLocationChange);\n globalThis.removeEventListener('hashchange', onLocationChange);\n patchState = null;\n}\n\nexport interface InstallDatadogAppDeepLinksOptions {\n /** The embedding connection shared by every mount of this package. */\n readonly embedding: AppEmbedding;\n /** Aborted when this mount disposes; all cleanup keys off it. */\n readonly disposeSignal: AbortSignal;\n}\n\n/**\n * Installs the deep-links guest runtime for one provider mount.\n *\n * A one-way mirror the app drives onto the host page URL. The app owns its\n * query string and fragment; this runtime watches them -- patching `history`\n * once per realm and listening for `popstate` and `hashchange` -- and, whenever\n * they change, calls the host's `setDeepLinkState` with the current\n * snapshot. On each transition of the deep-links claim to `ready`, including\n * after an embedding reconnect, it publishes the current snapshot immediately.\n * The host's outer URL therefore reflects the app's state even before the app\n * navigates. There is no inbound apply and no remembered baseline: the host\n * seeded the iframe's starting URL before first navigation, and after that the\n * app's URL is its own state -- this runtime only reports it outward.\n *\n * When the claim is not `ready` (no host-side deep-links counterpart, or the\n * handshake still in flight) publishing is a no-op, so a default install is\n * inert rather than broken. Re-runnable: `install -> dispose -> install` on\n * the same mount is legal (StrictMode double-invokes provider effects), so\n * the patch acquisition, claim subscription, and abort listener all clean up\n * on `disposeSignal` and tolerate a second install.\n */\nexport function installDatadogAppDeepLinks({\n embedding,\n disposeSignal,\n}: InstallDatadogAppDeepLinksOptions): void {\n if (disposeSignal.aborted) {\n return;\n }\n\n const store = embedding.getClaim(datadogAppDeepLinksContract);\n\n const publish: Publish = ({ search, fragment }) => {\n const claim = store.getSnapshot();\n if (claim.status !== 'ready') {\n return;\n }\n claim.fields\n .setDeepLinkState({ search, fragment })\n .catch((error: unknown) =>\n reportDeepLinksError(\n 'The app URL state could not be synchronized to the embedding host.',\n error,\n ),\n );\n };\n\n // Publish the current snapshot on each transition of the claim to\n // `ready`. A reconnect produces a fresh claim (new callable), so\n // publishing per-ready (rather than once per install) keeps the host in\n // sync after a reconnect and reconciles the one-shot overlay with the\n // app's effective URL even when it never navigates. An unseeded app also\n // publishes any authored params so the outer URL gains a shareable link.\n const publishIfReady = (\n claim: ClaimState<typeof datadogAppDeepLinksContract>,\n ): void => {\n if (claim.status === 'ready' && isActivePublisher(publish)) {\n // Force each ready transition through even when its URL state is\n // unchanged: a reconnect supplies a fresh host callable that has\n // not received the current snapshot yet.\n publishCurrentLocation(true);\n }\n };\n const unsubscribe = store.subscribe(() => {\n publishIfReady(store.getSnapshot());\n });\n\n try {\n acquireHistoryPatch(publish);\n } catch (error) {\n unsubscribe();\n throw error;\n }\n\n // The claim may already be `ready` when this install runs (a sibling\n // mount claimed the same contract, or a reconnect raced the install\n // effect), so check once up front in addition to listening for changes.\n publishIfReady(store.getSnapshot());\n\n disposeSignal.addEventListener(\n 'abort',\n () => {\n unsubscribe();\n releaseHistoryPatch(publish);\n },\n { once: true },\n );\n}\n", "/**\n * The npm-facing React entry point for deep links. The provider module is a\n * startup capability: the provider installs it by id and knows nothing about\n * what it does. Nothing is rendered on the module's behalf -- the guest\n * runtime is framework-neutral install code over the shared embedding\n * connection.\n */\nimport { createDatadogAppProviderModule } from '../../embedding/react/config';\nimport type {\n DatadogAppProviderModule,\n DatadogAppProviderModuleHandle,\n} from '../../embedding/react/config';\n\nimport { installDatadogAppDeepLinks } from './module-install';\n\n/** Deep links take no module configuration today. */\nexport type DatadogAppDeepLinksConfig = Readonly<Record<string, never>>;\n\nexport type DatadogAppDeepLinksProviderModule = DatadogAppProviderModule<\n 'datadog.deep-links',\n DatadogAppDeepLinksConfig\n>;\n\nconst EMPTY_DEEP_LINKS_CONFIG: DatadogAppDeepLinksConfig = Object.freeze({});\n\n/**\n * Starts deep links with the provider. Installing this module mirrors the\n * app's query and fragment state onto the embedding host's page URL (under\n * the host's opaque id), so an app's navigations become shareable links. App\n * authors pass it through the composite provider's `modules` list (or get it\n * as a default); with no host-side deep-links counterpart the claim stays\n * pending and the module is inert.\n */\nexport function datadogAppDeepLinks(): DatadogAppDeepLinksProviderModule {\n return createDatadogAppProviderModule(\n 'datadog.deep-links',\n EMPTY_DEEP_LINKS_CONFIG,\n {\n install({\n embedding,\n disposeSignal,\n }: DatadogAppProviderModuleHandle): undefined {\n installDatadogAppDeepLinks({ embedding, disposeSignal });\n },\n },\n );\n}\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
|
+
"names": ["providerModuleImplementation", "createDatadogAppProviderModule", "id", "config", "implementation", "reportInstallFailure", "moduleId", "error", "installDatadogAppProviderModules", "modules", "embedding", "disposeSignal", "moduleIds", "module", "handle", "stringSchema", "string", "undefinedSchema", "_undefined", "datadogAppDeepLinksContract", "defineContract", "fn", "variablesSchema", "record", "datadogAppDeepLinksV1Contract", "EMPTY_LOCATION_STATE", "currentLocationState", "reportDeepLinksError", "message", "error", "patchState", "onLocationChange", "publishCurrentLocation", "locationStateFingerprint", "search", "fragment", "force", "state", "locationState", "fingerprint", "publishToActivePublisher", "publishers", "next", "isActivePublisher", "publish", "acquireHistoryPatch", "history", "originalPushState", "originalReplaceState", "publishLocalState", "patchedPushState", "data", "unused", "url", "patchedReplaceState", "releaseHistoryPatch", "installDatadogAppDeepLinks", "embedding", "disposeSignal", "store", "datadogAppDeepLinksContract", "claim", "publishIfReady", "unsubscribe", "EMPTY_DEEP_LINKS_CONFIG", "datadogAppDeepLinks", "createDatadogAppProviderModule", "embedding", "disposeSignal", "installDatadogAppDeepLinks"]
|
|
7
|
+
}
|
|
@@ -3,5 +3,5 @@
|
|
|
3
3
|
* Copyright 2019-Present Datadog, Inc.
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import{a}from"../../_chunks/chunk-
|
|
6
|
+
import{b as a}from"../../_chunks/chunk-2ZECSTB4.js";import"../../_chunks/chunk-PA4Z7DNH.js";import"../../_chunks/chunk-LEEYMNMO.js";export{a as datadogAppDeepLinks};
|
|
7
7
|
//# sourceMappingURL=index.js.map
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
export { DatadogAppProvider } from './provider.js';
|
|
7
|
-
export type { DatadogAppProviderProps } from './provider.js';
|
|
7
|
+
export type { DatadogAppProviderProps, DefaultDatadogAppModuleId, } from './provider.js';
|
|
8
8
|
export type { DatadogAppProviderModule } from './config.js';
|
|
9
9
|
export { useDatadogAppEmbedding } from './use-datadog-app-embedding.js';
|
|
10
10
|
export type { UseDatadogAppEmbeddingOptions } from './use-datadog-app-embedding.js';
|
|
@@ -3,5 +3,5 @@
|
|
|
3
3
|
* Copyright 2019-Present Datadog, Inc.
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import{a as u}from"../../_chunks/chunk-VVRISDII.js";import"../../_chunks/chunk-MF7HCOXQ.js";import{a as s,b as g,d as m}from"../../_chunks/chunk-2V2HASKF.js";import"../../_chunks/chunk-LEEYMNMO.js";import{useSyncExternalStore as l}from"react";var r=new WeakMap;function c(e){return e==="connecting"||e==="reconnecting"}function E(e,t){let d=r.get(t);if(!d){let n=s(e),i;d=new Promise(b=>{i=b}),r.set(t,d);let o,a=!1,p=()=>{a||c(t.getSnapshot().state)||(a=!0,o?.(),r.delete(t),g(e,n),i())};o=t.subscribe(p),a?o():p()}throw d}function f(){throw new Error("useDatadogAppEmbedding does not support server rendering: the Datadog App embedding connection only exists in the browser.")}function A(e){throw new Error(e.state==="rejected"?`The Datadog App embedding connection was rejected: ${e.error.code}.`:"The Datadog App embedding connection closed.")}function S(e){let t=m(),d=t.getEmbeddingMetadata(),n=l(d.subscribe,d.getSnapshot,f);return e?.suspense&&(c(n.state)&&E(t,d),(n.state==="rejected"||n.state==="closed")&&A(n)),n}export{u as DatadogAppProvider,S as useDatadogAppEmbedding};
|
|
6
|
+
import{a as gn,b as Rn}from"../../_chunks/chunk-2ZECSTB4.js";import{a as vn,b as An,c as In,d as _n}from"../../_chunks/chunk-2V2HASKF.js";import"../../_chunks/chunk-PA4Z7DNH.js";import{A as b,B as k,C as w,D as ge,a as Fe,b as r,c as p,d as l,e as a,f as qe,g as En,h as Tn,i as xe,j as Cn,k as On,l as et,m as It,n as B,o as tt,p as bn,q as yn,r as _t,s as Dt,t as S,u as J,v as x,w as y,x as me,y as P,z as u}from"../../_chunks/chunk-LEEYMNMO.js";import{createElement as or,useEffect as rr,useState as ir}from"react";var go=/^https:\/\/(?:[a-zA-Z0-9-]+\.)*(?:datadoghq\.(?:com|eu)|ddog-gov\.com)$/,Eo=/^https:\/\/(?:[a-zA-Z0-9-]+\.)*(?:datad0g\.com|datad0g\.eu|staging\.dog|prod\.dog)$/,To=/^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/;function Dn(t){return go.test(t)||Eo.test(t)||To.test(t)}var Mn="dd-apps-frontend-bootstrap",Pn=1;function Oo(t,e,n){let{data:o}=n;return n.source!==t||n.ports.length!==0||!b(o)||o.namespace!==Mn||o.version!==Pn||o.type!=="accepted"&&o.type!=="rejected-origin"||o.attemptId!==e?{status:"ignored"}:Dn(n.origin)?o.type==="rejected-origin"?typeof o.origin=="string"?{status:"rejected-origin",origin:o.origin}:{status:"ignored"}:{status:"accepted"}:{status:"rejected-origin",origin:n.origin}}function wn(t,e,n,o=1e4){if(n.aborted)return Promise.resolve(u({code:"ABORTED"}));let i=t.parent;if(i===t)return Promise.resolve(u({code:"TRANSPORT_FAILED",cause:new Error("The app is not running in an iframe.")}));let s=me("bootstrap"),d=new MessageChannel;return new Promise(c=>{let h=!1,f=!1,m=!1,C,_=M=>{h||(h=!0,t.removeEventListener("message",O),n.removeEventListener("abort",D),C!==void 0&&globalThis.clearTimeout(C),M.ok||(w("failed app bootstrap port",()=>d.port1.close()),f||w("untransferred app bootstrap port",()=>d.port2.close())),c(M))},O=M=>{let T=Oo(i,s,M);T.status==="accepted"?_(P(d.port1)):T.status==="rejected-origin"&&_(u({code:"ORIGIN_REJECTED",origin:T.origin}))},D=()=>_(u({code:"ABORTED"})),H=()=>{if(!(m||h)){m=!0,C=globalThis.setTimeout(()=>_(u({code:"TIMED_OUT",timeoutMs:o})),Math.max(0,o));try{i.postMessage({namespace:Mn,version:Pn,type:"request",attemptId:s,documentId:e},"*",[d.port2]),f=!0}catch(M){_(u({code:"TRANSPORT_FAILED",cause:M}))}}};if(t.addEventListener("message",O),n.addEventListener("abort",D,{once:!0}),n.aborted){D();return}H()})}var Ln=me("document");var Nn="dd-apps-frontend-compatibility",Sn=1,bo=64;function yo(t,e,n,o){return n.aborted?Promise.resolve({ok:!1,error:{code:"ABORTED"}}):new Promise(i=>{let s=!1,d,c=m=>{s||(s=!0,t.removeEventListener("message",h),n.removeEventListener("abort",f),d!==void 0&&globalThis.clearTimeout(d),i(m))},h=m=>c({ok:!0,value:m}),f=()=>c({ok:!1,error:{code:"ABORTED"}});t.addEventListener("message",h),n.addEventListener("abort",f,{once:!0}),d=globalThis.setTimeout(()=>c({ok:!1,error:{code:"TIMED_OUT",timeoutMs:e}}),Math.max(0,e));try{t.start(),o?.()}catch(m){c({ok:!1,error:{code:"TRANSPORT_FAILED",cause:m}})}})}function kn(t){if(!(!Array.isArray(t)||t.length===0||t.length>bo||!Array.from(t).every(e=>Number.isSafeInteger(e)&&e>0)||new Set(t).size!==t.length))return[...t].sort((e,n)=>e-n)}function Ro(t,e){let n=t.filter(c=>e.includes(c));if(n.length>0)return{ok:!0,value:Math.max(...n)};let o=Math.min(...t),i=Math.max(...t),s=Math.min(...e),d=Math.max(...e);return i<s?{ok:!1,error:{code:"APP_PROTOCOL_TOO_OLD",appProtocols:t,hostProtocols:e}}:d<o?{ok:!1,error:{code:"HOST_PROTOCOL_TOO_OLD",appProtocols:t,hostProtocols:e}}:{ok:!1,error:{code:"PROTOCOL_INCOMPATIBLE",appProtocols:t,hostProtocols:e}}}async function Un(t,e,n,o){let i=kn(e);if(!i)return t.close(),{ok:!1,error:{code:"TRANSPORT_FAILED",cause:new Error("The app protocol registry is invalid.")}};let s=await yo(t,n,o,()=>{t.postMessage({namespace:Nn,version:Sn,type:"offer",role:"app",protocols:i})});if(t.close(),!s.ok)return s;let{data:d,ports:c}=s.value;if(!b(d)||d.namespace!==Nn||d.version!==Sn||d.type!=="answer"||d.role!=="host"){for(let C of c)C.close();return{ok:!1,error:{code:"TRANSPORT_FAILED",cause:new Error("The host returned an invalid compatibility answer.")}}}let h=kn(d.protocols);if(!h){for(let C of c)C.close();return{ok:!1,error:{code:"TRANSPORT_FAILED",cause:new Error("The host returned an invalid supported-protocol list.")}}}let f=Ro(i,h);if(!f.ok){for(let C of c)C.close();return f}let[m]=c;if(c.length!==1||m===void 0){for(let C of c)C.close();return{ok:!1,error:{code:"TRANSPORT_FAILED",cause:new Error("A compatible host must transfer exactly one operational port.")}}}return{ok:!0,value:{protocol:f.value,operationalPort:m}}}import{connect as ko,PortMessenger as Uo,Reply as Vo}from"penpal";var pt="dd-apps-frontend-heartbeat",ht=1,Vn=Object.freeze({intervalMs:En,timeoutMs:Tn});function rt(t){try{t.postMessage({namespace:pt,version:ht,type:"close"})}catch{}}function Fn(t,e){rt(e),globalThis.setTimeout(()=>{w("failed Penpal connection",()=>t.destroy()),w("failed operational port",()=>e.close())},xe)}var K,re,ie,nt,Q,ot,V,Mt,Pt,wt,ft,mt=class{constructor(e,n,o,i){this.port=e;this.onDead=n;this.policy=o;this.side=i;p(this,V);p(this,K);p(this,re);p(this,ie,0);p(this,nt,!1);p(this,Q,!1);p(this,ot,e=>{let n=e.data;if(!(!b(n)||n.namespace!==pt||n.version!==ht)){if(n.type==="close"){a(this,V,ft).call(this,!1);return}if(k(n.nonce)){if(n.type==="ping"){try{this.port.postMessage({namespace:pt,version:ht,type:"pong",nonce:n.nonce})}catch(o){y("could not answer a heartbeat probe",{side:this.side,cause:S(o)}),a(this,V,ft).call(this,!0)}return}n.type!=="pong"||n.nonce!==r(this,re)||(l(this,re,void 0),l(this,ie,0),r(this,K)!==void 0&&(globalThis.clearTimeout(r(this,K)),l(this,K,void 0)),a(this,V,Mt).call(this,this.policy.intervalMs))}}});this.port.addEventListener("message",r(this,ot))}port;onDead;policy;side;start(){r(this,nt)||r(this,Q)||(l(this,nt,!0),a(this,V,Mt).call(this,this.policy.intervalMs))}stop(){r(this,Q)||(l(this,Q,!0),l(this,re,void 0),r(this,K)!==void 0&&(globalThis.clearTimeout(r(this,K)),l(this,K,void 0)),this.port.removeEventListener("message",r(this,ot)))}};K=new WeakMap,re=new WeakMap,ie=new WeakMap,nt=new WeakMap,Q=new WeakMap,ot=new WeakMap,V=new WeakSet,Mt=function(e){r(this,Q)||l(this,K,globalThis.setTimeout(()=>a(this,V,Pt).call(this),Math.max(0,e)))},Pt=function(){if(r(this,Q))return;let e=me("heartbeat");l(this,re,e);try{this.port.postMessage({namespace:pt,version:ht,type:"ping",nonce:e})}catch(n){x("could not send a heartbeat probe",{side:this.side,misses:r(this,ie),cause:S(n)}),a(this,V,wt).call(this,e);return}l(this,K,globalThis.setTimeout(()=>a(this,V,wt).call(this,e),Math.max(0,this.policy.timeoutMs)))},wt=function(e){if(!(r(this,Q)||r(this,re)!==e)){if(l(this,re,void 0),l(this,ie,r(this,ie)+1),r(this,ie)>=2){y("the peer stopped answering heartbeats",{side:this.side,misses:r(this,ie),probeTimeoutMs:this.policy.timeoutMs,intervalMs:this.policy.intervalMs}),a(this,V,ft).call(this,!0);return}x("a heartbeat probe went unanswered",{side:this.side,misses:r(this,ie),probeTimeoutMs:this.policy.timeoutMs}),a(this,V,Pt).call(this)}},ft=function(e){r(this,Q)||(this.stop(),this.onDead(e))};import{Reply as vo}from"penpal";function Ao(t){return(typeof t=="object"&&t!==null||typeof t=="function")&&typeof t.then=="function"}function De(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=1}function Nt(t){return Array.isArray(t)&&t.every(De)}function Me(t){return Array.isArray(t)&&t.every(e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>0)}function Io(t){return Array.isArray(t)&&t.every(e=>typeof e=="string"||typeof e=="number"&&Number.isSafeInteger(e)&&e>=0)}function St(t){return Array.isArray(t)&&t.every(e=>b(e)&&typeof e.message=="string"&&Io(e.path))}function Pe(t,e){try{let n=t["~standard"].validate(e);return Ao(n)?(Promise.resolve(n).catch(()=>{}),u([{message:"Embedding value schemas must be synchronous.",path:[]}])):n.issues?u(n.issues.map(o=>({message:o.message,path:_o(o.path)}))):P(n.value)}catch(n){return u([{message:n instanceof Error?n.message:"The value parser rejected this value.",path:[]}])}}function _o(t){return t?t.map(e=>{let n=typeof e=="object"&&e!==null&&"key"in e?e.key:e;return typeof n=="string"||typeof n=="number"&&Number.isSafeInteger(n)&&n>=0?n:String(n)}):[]}function it(t,e=[],n=new Set){try{globalThis.structuredClone(t);return}catch{if(typeof t!="object"&&typeof t!="function"||t===null||n.has(t))return e;n.add(t);let o;try{o=Object.entries(t)}catch{return e}for(let[i,s]of o){let d=it(s,[...e,Array.isArray(t)?Number(i):i],n);if(d)return d}return e}}function He(t,e){return e.map(n=>({message:n.message,path:[t,...n.path]}))}function gt(t){return Object.entries(t.fields).filter(([,e])=>e.kind==="value").map(([e])=>e)}function xn(t,e,n){let o=new Set(t);if(n){let s=[...o].find(d=>!Object.prototype.hasOwnProperty.call(e,d));if(s!==void 0)return{field:s,kind:"missing"}}let i=Object.keys(e).find(s=>!o.has(s));return i===void 0?void 0:{field:i,kind:"unknown"}}function Hn(t){return{code:"INVALID_RESULT",issues:[{message:t.kind==="missing"?"The host value snapshot omitted a claimed field.":"The host value snapshot included an unclaimed field.",path:[t.field]}]}}function Et(t,e){let n=xn(t,e,!0);return n&&Hn(n)}function kt(t,e){let n=xn(t,e,!1);return n&&Hn(n)}function Ut(t,e,n){let o;try{o=n.get()}catch(s){return y("a host value provider threw while being read",{side:"host",field:t,cause:S(s)}),u([{message:"The host value provider threw while being read.",path:[t]}])}let i=Pe(e,o);if(!i.ok)return u(He(t,i.error));try{return P(globalThis.structuredClone(i.value))}catch{let s=it(i.value)??[];return u([{message:"The host value is not structured-clone-safe.",path:[t,...s]}])}}function Tt(t,e,n){return y("a host value could not be provided",{side:"host",target:`${t}.${e}`,details:S(n)}),[{message:"The host could not provide a value that satisfies this field schema.",path:[e]}]}function Vt(t,e,n){if(!b(n))return u([{message:"Expected a named inputs object.",path:[t,"inputs"]}]);let o=Object.keys(n).find(s=>!Object.hasOwn(e.inputs,s));if(o!==void 0)return u([{message:`Unknown function input "${o}".`,path:[t,"inputs",o]}]);let i=Object.create(null);for(let[s,d]of Object.entries(e.inputs)){let c=Pe(d,Object.hasOwn(n,s)?n[s]:void 0);if(!c.ok)return u(c.error.map(h=>({message:h.message,path:[t,"inputs",s,...h.path]})));i[s]=c.value}try{return P(globalThis.structuredClone(i))}catch{let s=it(i)??[];return u([{message:"The function inputs are not structured-clone-safe.",path:[t,"inputs",...s]}])}}function jn(t){if(typeof t!="object"||t===null||typeof globalThis.MessagePort!="function")return!1;if(t instanceof globalThis.MessagePort)return!0;let e=globalThis.MessagePort.prototype;for(;e;){let n=Object.getOwnPropertyDescriptor(e,"onmessage")?.get;if(n)try{return n.call(t),!0}catch{return!1}e=Object.getPrototypeOf(e)}return!1}var Bn=Object.freeze({"~standard":{version:1,vendor:"@datadog/apps-frontend",validate(t){return jn(t)?{value:t}:{issues:[{message:"Expected a MessagePort."}]}}}});function st(t){jn(t)&&w("discarded function result MessagePort",()=>t.close())}function Lt(t,e=[]){return u([{message:"The function result is not structured-clone-safe.",path:[t,...e]}])}function zn(t,e,n){let o=Pe(e.result,n);if(!o.ok)return u(He(t,o.error));if(e.result===Bn){let i=o.value;try{let s=globalThis.structuredClone(i,{transfer:[i]});return P(new vo(P(s),{transferables:[s]}))}catch{return Lt(t)}}try{return P(P(globalThis.structuredClone(o.value)))}catch{let i=it(o.value)??[];return Lt(t,i)}}function Wn(t,e,n){let o=Pe(e.result,n);if(!o.ok)return u(He(t,o.error));if(e.result===Bn)return P(o.value);try{return P(globalThis.structuredClone(o.value))}catch{let i=it(o.value)??[];return Lt(t,i)}}import{ErrorCode as Do,PenpalError as Mo}from"penpal";function Po(t){let e=t.wanted,n=t.hostVersions;return De(e)&&Nt(n)&&!n.includes(e)&&n.some(o=>o>e)}function wo(t){let e=t.wanted,n=t.hostVersions;return De(e)&&Nt(n)&&!n.includes(e)&&n.every(o=>o<e)}var $n={ORIGIN_REJECTED:t=>typeof t.origin=="string",APP_PROTOCOL_TOO_OLD:t=>Me(t.appProtocols)&&Me(t.hostProtocols),HOST_PROTOCOL_TOO_OLD:t=>Me(t.appProtocols)&&Me(t.hostProtocols),PROTOCOL_INCOMPATIBLE:t=>Me(t.appProtocols)&&Me(t.hostProtocols),PEER_LACKS_MODULE:t=>typeof t.identifier=="string",APP_MAJOR_TOO_OLD:Po,HOST_MAJOR_TOO_OLD:wo,CONTRACT_INCOMPATIBLE:t=>typeof t.field=="string",INVALID_ARGUMENT:t=>St(t.issues),FUNCTION_FAILED:t=>typeof t.field=="string",INVALID_RESULT:t=>St(t.issues),TIMED_OUT:t=>typeof t.timeoutMs=="number"&&Number.isFinite(t.timeoutMs)&&t.timeoutMs>=0,TRANSPORT_FAILED:()=>!0,ABORTED:()=>!0,DISCONNECTED:()=>!0,UNRECOGNIZED:t=>typeof t.rawCode=="string"&&t.rawCode.length>0},Lo={ORIGIN_REJECTED:["origin"],APP_PROTOCOL_TOO_OLD:["appProtocols","hostProtocols"],HOST_PROTOCOL_TOO_OLD:["appProtocols","hostProtocols"],PROTOCOL_INCOMPATIBLE:["appProtocols","hostProtocols"],PEER_LACKS_MODULE:["identifier"],APP_MAJOR_TOO_OLD:["wanted","hostVersions"],HOST_MAJOR_TOO_OLD:["wanted","hostVersions"],CONTRACT_INCOMPATIBLE:["field"],INVALID_ARGUMENT:["issues"],FUNCTION_FAILED:["field"],INVALID_RESULT:["issues"],TIMED_OUT:["timeoutMs"],TRANSPORT_FAILED:[],ABORTED:[],DISCONNECTED:[],UNRECOGNIZED:["rawCode","raw"]};function Ct(t,e){if(b(t)&&typeof t.code=="string"){let n=t.code;if(e.includes(n)&&Object.prototype.hasOwnProperty.call($n,n)){let o=$n[n];if(o(t)){if(n==="UNRECOGNIZED")return{code:n,rawCode:t.rawCode,raw:void 0};let i={code:n};for(let s of Lo[n])i[s]=t[s];return i}}}return{code:"UNRECOGNIZED",rawCode:b(t)&&typeof t.code=="string"?t.code:"MALFORMED_ERROR",raw:void 0}}function Ee(t,e,n){let o=`${t.identifier}.${e}`,i=n.code==="UNRECOGNIZED"?"UNKNOWN":n.code,s;switch(n.code){case"INVALID_ARGUMENT":s=`The inputs passed to "${o}" are invalid: ${n.issues[0]?.message??"the schema rejected them"}.`;break;case"INVALID_RESULT":s=`Datadog returned an invalid result from "${o}": ${n.issues[0]?.message??"the schema rejected it"}. The app and host may be using incompatible schema implementations.`;break;case"FUNCTION_FAILED":s=`Datadog could not complete "${o}". Screenshot this message and contact support if the problem continues.`;break;case"TIMED_OUT":s=`"${o}" did not finish within ${n.timeoutMs} ms. It may still complete in Datadog; do not automatically retry an action that is not idempotent.`;break;case"CONTRACT_INCOMPATIBLE":s=`The Datadog host contract for "${o}" does not match the schema compiled into this app. Update the app or contact support.`;break;case"ABORTED":s=`The inputs used by "${o}" were released before it completed. Its outcome is unknown; wait for the inputs to become ready before calling it again.`;break;case"DISCONNECTED":s=`The Datadog connection closed before "${o}" completed. Its outcome is unknown; reconnect before trying again.`;break;case"UNRECOGNIZED":s=`Datadog returned an unrecognized failure for "${o}" (${n.rawCode}). Screenshot this message and contact support.`;break;default:s=n}let d=new Error(`DATADOG_APP_INPUT_FUNCTION_${i}: ${s}`,{cause:n});return d.name="DatadogAppInputFunctionError",y("a Datadog host function call failed",{side:"app",target:o,error:J(n)}),Object.assign(d,{code:i})}function Gn(t,e){return b(t)&&t.code==="ABORTED"?{code:"ABORTED"}:b(t)&&t.code==="TIMED_OUT"?{code:"TIMED_OUT",timeoutMs:e}:b(t)&&t.code==="DISCONNECTED"?{code:"DISCONNECTED"}:t instanceof Mo&&t.code===Do.ConnectionTimeout?{code:"TIMED_OUT",timeoutMs:e}:{code:"TRANSPORT_FAILED",cause:t}}function Jn(t){if(!b(t))return{code:"INVALID_RESULT",issues:[{message:"Malformed __ddClaim envelope: expected an object.",path:[]}]};if(!k(t.claimId,B))return{code:"INVALID_RESULT",issues:[{message:`"claimId" must contain between 1 and ${B} characters.`,path:["claimId"]}]};if(!k(t.identifier))return{code:"INVALID_RESULT",issues:[{message:'"identifier" must be a non-empty string.',path:["identifier"]}]};if(!De(t.version))return{code:"INVALID_RESULT",issues:[{message:'"version" must be a positive integer.',path:["version"]}]};if(!Array.isArray(t.fields)||t.fields.length===0||t.fields.length>_t)return{code:"INVALID_RESULT",issues:[{message:`"fields" must contain between 1 and ${_t} entries.`,path:["fields"]}]};if(!t.fields.every(e=>typeof e=="string"&&e.length>0&&e.length<=Dt)||new Set(t.fields).size!==t.fields.length)return{code:"INVALID_RESULT",issues:[{message:`"fields" must contain unique non-empty strings of at most ${Dt} characters.`,path:["fields"]}]}}function Kn(t){if(!b(t))return{code:"INVALID_ARGUMENT",issues:[{message:"Malformed __ddCall envelope: expected an object.",path:[]}]};if(!k(t.claimId,B))return{code:"INVALID_ARGUMENT",issues:[{message:`"claimId" must contain between 1 and ${B} characters.`,path:["claimId"]}]};if(!k(t.callId,tt))return{code:"INVALID_ARGUMENT",issues:[{message:`"callId" must contain between 1 and ${tt} characters.`,path:["callId"]}]};if(!k(t.field))return{code:"INVALID_ARGUMENT",issues:[{message:'"field" must be a non-empty string.',path:["field"]}]};if(!b(t.inputs))return{code:"INVALID_ARGUMENT",issues:[{message:'"inputs" must be an object.',path:["inputs"]}]}}function Ft(t,e){let n=e.map(({version:s})=>s).sort((s,d)=>s-d),o=n[n.length-1];if(o===void 0)return u({code:"HOST_MAJOR_TOO_OLD",wanted:t,hostVersions:n});let i=e.find(({version:s})=>s===t);return i?P(i):u(t<o?{code:"APP_MAJOR_TOO_OLD",wanted:t,hostVersions:n}:{code:"HOST_MAJOR_TOO_OLD",wanted:t,hostVersions:n})}function Zn(t,e){let n=e.filter(({identifier:i})=>i===t.identifier);if(n.length===0)return{code:"PEER_LACKS_MODULE",identifier:t.identifier};let o=Ft(t.version,n);return o.ok?void 0:o.error}var Le,Ht=class{constructor(e){this.value=e;p(this,Le,new Set)}value;get(){return this.value}subscribe(e){return r(this,Le).add(e),()=>{r(this,Le).delete(e)}}set(e){return Object.is(this.value,e)?!1:(this.value=e,!0)}notify(){ge(r(this,Le))}freeze(){r(this,Le).clear()}};Le=new WeakMap;var xt=0;function Xn(t){let e=t.timeoutMs;return typeof e=="number"&&Number.isFinite(e)&&e>0&&e<=2147483647?e:6e5}var at,F,se,Te,Ce,Z,q,Oe,Be,ze,dt,I,jt,we,Ot,je,Bt,bt=class{constructor(e,n,o,i,s,d){this.role=e;this.remote=n;this.penpal=o;this.port=i;this.modules=s;this.operationTimeoutMs=d;p(this,I);p(this,at,new AbortController);p(this,F,new Map);p(this,se,new Map);p(this,Te,new Map);p(this,Ce,new Map);p(this,Z,new Map);p(this,q,new Map);p(this,Oe,new Set);p(this,Be);p(this,ze,!1);p(this,dt,!1)}role;remote;penpal;port;modules;operationTimeoutMs;get closed(){return r(this,ze)}get closeSignal(){return r(this,at).signal}attachHeartbeat(e){if(this.closed){e.stop();return}l(this,Be,e),e.start()}send(e,n){if(this.closed)return;let o;try{o=n()}catch(d){y("an outbound embedding message could not be sent",{side:this.role,operation:e,cause:S(d)}),this.noteDisconnected();return}let i=globalThis.setTimeout(()=>{r(this,Oe).delete(i),y("an outbound embedding message was never acknowledged; closing the connection",{side:this.role,operation:e,timeoutMs:this.operationTimeoutMs}),this.close()},Math.max(0,this.operationTimeoutMs));r(this,Oe).add(i);let s=(d,c)=>{r(this,Oe).delete(i)&&(globalThis.clearTimeout(i),d&&(y("an outbound embedding message was rejected",{side:this.role,operation:e,cause:S(c)}),this.noteDisconnected()))};o.then(()=>s(!1),d=>s(!0,d))}noteDisconnected(e=!1){this.close(e)}close(e=!0){if(r(this,ze))return;l(this,ze,!0);let n;if(e){rt(this.port);try{n=this.remote.__ddClose()}catch{}}r(this,Be)?.stop(),l(this,Be,void 0);for(let o of r(this,Oe))globalThis.clearTimeout(o);r(this,Oe).clear(),r(this,at).abort();for(let o of[...r(this,F).keys()])this.receiveRelease(o);for(let[o,i]of[...r(this,Te).entries()])a(this,I,je).call(this,o,i,{code:"DISCONNECTED"},!1);if(r(this,Ce).clear(),r(this,Z).clear(),r(this,q).clear(),!e){a(this,I,jt).call(this);return}n?.catch(()=>{}),globalThis.setTimeout(()=>a(this,I,jt).call(this),xe)}async settleRemoteResult(e,n){return this.closed?(e.then(o=>{n.onDiscardedResult?.(o)},()=>{}),u(n.disconnectedError)):new Promise(o=>{let i=!1,s,d=f=>{i||(i=!0,s!==void 0&&globalThis.clearTimeout(s),n.signal?.removeEventListener("abort",c),this.closeSignal.removeEventListener("abort",h),o(f))},c=()=>{n.onCancel(),d(u(n.abortError))},h=()=>d(u(n.disconnectedError));if(n.signal?.addEventListener("abort",c,{once:!0}),this.closeSignal.addEventListener("abort",h,{once:!0}),n.signal?.aborted){c();return}if(this.closeSignal.aborted){h();return}s=globalThis.setTimeout(()=>{n.onCancel(),d(u(n.timeoutError(n.timeoutMs)))},Math.max(0,n.timeoutMs)),e.then(f=>{if(i){n.onDiscardedResult?.(f);return}if(b(f)&&f.ok===!0){d(P(f.value));return}n.onDiscardedResult?.(f),d(u(n.normalize(b(f)?f.error:f)))},()=>{this.noteDisconnected(),d(u(n.disconnectedError))})})}async claim(e,n={}){if(this.closed)return u({code:"DISCONNECTED"});if(n.signal?.aborted)return u({code:"ABORTED"});let o=n.timeoutMs??5e3;qe("ClaimOptions.timeoutMs",o);let i=me("claim");r(this,Ce).set(i,e);let s;try{s=this.remote.__ddClaim({claimId:i,identifier:e.identifier,version:e.version,fields:Object.keys(e.fields)})}catch(O){return y("a claim could not be sent to the Datadog host",{side:this.role,claimId:i,identifier:e.identifier,version:e.version,cause:S(O)}),a(this,I,we).call(this,i),this.noteDisconnected(),u({code:"DISCONNECTED"})}s=s.then(O=>O,()=>(this.noteDisconnected(),u({code:"DISCONNECTED"})));let d=await this.settleRemoteResult(s,{timeoutMs:o,signal:n.signal,onCancel:()=>{this.send("__ddRelease",()=>this.remote.__ddRelease(i))},timeoutError:O=>({code:"TIMED_OUT",timeoutMs:O}),abortError:{code:"ABORTED"},disconnectedError:{code:"DISCONNECTED"},normalize:O=>Ct(O,["PEER_LACKS_MODULE","APP_MAJOR_TOO_OLD","HOST_MAJOR_TOO_OLD","CONTRACT_INCOMPATIBLE","INVALID_RESULT","TIMED_OUT","ABORTED","DISCONNECTED","UNRECOGNIZED"])});if(!d.ok)return a(this,I,we).call(this,i),d;if(!b(d.value)||!b(d.value.values))return a(this,I,we).call(this,i),this.send("__ddRelease",()=>this.remote.__ddRelease(i)),u({code:"INVALID_RESULT",issues:[{message:"Malformed claim success payload.",path:[]}]});let c=Et(gt(e),d.value.values);if(c)return a(this,I,we).call(this,i),this.send("__ddRelease",()=>this.remote.__ddRelease(i)),u(c);let h=new Map,f={},m={contract:e,values:h,valueListeners:new Set,invalidationListeners:new Set,releaseController:new AbortController,released:!1,hydrated:!1};for(let[O,D]of Object.entries(e.fields)){if(D.kind==="function"){f[O]=(...T)=>this.callFunction(i,m,O,D,T);continue}let H=Pe(D.schema,d.value.values[O]);if(!H.ok)return a(this,I,we).call(this,i),this.send("__ddRelease",()=>this.remote.__ddRelease(i)),u({code:"INVALID_RESULT",issues:He(O,H.error)});let M=new Ht(H.value);h.set(O,M),f[O]=M}r(this,Te).set(i,m);let C=r(this,Z).get(i);C&&this.receiveValues(i,C);let _=m.invalidation??r(this,q).get(i);return a(this,I,we).call(this,i),_?(a(this,I,Ot).call(this,i,m,!0,_),u(_)):P({fields:f,release:()=>a(this,I,Ot).call(this,i,m,!0),onValuesChanged:O=>m.released?()=>{}:(m.valueListeners.add(O),()=>m.valueListeners.delete(O)),onInvalidated:O=>{let D=m.invalidation;return D?(globalThis.queueMicrotask(()=>O(D)),()=>{}):m.released?()=>{}:(m.invalidationListeners.add(O),()=>m.invalidationListeners.delete(O))}})}async callFunction(e,n,o,i,s){if(this.closed)throw Ee(n.contract,o,{code:"DISCONNECTED"});if(n.released)throw Ee(n.contract,o,{code:"ABORTED"});if(s.length!==1)throw Ee(n.contract,o,{code:"INVALID_ARGUMENT",issues:[{message:`Expected one named inputs object, received ${s.length} arguments.`,path:[o,"inputs"]}]});let d=Vt(o,i,s[0]);if(!d.ok)throw Ee(n.contract,o,{code:"INVALID_ARGUMENT",issues:d.error});let c=me("call"),h;try{h=this.remote.__ddCall({claimId:e,callId:c,field:o,inputs:d.value})}catch{throw this.noteDisconnected(),Ee(n.contract,o,{code:"DISCONNECTED"})}let f=await this.settleRemoteResult(h,{timeoutMs:Xn(i),signal:n.releaseController.signal,onCancel:()=>{this.send("__ddCancel",()=>this.remote.__ddCancel({claimId:e,callId:c}))},timeoutError:C=>({code:"TIMED_OUT",timeoutMs:C}),abortError:{code:"ABORTED"},disconnectedError:{code:"DISCONNECTED"},normalize:C=>Ct(C,["CONTRACT_INCOMPATIBLE","INVALID_ARGUMENT","FUNCTION_FAILED","INVALID_RESULT","TIMED_OUT","ABORTED","DISCONNECTED","UNRECOGNIZED"]),onDiscardedResult:C=>{b(C)&&C.ok===!0&&st(C.value)}});if(!f.ok){let C=f.error.code==="INVALID_ARGUMENT"?{code:"CONTRACT_INCOMPATIBLE",field:o}:f.error;throw Ee(n.contract,o,C)}let m=Wn(o,i,f.value);if(!m.ok)throw Ee(n.contract,o,{code:"INVALID_RESULT",issues:m.error});return m.value}receiveValues(e,n){if(!k(e,B)){y("ignored a __ddValues envelope with an invalid claim id",{side:this.role,claimId:e,maxClaimIdLength:B});return}let o=r(this,Te).get(e),i=r(this,Ce).get(e);if(!b(n)){let h={code:"INVALID_RESULT",issues:[{message:"The host value snapshot must be an object.",path:[]}]};o?a(this,I,je).call(this,e,o,h,!0):i?(r(this,q).set(e,h),r(this,Z).delete(e)):y("ignored a __ddValues envelope for an unknown claim",{side:this.role,claimId:e,receivedValues:typeof n});return}if(!o){if(!i)return;let f=r(this,Z).has(e)?kt(gt(i),n):Et(gt(i),n);if(f){r(this,q).set(e,f),r(this,Z).delete(e);return}if(!r(this,q).has(e)){let m=r(this,Z).get(e);r(this,Z).set(e,Object.freeze({...m,...n}))}return}let s=o.hydrated?kt(o.values.keys(),n):Et(o.values.keys(),n);if(s){a(this,I,je).call(this,e,o,s,!0);return}o.hydrated=!0;let d=[];for(let[h,f]of Object.entries(n)){let m=o.values.get(h),C=o.contract.fields[h];if(!m||!C||C.kind!=="value")continue;let _=Pe(C.schema,f);if(!_.ok){let O={code:"INVALID_RESULT",issues:He(h,_.error)};a(this,I,je).call(this,e,o,O,!0);return}d.push([m,_.value])}let c=[];for(let[h,f]of d)h.set(f)&&c.push(h);for(let h of c)h.notify();c.length>0&&ge(o.valueListeners)}receiveInvalidation(e,n){if(!k(e,B)){y("ignored a __ddInvalidate envelope with an invalid claim id",{side:this.role,claimId:e,maxClaimIdLength:B});return}let o=Ct(n,["INVALID_RESULT","UNRECOGNIZED"]),i=r(this,Te).get(e);if(i){a(this,I,je).call(this,e,i,o,!1);return}r(this,Ce).has(e)&&r(this,q).set(e,o)}async receiveClaim(e){if(this.closed)return u({code:"DISCONNECTED"});let n=Jn(e);if(n)return u(n);if(r(this,F).has(e.claimId))return u({code:"INVALID_RESULT",issues:[{message:`Claim id "${e.claimId}" is already live.`,path:["claimId"]}]});if(r(this,F).size>=It)return u({code:"INVALID_RESULT",issues:[{message:`The peer exceeded the limit of ${It} simultaneous claims.`,path:["claimId"]}]});let o=this.modules.filter(({contract:T})=>T.identifier===e.identifier);if(o.length===0)return u({code:"PEER_LACKS_MODULE",identifier:e.identifier});let i=Ft(e.version,o.map(T=>({version:T.contract.version,module:T})));if(!i.ok)return i;let s=i.value.module;if(s.signal?.aborted)return u({code:"INVALID_RESULT",issues:[{message:`The host provider for "${e.identifier}" is disposed.`,path:[]}]});let d=new Map,c={releases:[],module:s,fields:d};if(r(this,F).set(e.claimId,c),s.signal){let T=()=>a(this,I,Bt).call(this,e.claimId,[{message:`The host provider for "${e.identifier}" was disposed.`,path:[]}]);s.signal.addEventListener("abort",T,{once:!0}),c.releases.push(()=>s.signal?.removeEventListener("abort",T))}let h={},f={ready:!1},m=!1,C=!1,_=!1,O=new Set,D=new Map,H=()=>{if(C=!1,!r(this,F).has(e.claimId))return;let T=!_;if(!T&&O.size===0)return;let A=T?[...D.keys()]:[...O];_=!0,O.clear();let U={};for(let W of A){let oe=D.get(W);if(!oe)continue;let j=Ut(W,oe.field.schema,oe.provider);if(!j.ok){a(this,I,Bt).call(this,e.claimId,Tt(e.identifier,W,j.error));return}U[W]=j.value}this.send("__ddValues",()=>this.remote.__ddValues(e.claimId,U))},M=()=>{if(r(this,F).has(e.claimId)){if(!f.ready){m=!0;return}C||(C=!0,globalThis.queueMicrotask(H))}};for(let T of e.fields){let A=s.contract.fields[T];if(!A)return this.receiveRelease(e.claimId),u({code:"CONTRACT_INCOMPATIBLE",field:T});if(d.set(T,A),A.kind==="function"){let j=Object.hasOwn(s.implementation,T)?s.implementation[T]:void 0;if(!b(j)||typeof j.invoke!="function")return this.receiveRelease(e.claimId),u({code:"INVALID_RESULT",issues:[{message:"The host implementation is not a callable function field.",path:[T]}]});continue}let U=Object.hasOwn(s.implementation,T)?s.implementation[T]:void 0;if(!U||typeof U.get!="function"||typeof U.subscribe!="function")return this.receiveRelease(e.claimId),u({code:"INVALID_RESULT",issues:[{message:"The host implementation is not a live value.",path:[T]}]});D.set(T,{field:A,provider:U});let W;try{W=U.subscribe(()=>{O.add(T),M()})}catch(j){return this.receiveRelease(e.claimId),u({code:"INVALID_RESULT",issues:Tt(e.identifier,T,j)})}if(typeof W!="function")return this.receiveRelease(e.claimId),u({code:"INVALID_RESULT",issues:[{message:"The host value provider did not return an unsubscribe function.",path:[T]}]});if(r(this,F).get(e.claimId)!==c)return w(`unsubscribe for interrupted claim ${e.claimId}`,W),this.closed?u({code:"DISCONNECTED"}):u({code:"INVALID_RESULT",issues:[{message:`The host provider for "${e.identifier}" was disposed during claim setup.`,path:[]}]});c.releases.push(W);let oe=Ut(T,A.schema,U);if(!oe.ok)return this.receiveRelease(e.claimId),u({code:"INVALID_RESULT",issues:Tt(e.identifier,T,oe.error)});h[T]=oe.value}return f.ready=!0,m&&M(),P({values:h})}async receiveFunctionCall(e){if(this.closed)return u({code:"DISCONNECTED"});let n=Kn(e);if(n)return u(n);let o=r(this,F).get(e.claimId);if(!o)return u({code:"DISCONNECTED"});let i=o.fields.get(e.field);if(!i||i.kind!=="function")return u({code:"CONTRACT_INCOMPATIBLE",field:e.field});if(r(this,se).has(e.callId))return u({code:"INVALID_ARGUMENT",issues:[{message:`Function call id "${e.callId}" is already active.`,path:["callId"]}]});if(xt>=bn)return u({code:"FUNCTION_FAILED",field:e.field});let s=Vt(e.field,i,e.inputs);if(!s.ok)return y("the host rejected the inputs of a function call",{side:this.role,claimId:e.claimId,callId:e.callId,target:`${o.module.contract.identifier}.${e.field}`,issueCount:s.error.length}),u({code:"INVALID_ARGUMENT",issues:[{message:"The function inputs do not satisfy the host schema.",path:[e.field,"inputs"]}]});let d=Object.hasOwn(o.module.implementation,e.field)?o.module.implementation[e.field]:void 0;if(!b(d)||typeof d.invoke!="function")return u({code:"CONTRACT_INCOMPATIBLE",field:e.field});let c=new AbortController,h=()=>{},f=new Promise(A=>{h=A}),m={claimId:e.claimId,controller:c,interrupt(A){c.signal.aborted||(c.abort(),h({status:"interrupted",reason:A}))}};xt+=1,r(this,se).set(e.callId,m);let C=Xn(i),_=globalThis.performance.now()+C,O=globalThis.setTimeout(()=>m.interrupt("timed-out"),C),D;try{let A=d.invoke(s.value,Object.freeze({signal:c.signal}));globalThis.performance.now()>=_&&m.interrupt("timed-out"),D=Promise.resolve(A).then(U=>globalThis.performance.now()>=_?(m.interrupt("timed-out"),st(U),{status:"interrupted",reason:"timed-out"}):{status:"returned",value:U},U=>globalThis.performance.now()>=_?(m.interrupt("timed-out"),{status:"interrupted",reason:"timed-out"}):{status:"threw",cause:U})}catch(A){globalThis.performance.now()>=_&&m.interrupt("timed-out"),D=Promise.resolve({status:"threw",cause:A})}let H=D.finally(()=>{xt-=1,r(this,se).get(e.callId)===m&&r(this,se).delete(e.callId)}),M=await Promise.race([H,f]);if(globalThis.clearTimeout(O),M.status==="interrupted")return H.then(A=>{A.status==="returned"&&st(A.value)}),M.reason==="timed-out"?u({code:"TIMED_OUT",timeoutMs:C}):u({code:"DISCONNECTED"});if(this.closed||c.signal.aborted||r(this,F).get(e.claimId)!==o)return M.status==="returned"&&st(M.value),u({code:"DISCONNECTED"});if(M.status==="threw")return y("a host function implementation threw",{side:this.role,claimId:e.claimId,callId:e.callId,target:`${o.module.contract.identifier}.${e.field}`,cause:S(M.cause)}),u({code:"FUNCTION_FAILED",field:e.field});let T=zn(e.field,i,M.value);return T.ok?T.value:(y("a host function returned an invalid result",{side:this.role,claimId:e.claimId,callId:e.callId,target:`${o.module.contract.identifier}.${e.field}`,issues:T.error}),u({code:"INVALID_RESULT",issues:[{message:"The host function returned a result that does not satisfy its schema.",path:[e.field]}]}))}receiveFunctionCancel(e){if(!b(e)||!k(e.claimId,B)||!k(e.callId,tt)){y("ignored a malformed __ddCancel envelope",{side:this.role,request:b(e)?{claimId:e.claimId,callId:e.callId}:{malformed:!0,received:typeof e}});return}let n=r(this,se).get(e.callId);n?.claimId===e.claimId&&n.interrupt("cancelled")}receiveRelease(e){if(!k(e,B)){y("ignored a __ddRelease with an invalid claim id",{side:this.role,claimId:e,maxClaimIdLength:B});return}let n=r(this,F).get(e);if(n){r(this,F).delete(e);for(let o of r(this,se).values())o.claimId===e&&o.interrupt("cancelled");for(let o of n.releases)w(`unsubscribe for claim ${e}`,o)}}};at=new WeakMap,F=new WeakMap,se=new WeakMap,Te=new WeakMap,Ce=new WeakMap,Z=new WeakMap,q=new WeakMap,Oe=new WeakMap,Be=new WeakMap,ze=new WeakMap,dt=new WeakMap,I=new WeakSet,jt=function(){r(this,dt)||(l(this,dt,!0),w("Penpal connection",()=>this.penpal.destroy()),w("operational port",()=>this.port.close()))},we=function(e){r(this,Ce).delete(e),r(this,Z).delete(e),r(this,q).delete(e)},Ot=function(e,n,o,i){if(n.released)return!1;n.released=!0,n.invalidation=i,n.releaseController.abort();for(let s of n.values.values())s.freeze();return n.valueListeners.clear(),n.invalidationListeners.clear(),r(this,Te).delete(e),o&&this.send("__ddRelease",()=>this.remote.__ddRelease(e)),!0},je=function(e,n,o,i){let s=[...n.invalidationListeners];if(!a(this,I,Ot).call(this,e,n,i,o))return;(o.code==="DISCONNECTED"?x:y)("a live claim was invalidated",{side:this.role,claimId:e,identifier:n.contract.identifier,version:n.contract.version,observedListeners:s.length,error:J(o)}),ge(s,o)},Bt=function(e,n){let o=r(this,F).get(e);o&&(y("the host invalidated a claim it was serving",{side:this.role,claimId:e,identifier:o.module.contract.identifier,version:o.module.contract.version,issues:n}),this.receiveRelease(e),this.send("__ddInvalidate",()=>this.remote.__ddInvalidate(e,{code:"INVALID_RESULT",issues:n})))};function Fo(t,e){if(!b(t))return{malformed:!0,received:typeof t};let n={};for(let o of e)n[o]=t[o];return n}var Wt=class{constructor(e,n){this.endpoint=e;this.modules=n}endpoint;modules;async claim(e,n){if(this.endpoint.closed||n?.signal?.aborted)return this.endpoint.claim(e,n);qe("ClaimOptions.timeoutMs",n?.timeoutMs??5e3);let o=Zn(e,this.modules);return o?Promise.resolve(u(o)):this.endpoint.claim(e,n)}};function xo(t){return b(t)&&t.role==="host"&&Array.isArray(t.modules)}function Ho(t){let e=new Set,n=[];for(let o of t){if(!b(o)||!k(o.identifier)||!De(o.version))continue;let i=JSON.stringify([o.identifier,o.version]);e.has(i)||(e.add(i),n.push({identifier:o.identifier,version:o.version}))}return n}async function jo(t,e,n,o,i,s,d){let c,h,f=!1,m=!1,C,_=new Promise((g,R)=>{C=R});try{h=new mt(t,g=>{c?c.noteDisconnected(g):(f=!0,g||t.close(),C?.({code:"DISCONNECTED"}))},d,e)}catch(g){return w("failed operational port",()=>t.close()),u({code:"TRANSPORT_FAILED",cause:g})}let O=!1,D=0,H=()=>{},M=new Promise(g=>{H=g}),T=g=>{O||(O=!0,H(g))},A=(g,R)=>{let N=Y=>(x("an embedding operation was refused",{side:e,operation:R,expectedRole:g,reason:Y,pendingEndpointOperations:D}),new Error(Y));return c?c.role===g?Promise.resolve(c):Promise.reject(N("The embedding operation is not valid here.")):O||D>=yn?Promise.reject(N("The embedding endpoint is not ready for work.")):(D+=1,M.then(Y=>{if(!Y||Y.role!==g)throw N("The embedding operation is not valid here.");return Y}).finally(()=>{D-=1}))},U=e==="host"?{role:"host",modules:i.map(({contract:g})=>({identifier:g.identifier,version:g.version})),surfaceId:s}:{role:"app"},W=(g,R,N,Y)=>(Y.ok||x(`${g} was rejected`,{side:e,request:Fo(R,N),error:J(Y.error)}),Y),oe={__ddDescribe:()=>U,__ddClaim:g=>A("host","__ddClaim").then(R=>R.receiveClaim(g).then(N=>W("__ddClaim",g,["claimId","identifier","version","fields"],N))),__ddRelease:g=>A("host","__ddRelease").then(R=>R.receiveRelease(g)),__ddValues:(g,R)=>A("app","__ddValues").then(N=>N.receiveValues(g,R)),__ddCall:g=>A("host","__ddCall").then(R=>R.receiveFunctionCall(g).then(N=>(W("__ddCall",g,["claimId","callId","field"],N instanceof Vo?N.value:N),N))),__ddCancel:g=>A("host","__ddCancel").then(R=>R.receiveFunctionCancel(g)),__ddInvalidate:(g,R)=>A("app","__ddInvalidate").then(N=>N.receiveInvalidation(g,R)),__ddClose:()=>(c||(m=!0),A(e,"__ddClose").then(g=>g.close(!1)))},j;try{j=ko({messenger:new Uo({port:t}),methods:oe,timeout:n})}catch(g){return h.stop(),rt(t),globalThis.setTimeout(()=>t.close(),xe),u({code:"TRANSPORT_FAILED",cause:g})}let un,pn,hn=()=>un?.({code:"ABORTED"}),fn=new Promise((g,R)=>{un=R}),mn=new Promise((g,R)=>{pn=R}),mo=globalThis.setTimeout(()=>pn?.({code:"TIMED_OUT"}),Math.max(0,n));o.addEventListener("abort",hn,{once:!0});let At="handshake";try{if(o.aborted)throw Object.assign(new Error("The connection was aborted."),{code:"ABORTED"});let g=await Promise.race([j.promise,fn,mn,_]);At="peer-description";let R=await Promise.race([g.__ddDescribe(),fn,mn,_]);if(At="validation",!(e==="app"?xo(R):b(R)&&R.role==="app"))throw new Error(`Expected an embedding ${e==="app"?"host":"app"} using the operational protocol.`);if(c=new bt(e,g,j,t,i,n),f)throw Object.assign(new Error("The transport disconnected before establishment completed."),{code:"DISCONNECTED"});if(m)throw Object.assign(new Error("The peer requested to close before establishment completed."),{code:"DISCONNECTED"});return T(c),c.attachHeartbeat(h),P({endpoint:c,description:R})}catch(g){let R=Gn(g,n);return x("the operational protocol could not be established",{side:e,stage:At,timeoutMs:n,describedPeer:!!c,error:J(R),cause:S(g)}),h.stop(),c?c.close():Fn(j,t),u(R)}finally{T(void 0),globalThis.clearTimeout(mo),o.removeEventListener("abort",hn)}}function Bo(t){let e=t.endpoint,n=t.description;return{connection:new Wt(e,Ho(n.modules)),surfaceId:typeof n.surfaceId=="string"?n.surfaceId:void 0,closeSignal:e.closeSignal,close:()=>e.close()}}async function Yn(t,e,n,o){let i=await jo(t,"app",e,n,[],void 0,o);return i.ok?P(Bo(i.value)):i}var $o=[1];async function Go(t,e,n=1e4){if(e.aborted)return t.close(),u({code:"ABORTED"});let o=await Un(t,$o,n,e);return o.ok?Yn(o.value.operationalPort,n,e,Vn):o}var We,$t=class{constructor(){p(this,We)}next(){let e=r(this,We)??Cn;return l(this,We,Math.min(e*2,On)),e}reset(){l(this,We,void 0)}};We=new WeakMap;function Jo(){return typeof globalThis.window<"u"&&globalThis.window.parent!==globalThis.window}function Ko(t){switch(t.code){case"TIMED_OUT":case"TRANSPORT_FAILED":case"DISCONNECTED":case"UNRECOGNIZED":return!0;case"ORIGIN_REJECTED":case"APP_PROTOCOL_TOO_OLD":case"HOST_PROTOCOL_TOO_OLD":case"PROTOCOL_INCOMPATIBLE":case"ABORTED":return!1;default:return t}}var ae,Se,ct,z,de,ee,ce,le,te,be,$e,ke,v,Qn,Jt,Kt,Zt,Xt,yt,qn,Ne,Gt=class{constructor(){p(this,v);p(this,ae,new AbortController);p(this,Se,new Set);p(this,ct,new $t);p(this,z,{state:"connecting"});p(this,de);p(this,ee);p(this,ce);p(this,le);p(this,te);p(this,be,0);p(this,$e,!1);p(this,ke,!1);if(!Jo()){l(this,z,{state:"not-embedded"});return}a(this,v,Xt).call(this),a(this,v,Jt).call(this)}getSnapshot(){return r(this,z)}subscribe(e){return r(this,Se).add(e),()=>{r(this,Se).delete(e)}}close(){if(r(this,z).state==="closed")return;r(this,ae).abort(),r(this,ee)?.abort(),l(this,ee,void 0),a(this,v,Zt).call(this),a(this,v,yt).call(this);let e=r(this,de);l(this,de,void 0),a(this,v,Ne).call(this,{state:"closed"}),e?.close(),r(this,Se).clear()}};ae=new WeakMap,Se=new WeakMap,ct=new WeakMap,z=new WeakMap,de=new WeakMap,ee=new WeakMap,ce=new WeakMap,le=new WeakMap,te=new WeakMap,be=new WeakMap,$e=new WeakMap,ke=new WeakMap,v=new WeakSet,Qn=async function(e){let n=await wn(globalThis.window,Ln,e);return n.ok?Go(n.value,e):n},Jt=async function(){if(r(this,ae).signal.aborted||r(this,ke)||r(this,$e)||r(this,de))return;l(this,$e,!0),l(this,be,r(this,be)+1);let e=new AbortController;l(this,ee,e);let n;try{n=await a(this,v,Qn).call(this,e.signal)}catch(i){n={ok:!1,error:{code:"TRANSPORT_FAILED",cause:i}}}if(l(this,$e,!1),r(this,ee)===e&&l(this,ee,void 0),r(this,ae).signal.aborted||r(this,ke)){n.ok&&n.value.close();return}if(!n.ok){if(l(this,te,n.error),!Ko(n.error)){a(this,v,yt).call(this),y("the app connection was rejected",{side:"app",attempt:r(this,be),retryable:!1,error:J(n.error)}),a(this,v,Ne).call(this,{state:"rejected",error:n.error});return}a(this,v,Ne).call(this,r(this,z).state==="reconnecting"?{state:"reconnecting",lastError:n.error}:{state:"connecting",error:n.error}),a(this,v,Kt).call(this);return}l(this,de,n.value),l(this,te,void 0),r(this,ct).reset(),a(this,v,yt).call(this);let o=()=>{r(this,ae).signal.aborted||r(this,de)!==n.value||(l(this,de,void 0),l(this,te,{code:"DISCONNECTED"}),x("the app lost its established connection",{side:"app",attempt:r(this,be),surfaceId:n.value.surfaceId}),a(this,v,Xt).call(this),a(this,v,Ne).call(this,{state:"reconnecting",lastError:r(this,te)}),a(this,v,Kt).call(this))};if(n.value.closeSignal.addEventListener("abort",o,{once:!0}),n.value.closeSignal.aborted){o();return}a(this,v,Ne).call(this,{state:"connected",connection:n.value.connection,surfaceId:n.value.surfaceId})},Kt=function(){if(r(this,ae).signal.aborted||r(this,ke)||r(this,ce)!==void 0)return;let e=r(this,ct).next();x("retrying the app connection",{side:"app",state:r(this,z).state,failedAttempts:r(this,be),retryInMs:e,giveUpAfterMs:et,error:r(this,te)&&J(r(this,te))}),l(this,ce,globalThis.setTimeout(()=>{l(this,ce,void 0),a(this,v,Jt).call(this)},e))},Zt=function(){r(this,ce)!==void 0&&(globalThis.clearTimeout(r(this,ce)),l(this,ce,void 0))},Xt=function(){r(this,le)===void 0&&l(this,le,globalThis.setTimeout(()=>{l(this,le,void 0),a(this,v,qn).call(this)},et))},yt=function(){r(this,le)!==void 0&&(globalThis.clearTimeout(r(this,le)),l(this,le,void 0))},qn=function(){if(r(this,ae).signal.aborted||r(this,z).state==="connected"||r(this,z).state==="closed")return;l(this,ke,!0),a(this,v,Zt).call(this),r(this,ee)?.abort(),l(this,ee,void 0);let e=r(this,te)??{code:"TIMED_OUT",timeoutMs:et};y("the app gave up connecting to its Datadog host",{side:"app",state:r(this,z).state,failedAttempts:r(this,be),gaveUpAfterMs:et,error:J(e)}),a(this,v,Ne).call(this,{state:"rejected",error:e})},Ne=function(e){r(this,z)!==e&&(l(this,z,e),ge(r(this,Se)))};var eo=Object.freeze({connect(){return new Gt}});function to(t){return t.join(", ")}function Zo(t){return t.map(e=>`${e.path.length>0?e.path.join("."):"(root)"}: ${e.message}`).join("; ")}function Xo(t){let e;try{if(t instanceof Error)e=t.message||t.name;else if(typeof t=="string")e=t;else try{e=JSON.stringify(t)??String(t)}catch{e=Object.prototype.toString.call(t)}}catch{e="(cause could not be described)"}return e.length>200?`${e.slice(0,200)}\u2026`:e}function Yt(t){switch(t.code){case"TIMED_OUT":return{code:"TIMED_OUT",action:"retry",message:`TIMED_OUT: the Datadog host did not complete the connection within ${t.timeoutMs}ms. Reload the app to try again.`};case"ORIGIN_REJECTED":return{code:"ORIGIN_REJECTED",action:"contact-support",message:`ORIGIN_REJECTED: the embedding connection failed origin validation for "${t.origin}". Screenshot this message and contact support.`};case"APP_PROTOCOL_TOO_OLD":return{code:"APP_PROTOCOL_TOO_OLD",action:"update-app",message:`APP_PROTOCOL_TOO_OLD: this app supports embedding protocols ${t.appProtocols.join(", ")}, while the Datadog host requires ${t.hostProtocols.join(", ")}. Update @datadog/apps-frontend, rebuild this app, and upload the new bundle.`};case"HOST_PROTOCOL_TOO_OLD":return{code:"HOST_PROTOCOL_TOO_OLD",action:"contact-support",message:`HOST_PROTOCOL_TOO_OLD: this app supports embedding protocols ${t.appProtocols.join(", ")}, newer than the Datadog host's ${t.hostProtocols.join(", ")}. Rebuilding the app will not fix this; screenshot this message and contact support.`};case"PROTOCOL_INCOMPATIBLE":return{code:"PROTOCOL_INCOMPATIBLE",action:"contact-support",message:`PROTOCOL_INCOMPATIBLE: this app supports embedding protocols ${t.appProtocols.join(", ")}, while the Datadog host supports ${t.hostProtocols.join(", ")}. The sets do not overlap; screenshot this message and contact support.`};case"DISCONNECTED":return{code:"CONNECTION_LOST",action:"retry",message:"CONNECTION_LOST: the Datadog host stopped responding and the connection could not be re-established. Reload the app to try again."};case"TRANSPORT_FAILED":return{code:"UNKNOWN",action:"contact-support",message:`TRANSPORT_FAILED: the local embedding transport failed (${Xo(t.cause)}). Screenshot this message and contact support.`};case"UNRECOGNIZED":return{code:"UNKNOWN",action:"contact-support",message:`UNRECOGNIZED: the peer reported failure code "${t.rawCode}", which this app build does not know. Screenshot this message and contact support.`};case"ABORTED":return{code:"UNKNOWN",action:"contact-support",message:"ABORTED: the embedding connection was cancelled unexpectedly. Screenshot this message and contact support."};default:return t}}function Qt(t){switch(t.code){case"APP_MAJOR_TOO_OLD":return{code:"APP_MAJOR_TOO_OLD",action:"update-app",requestedVersion:t.wanted,availableVersions:t.hostVersions,message:`APP_MAJOR_TOO_OLD: this app's claim requests v${t.wanted}, while the host now offers ${to(t.hostVersions)}. Update @datadog/apps-frontend, rebuild this app, and upload the new bundle.`};case"HOST_MAJOR_TOO_OLD":return{code:"HOST_MAJOR_TOO_OLD",action:"contact-support",requestedVersion:t.wanted,availableVersions:t.hostVersions,message:`HOST_MAJOR_TOO_OLD: this app's claim requests v${t.wanted}, newer than the host's ${to(t.hostVersions)}. Rebuilding the app will not fix this; screenshot this message and contact support.`};case"CONTRACT_INCOMPATIBLE":return{code:"UNKNOWN",action:"contact-support",message:`CONTRACT_INCOMPATIBLE: the host omitted required field "${t.field}" despite advertising a compatible contract version. Screenshot this message and contact support.`};case"INVALID_RESULT":return{code:"UNKNOWN",action:"contact-support",message:`INVALID_RESULT: a host value failed this app's bundled parser (${Zo(t.issues)}). Screenshot this message and contact support.`};case"TIMED_OUT":return{code:"TIMED_OUT",action:"retry",message:`TIMED_OUT: the Datadog host did not complete the claim request within ${t.timeoutMs}ms. Reload the app to try again.`};case"DISCONNECTED":case"UNRECOGNIZED":return Yt(t);default:return t}}var Yo=0,Qo=Object.freeze({status:"pending"}),qo=Object.freeze({status:"unavailable"}),er=Object.freeze({code:"UNKNOWN",action:"contact-support",message:"EMBEDDING_CLOSED: the Datadog App connection closed while its provider was still mounted. Screenshot this message and contact support."}),qt=Object.freeze({code:"UNKNOWN",action:"contact-support",message:"CLAIM_REJECTED: the requested Datadog App claim failed unexpectedly. Screenshot this message and contact support."}),no=Object.freeze({code:"UNKNOWN",action:"contact-support",message:"CONNECTION_START_FAILED: the Datadog App connection could not be started. Screenshot this message and contact support."});function en(){return Qo}function oo(){return qo}function tr(t){let e="requestedVersion"in t?Object.freeze({...t,availableVersions:Object.freeze([...t.availableVersions])}):Object.freeze({...t});return Object.freeze({status:"failed",error:e})}var Re,pe,ve,vt=class{constructor(e,n){this.owner=e;this.resource=n;p(this,Re,new Set);p(this,pe);p(this,ve,!1);Fe(this,"subscribe",e=>{r(this,pe)!==void 0&&(globalThis.clearTimeout(r(this,pe)),l(this,pe,void 0));let n=()=>e();r(this,Re).add(n),r(this,ve)||(l(this,ve,!0),this.owner.activate(this.resource));let o=!0;return()=>{o&&(o=!1,r(this,Re).delete(n),r(this,Re).size===0&&r(this,pe)===void 0&&l(this,pe,globalThis.setTimeout(()=>{l(this,pe,void 0),r(this,Re).size===0&&r(this,ve)&&(l(this,ve,!1),this.owner.deactivate(this.resource))},Yo)))}})}owner;resource;notify(){ge(r(this,Re))}get isActive(){return r(this,ve)}};Re=new WeakMap,pe=new WeakMap,ve=new WeakMap;var Ae,$,Ie,G,ne,he,Je,E,ro,io,so,on,Ge,ye,ue,Ue,nn=class{constructor(e,n){p(this,E);p(this,Ae);p(this,$);p(this,Ie,en());p(this,G);p(this,ne);p(this,he);p(this,Je,[]);Fe(this,"getSnapshot",()=>r(this,Ie));Fe(this,"subscribe",e=>r(this,Ae).subscribe(e));l(this,$,n),l(this,Ae,new vt(e,this))}sync(e){if(!e){this.reset();return}switch(e.state){case"connected":if(r(this,G)===e.connection)return;a(this,E,ye).call(this),l(this,G,e.connection),a(this,E,Ue).call(this,en()),a(this,E,ro).call(this,e.connection);return;case"connecting":case"reconnecting":this.reset();return;case"not-embedded":l(this,G,void 0),a(this,E,ye).call(this),a(this,E,Ue).call(this,oo());return;case"rejected":l(this,G,void 0),a(this,E,ye).call(this),a(this,E,ue).call(this,Yt(e.error));return;case"closed":l(this,G,void 0),a(this,E,ye).call(this),a(this,E,ue).call(this,er);return;default:return e}}fail(e){l(this,G,void 0),a(this,E,ye).call(this),a(this,E,ue).call(this,e)}reset(){l(this,G,void 0),a(this,E,ye).call(this),a(this,E,Ue).call(this,en())}};Ae=new WeakMap,$=new WeakMap,Ie=new WeakMap,G=new WeakMap,ne=new WeakMap,he=new WeakMap,Je=new WeakMap,E=new WeakSet,ro=function(e){let n=new AbortController;l(this,ne,n);let o;try{o=e.claim(r(this,$),{signal:n.signal})}catch(i){y("a claim could not be requested",{side:"app",identifier:r(this,$).identifier,current:a(this,E,Ge).call(this,e,n),cause:S(i)}),a(this,E,Ge).call(this,e,n)&&(l(this,ne,void 0),a(this,E,ue).call(this,qt));return}o.then(i=>{if(!a(this,E,Ge).call(this,e,n)){i.ok&&i.value.release();return}if(l(this,ne,void 0),!i.ok){if(i.error.code==="PEER_LACKS_MODULE"){x("the Datadog host does not offer this module",{side:"app",identifier:r(this,$).identifier,version:r(this,$).version}),a(this,E,Ue).call(this,oo());return}if(i.error.code==="ABORTED"){a(this,E,ue).call(this,qt);return}a(this,E,ue).call(this,Qt(i.error));return}a(this,E,io).call(this,e,i.value)},i=>{y("a claim request rejected",{side:"app",identifier:r(this,$).identifier,current:a(this,E,Ge).call(this,e,n),cause:S(i)}),a(this,E,Ge).call(this,e,n)&&(l(this,ne,void 0),a(this,E,ue).call(this,qt))})},io=function(e,n){if(!r(this,Ae).isActive||r(this,G)!==e||r(this,he)){n.release();return}l(this,he,n),r(this,Je).push(n.onInvalidated(o=>a(this,E,so).call(this,n,o))),r(this,Je).push(n.onValuesChanged(()=>{r(this,he)===n&&a(this,E,on).call(this,n)})),a(this,E,on).call(this,n)},so=function(e,n){if(r(this,he)!==e)return;let o=Qt(n);a(this,E,ye).call(this),a(this,E,ue).call(this,o)},on=function(e){let n=Object.entries(r(this,$).fields),o=n.map(([s])=>s),i=Object.create(null);for(let[s,d]of n){let c=e.fields[s];i[s]=d.kind==="value"?c.get():c}if(r(this,Ie).status==="ready"){let s=r(this,Ie).fields;if(o.every(d=>Object.is(s[d],i[d])))return}a(this,E,Ue).call(this,Object.freeze({status:"ready",fields:Object.freeze(i)}))},Ge=function(e,n){return r(this,Ae).isActive&&r(this,G)===e&&r(this,ne)===n&&!n.signal.aborted},ye=function(){r(this,ne)?.abort(),l(this,ne,void 0);for(let n of r(this,Je).splice(0))n();let e=r(this,he);l(this,he,void 0),e?.release()},ue=function(e){y("a Datadog App claim failed",{side:"app",identifier:r(this,$).identifier,version:r(this,$).version,code:e.code,action:e.action,reason:e.message}),a(this,E,Ue).call(this,tr(e))},Ue=function(e){r(this,Ie)!==e&&(l(this,Ie,e),r(this,Ae).notify())};var tn=Object.freeze({state:"connecting"});function nr(t){switch(t.state){case"connecting":return{state:"connecting",error:t.error};case"connected":return{state:"connected",surfaceId:t.surfaceId};case"reconnecting":return{state:"reconnecting",lastError:t.lastError};case"rejected":return{state:"rejected",error:t.error};case"not-embedded":return{state:"not-embedded"};case"closed":return{state:"closed"};default:return t}}var Ke,Ze,Xe,Rt,rn=class{constructor(e){p(this,Xe);p(this,Ke);p(this,Ze,tn);Fe(this,"getSnapshot",()=>r(this,Ze));Fe(this,"subscribe",e=>r(this,Ke).subscribe(e));l(this,Ke,new vt(e,this))}sync(e){a(this,Xe,Rt).call(this,e?nr(e):tn)}fail(e){a(this,Xe,Rt).call(this,{state:"rejected",error:{code:"TRANSPORT_FAILED",cause:e}})}reset(){a(this,Xe,Rt).call(this,tn)}};Ke=new WeakMap,Ze=new WeakMap,Xe=new WeakSet,Rt=function(e){r(this,Ze)!==e&&(l(this,Ze,e),r(this,Ke).notify())};var lt,X,ut,fe,Ye,_e,Qe,Ve,L,ao,co,lo,uo,an,dn,cn,sn=class{constructor(e){this.connector=e;p(this,L);p(this,lt,new WeakMap);p(this,X,new Set);p(this,ut,{activate:e=>a(this,L,lo).call(this,e),deactivate:e=>a(this,L,uo).call(this,e)});p(this,fe);p(this,Ye);p(this,_e);p(this,Qe);p(this,Ve,0)}connector;getClaim(e){let n=e,o=r(this,lt).get(n);if(o)return o;let i=new nn(r(this,ut),e);return r(this,lt).set(n,i),i}getEmbeddingMetadata(){return r(this,Qe)||l(this,Qe,new rn(r(this,ut))),r(this,Qe)}start(){l(this,Ve,r(this,Ve)+1),r(this,Ve)===1&&a(this,L,ao).call(this);let e=!0;return()=>{e&&(e=!1,l(this,Ve,r(this,Ve)-1),r(this,Ve)===0&&a(this,L,co).call(this))}}};lt=new WeakMap,X=new WeakMap,ut=new WeakMap,fe=new WeakMap,Ye=new WeakMap,_e=new WeakMap,Qe=new WeakMap,Ve=new WeakMap,L=new WeakSet,ao=function(){l(this,_e,void 0);for(let n of r(this,X))n.reset();let e;try{e=this.connector.connect()}catch(n){a(this,L,cn).call(this,"connect",n);return}l(this,fe,e);try{l(this,Ye,e.subscribe(()=>a(this,L,an).call(this,e))),a(this,L,an).call(this,e)}catch(n){a(this,L,dn).call(this,e),a(this,L,cn).call(this,"subscribe",n);return}},co=function(){let e=r(this,fe);e&&a(this,L,dn).call(this,e),l(this,_e,void 0);for(let n of r(this,X))n.reset()},lo=function(e){if(r(this,X).add(e),r(this,_e)){e.fail(r(this,_e));return}e.sync(r(this,fe)?.getSnapshot())},uo=function(e){r(this,X).delete(e),e.reset()},an=function(e){if(r(this,fe)!==e)return;let n=e.getSnapshot();for(let o of r(this,X))o.sync(n)},dn=function(e){if(r(this,fe)!==e)return;l(this,fe,void 0);let n=r(this,Ye);l(this,Ye,void 0),n&&w("embedding connection handle unsubscribe",()=>n());for(let o of r(this,X))w("embedding claim resource reset",()=>o.reset());w("embedding connection handle close",()=>e.close())},cn=function(e,n){y("the embedding connection could not be started",{side:"app",step:e,affectedResources:r(this,X).size,cause:S(n)}),l(this,_e,no);for(let o of r(this,X))o.fail(no)};function po(t){return new sn(t)}var ho=po(eo),sr=In(ho),ar=Object.freeze([Rn()]);function dr(t){try{console.warn(t)}catch{}}function cr(t,e,n){let o=e??[],i=new Set(o.map(c=>c.id)),s=new Set(n??[]),d=t.filter(c=>!s.has(c.id)&&!i.has(c.id));if(s.size===0)return[...d,...o];for(let c of o)if(s.has(c.id))throw new Error(`DatadogAppProvider received module "${c.id}" in both modules and disabledModules.`);for(let c of s)t.some(f=>f.id===c)||o.some(f=>f.id===c)||dr(`[Datadog App provider] disabledModules names "${c}", but no module with that id is installed.`);return[...d,...o]}var lr=({children:t,modules:e,disabledModules:n})=>{let[o]=ir(()=>cr(ar,e,n));return rr(()=>{let i=new AbortController;return gn(o,ho,i.signal),()=>i.abort()},[o]),or(sr,null,t)};import{useSyncExternalStore as ur}from"react";var ln=new WeakMap;function fo(t){return t==="connecting"||t==="reconnecting"}function pr(t,e){let n=ln.get(e);if(!n){let o=vn(t),i;n=new Promise(h=>{i=h}),ln.set(e,n);let s,d=!1,c=()=>{d||fo(e.getSnapshot().state)||(d=!0,s?.(),ln.delete(e),An(t,o),i())};s=e.subscribe(c),d?s():c()}throw n}function hr(){throw new Error("useDatadogAppEmbedding does not support server rendering: the Datadog App embedding connection only exists in the browser.")}function fr(t){throw new Error(t.state==="rejected"?`The Datadog App embedding connection was rejected: ${t.error.code}.`:"The Datadog App embedding connection closed.")}function mr(t){let e=_n(),n=e.getEmbeddingMetadata(),o=ur(n.subscribe,n.getSnapshot,hr);return t?.suspense&&(fo(o.state)&&pr(e,n),(o.state==="rejected"||o.state==="closed")&&fr(o)),o}export{lr as DatadogAppProvider,mr as useDatadogAppEmbedding};
|
|
7
7
|
//# sourceMappingURL=index.js.map
|