@datadog/apps-frontend 0.0.6 → 0.0.7

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.
@@ -5,23 +5,56 @@
5
5
 
6
6
  import type { ComponentType, PropsWithChildren } from 'react';
7
7
  import type { DatadogAppProviderModule } from './config.js';
8
+ /**
9
+ * The ids of this package's default modules, exactly as app authors may name
10
+ * them in `disabledModules`. Publishing a module's id here is half of
11
+ * promoting it to a default; the other half is its entry in DEFAULT_MODULES
12
+ * directly below. The two cannot drift silently: DEFAULT_MODULES only accepts
13
+ * modules whose ids appear here, so a promoted entry without its id is a
14
+ * compile error. Deep links is the first (and so far only) default.
15
+ */
16
+ export type DefaultDatadogAppModuleId = 'datadog.deep-links';
17
+ /**
18
+ * Merges default and explicitly requested modules into the list this
19
+ * provider installs.
20
+ *
21
+ * `disabledModules` excludes defaults; passing a module explicitly and
22
+ * disabling its id in the same config is a contradiction and throws.
23
+ * Disabling an id that is neither a default nor explicitly requested warns:
24
+ * the id is stale (removed from a later package) or misspelled, and a frozen
25
+ * app must keep rendering rather than fail on it.
26
+ *
27
+ * A default and an explicitly requested module with the same id is not a
28
+ * duplicate: the explicit instance wins. An app compiled before a module was
29
+ * promoted to a default, requesting it explicitly, keeps working after the
30
+ * promotion.
31
+ */
32
+ export declare function mergeDatadogAppProviderModules(defaults: readonly DatadogAppProviderModule[], requested: readonly DatadogAppProviderModule[] | undefined, disabled: readonly string[] | undefined): readonly DatadogAppProviderModule[];
8
33
  export interface DatadogAppProviderProps extends PropsWithChildren {
9
34
  /**
10
- * Capability modules to install on this mount, in list order. Read once
11
- * per mount: modules are startup configuration, so a later change to
12
- * this prop is ignored -- remount the provider to change modules. (The
13
- * common inline form, `modules={[resizing(...)]}`, builds a fresh array
14
- * every render; installs deliberately do not track it.)
35
+ * Additional modules to install on top of the defaults, in list order.
36
+ * Read once per mount: modules are startup configuration, so a later
37
+ * change to this prop is ignored -- remount the provider to change
38
+ * modules. (The common inline form, `modules={[resizing(...)]}`, builds a
39
+ * fresh array every render; installs deliberately do not track it.)
15
40
  */
16
41
  readonly modules?: readonly DatadogAppProviderModule[];
42
+ /**
43
+ * Ids of default modules to exclude from this provider. The accepted
44
+ * names are exactly the package's default modules, so a misspelled id is
45
+ * a compile error; at runtime an unknown id still only warns, so a
46
+ * frozen app compiled against an older default set keeps rendering.
47
+ */
48
+ readonly disabledModules?: readonly DefaultDatadogAppModuleId[];
17
49
  }
18
50
  /**
19
51
  * Owns the shared embedding connection and installs capability modules.
20
52
  *
21
- * On each mount, every listed module's `install` runs once, in list order,
22
- * receiving the shared connection and this mount's dispose signal (aborted on
23
- * unmount, so modules clean up). A failing install is reported and isolated;
24
- * the remaining modules and the app still run. Installs happen after this
53
+ * On each mount, this package's default modules (deep links today) plus every
54
+ * explicitly listed module's `install` runs once, in list order, receiving
55
+ * the shared connection and this mount's dispose signal (aborted on unmount,
56
+ * so modules clean up). A failing install is reported and isolated; the
57
+ * remaining modules and the app still run. Installs happen after this
25
58
  * provider's children have mounted, and modules have no render rights, so no
26
59
  * child can observe module state during its own mount.
27
60
  *
@@ -3,5 +3,4 @@
3
3
  * Copyright 2019-Present Datadog, Inc.
4
4
  */
5
5
 
6
- export { DatadogAppsProvider } from './apps-provider.js';
7
- export type { DatadogAppsProviderProps, DefaultDatadogAppModuleId, } from './apps-provider.js';
6
+ export {};
package/dist/src/index.js CHANGED
@@ -3,5 +3,4 @@
3
3
  * Copyright 2019-Present Datadog, Inc.
4
4
  */
5
5
 
6
- import{a as s}from"./_chunks/chunk-VVRISDII.js";import{a as n}from"./_chunks/chunk-3UFPUAWY.js";import"./_chunks/chunk-MF7HCOXQ.js";import"./_chunks/chunk-2V2HASKF.js";import"./_chunks/chunk-PA4Z7DNH.js";import"./_chunks/chunk-LEEYMNMO.js";import{createElement as u,useState as g}from"react";var m=Object.freeze([n()]);function D(d){try{console.warn(d)}catch{}}function c(d,t,a){let o=t??[],l=new Set(o.map(e=>e.id)),r=new Set(a??[]),i=d.filter(e=>!r.has(e.id)&&!l.has(e.id));if(r.size===0)return[...i,...o];for(let e of o)if(r.has(e.id))throw new Error(`DatadogAppsProvider received module "${e.id}" in both modules and disabledModules.`);for(let e of r)d.some(p=>p.id===e)||o.some(p=>p.id===e)||D(`[Datadog Apps provider] disabledModules names "${e}", but no module with that id is installed.`);return[...i,...o]}var f=({children:d,modules:t,disabledModules:a})=>{let[o]=g(()=>c(m,t,a));return u(s,{modules:o},d)};export{f as DatadogAppsProvider};
7
6
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../src/apps-provider.ts"],
4
- "sourcesContent": ["import { createElement, useState } from 'react';\nimport type { ComponentType, PropsWithChildren, ReactElement } from 'react';\n\nimport { datadogAppDeepLinks } from './deep-links/react';\nimport type { DatadogAppProviderModule } from './embedding/react/config';\nimport { DatadogAppProvider } from './embedding/react/provider';\n\n/**\n * The ids of this package's default modules, exactly as app authors may name\n * them in `disabledModules`. Publishing a module's id here is half of\n * promoting it to a default; the other half is its entry in DEFAULT_MODULES\n * directly below. The two cannot drift silently: DEFAULT_MODULES only accepts\n * modules whose ids appear here, so a promoted entry without its id is a\n * compile error. Deep links is the first (and so far only) default.\n */\nexport type DefaultDatadogAppModuleId = 'datadog.deep-links';\n\n/**\n * Modules this provider installs by default, in list order (before any\n * explicitly requested ones).\n *\n * This composite provider, not the embedding core, owns the default set: the\n * core stays module-agnostic and never resolves a module id. A module package\n * lands in this list when it is promoted to a default.\n *\n * Deep links: mirrors the app's query and fragment state onto the embedding\n * host's page URL so navigations become shareable links. Inert without a host-side\n * deep-links counterpart (the claim stays pending), so defaulting it is safe\n * on every surface regardless of host wiring. Disable with\n * `disabledModules={['datadog.deep-links']}` or pass a configured\n * `datadogAppDeepLinks()` instance explicitly to replace it.\n */\nconst DEFAULT_MODULES: readonly DatadogAppProviderModule<DefaultDatadogAppModuleId>[] =\n Object.freeze([datadogAppDeepLinks()]);\n\n/** Applies to `disabledModules` only; explicitly passed modules win. */\nfunction warn(message: string): void {\n try {\n console.warn(message);\n } catch {\n // A hostile console implementation must never break rendering.\n }\n}\n\n/**\n * Merges default and explicitly requested modules into the list the core\n * provider installs.\n *\n * `disabledModules` excludes defaults; passing a module explicitly and\n * disabling its id in the same config is a contradiction and throws. Disabling\n * an id that is neither a default nor explicitly requested warns: the id is\n * stale (removed from a later package) or misspelled, and a frozen app must\n * keep rendering rather than fail on it.\n *\n * A default and an explicitly requested module with the same id is not a\n * duplicate: the explicit instance wins. An app compiled before a module was\n * promoted to a default, requesting it explicitly, keeps working after the\n * promotion.\n */\nexport function mergeDatadogAppsProviderModules(\n defaults: readonly DatadogAppProviderModule[],\n requested: readonly DatadogAppProviderModule[] | undefined,\n disabled: readonly string[] | undefined,\n): readonly DatadogAppProviderModule[] {\n const explicit = requested ?? [];\n const explicitIds = new Set(explicit.map((module) => module.id));\n const disabledIds = new Set(disabled ?? []);\n const survivingDefaults = defaults.filter(\n (module) => !disabledIds.has(module.id) && !explicitIds.has(module.id),\n );\n if (disabledIds.size === 0) {\n return [...survivingDefaults, ...explicit];\n }\n for (const module of explicit) {\n if (disabledIds.has(module.id)) {\n throw new Error(\n `DatadogAppsProvider received module \"${module.id}\" in both modules and disabledModules.`,\n );\n }\n }\n for (const id of disabledIds) {\n const isKnown =\n defaults.some((module) => module.id === id) ||\n explicit.some((module) => module.id === id);\n if (!isKnown) {\n warn(\n `[Datadog Apps provider] disabledModules names \"${id}\", but no module with that id is installed.`,\n );\n }\n }\n return [...survivingDefaults, ...explicit];\n}\n\nexport interface DatadogAppsProviderProps extends PropsWithChildren {\n /** Modules to install in addition to the defaults, in list order. */\n readonly modules?: readonly DatadogAppProviderModule[];\n /**\n * Ids of default modules to exclude from this provider. The accepted\n * names are exactly the package's default modules, so a misspelled id is\n * a compile error; at runtime an unknown id still only warns, so a frozen\n * app compiled against an older default set keeps rendering.\n */\n readonly disabledModules?: readonly DefaultDatadogAppModuleId[];\n}\n\n/**\n * The distribution-level Datadog App provider: installs this package's\n * default modules (deep links today), merges in explicitly requested ones, honors\n * `disabledModules`, and delegates to the module-agnostic\n * {@link DatadogAppProvider}. App authors normally mount this one\n * component.\n */\nexport const DatadogAppsProvider: ComponentType<DatadogAppsProviderProps> = ({\n children,\n modules,\n disabledModules,\n}: DatadogAppsProviderProps): ReactElement => {\n const [installed] = useState(() =>\n mergeDatadogAppsProviderModules(\n DEFAULT_MODULES,\n modules,\n disabledModules,\n ),\n );\n return createElement(DatadogAppProvider, { modules: installed }, children);\n};\n"],
5
- "mappings": "gPAAA,OAAS,iBAAAA,EAAe,YAAAC,MAAgB,QAgCxC,IAAMC,EACF,OAAO,OAAO,CAACC,EAAoB,CAAC,CAAC,EAGzC,SAASC,EAAKC,EAAuB,CACjC,GAAI,CACA,QAAQ,KAAKA,CAAO,CACxB,MAAQ,CAER,CACJ,CAiBO,SAASC,EACZC,EACAC,EACAC,EACmC,CACnC,IAAMC,EAAWF,GAAa,CAAC,EACzBG,EAAc,IAAI,IAAID,EAAS,IAAKE,GAAWA,EAAO,EAAE,CAAC,EACzDC,EAAc,IAAI,IAAIJ,GAAY,CAAC,CAAC,EACpCK,EAAoBP,EAAS,OAC9BK,GAAW,CAACC,EAAY,IAAID,EAAO,EAAE,GAAK,CAACD,EAAY,IAAIC,EAAO,EAAE,CACzE,EACA,GAAIC,EAAY,OAAS,EACrB,MAAO,CAAC,GAAGC,EAAmB,GAAGJ,CAAQ,EAE7C,QAAWE,KAAUF,EACjB,GAAIG,EAAY,IAAID,EAAO,EAAE,EACzB,MAAM,IAAI,MACN,wCAAwCA,EAAO,EAAE,wCACrD,EAGR,QAAWG,KAAMF,EAETN,EAAS,KAAMK,GAAWA,EAAO,KAAOG,CAAE,GAC1CL,EAAS,KAAME,GAAWA,EAAO,KAAOG,CAAE,GAE1CX,EACI,kDAAkDW,CAAE,6CACxD,EAGR,MAAO,CAAC,GAAGD,EAAmB,GAAGJ,CAAQ,CAC7C,CAqBO,IAAMM,EAA+D,CAAC,CACzE,SAAAC,EACA,QAAAC,EACA,gBAAAC,CACJ,IAA8C,CAC1C,GAAM,CAACC,CAAS,EAAIC,EAAS,IACzBf,EACIJ,EACAgB,EACAC,CACJ,CACJ,EACA,OAAOG,EAAcC,EAAoB,CAAE,QAASH,CAAU,EAAGH,CAAQ,CAC7E",
6
- "names": ["createElement", "useState", "DEFAULT_MODULES", "datadogAppDeepLinks", "warn", "message", "mergeDatadogAppsProviderModules", "defaults", "requested", "disabled", "explicit", "explicitIds", "module", "disabledIds", "survivingDefaults", "id", "DatadogAppsProvider", "children", "modules", "disabledModules", "installed", "useState", "createElement", "DatadogAppProvider"]
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@datadog/apps-frontend",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
4
4
  "private": false,
5
5
  "description": "React inputs for Datadog Apps",
6
6
  "homepage": "https://datadoghq.com",
@@ -1,7 +0,0 @@
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 m}from"./chunk-MF7HCOXQ.js";import{a as u,d as y,g as v}from"./chunk-PA4Z7DNH.js";import{J as g,K as f}from"./chunk-LEEYMNMO.js";var S=u(),L=y(),D=f({identifier:"datadog.deep-links",version:2,fields:{setDeepLinkState:g.readOnly({inputs:{search:S,fragment:S},result:L})}}),A=v(u(),u()),M=f({identifier:"datadog.deep-links",version:1,fields:{setDeepLinkVariables:g.readOnly({inputs:{variables:A,fragment:S},result:L})}});var k=Object.freeze({search:"",fragment:""});function C(){return typeof globalThis.location>"u"?k:Object.freeze({search:globalThis.location.search,fragment:globalThis.location.hash})}function T(a,e){console.error(`[datadog-apps:deep-links] ${a}`,e??"")}var i=null;function s(){b()}function E({search:a,fragment:e}){return JSON.stringify([a,e])}function b(a=!1){let e=i;if(e===null)return;let t=C(),n=E(t);!a&&e.lastPublishedFingerprint===n||(e.lastPublishedFingerprint=n,R(t))}function R(a){let e=i?.publishers;if(e===void 0)return;let t=e.values().next();t.done===!1&&t.value(a)}function V(a){let e=i?.publishers;if(e===void 0)return!1;let t=e.values().next();return t.done===!1&&t.value===a}function F(a){if(i!==null)return i.publishers.add(a),i;let e=globalThis.history,t=e.pushState,n=e.replaceState,c=new Set([a]),l=()=>{b()},o=function(r,d,h){t.call(e,r,d,h),l()},p=function(r,d,h){n.call(e,r,d,h),l()};try{e.pushState=o,e.replaceState=p,globalThis.addEventListener("popstate",s),globalThis.addEventListener("hashchange",s)}catch(r){throw e.replaceState===p&&(e.replaceState=n),e.pushState===o&&(e.pushState=t),globalThis.removeEventListener("popstate",s),globalThis.removeEventListener("hashchange",s),r}return i={pushState:o,replaceState:p,originalPushState:t,originalReplaceState:n,publishers:c,lastPublishedFingerprint:null},i}function x(a){let e=i;if(e===null||(e.publishers.delete(a),e.publishers.size>0))return;let t=globalThis.history;t.pushState===e.pushState&&(t.pushState=e.originalPushState),t.replaceState===e.replaceState&&(t.replaceState=e.originalReplaceState),globalThis.removeEventListener("popstate",s),globalThis.removeEventListener("hashchange",s),i=null}function P({embedding:a,disposeSignal:e}){if(e.aborted)return;let t=a.getClaim(D),n=({search:o,fragment:p})=>{let r=t.getSnapshot();r.status==="ready"&&r.fields.setDeepLinkState({search:o,fragment:p}).catch(d=>T("The app URL state could not be synchronized to the embedding host.",d))},c=o=>{o.status==="ready"&&V(n)&&b(!0)},l=t.subscribe(()=>{c(t.getSnapshot())});try{F(n)}catch(o){throw l(),o}c(t.getSnapshot()),e.addEventListener("abort",()=>{l(),x(n)},{once:!0})}var z=Object.freeze({});function Y(){return m("datadog.deep-links",z,{install({embedding:a,disposeSignal:e}){P({embedding:a,disposeSignal:e})}})}export{Y as a};
7
- //# sourceMappingURL=chunk-3UFPUAWY.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/deep-links/internal/protocol.ts", "../../../src/deep-links/react/module-install.ts", "../../../src/deep-links/react/index.ts"],
4
- "sourcesContent": ["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": "6IASA,IAAMA,EAAsCC,EAAO,EAC7CC,EAA4CC,EAAU,EAW/CC,EAQRC,EAAe,CAChB,WAAY,qBACZ,QAAS,EACT,OAAQ,CACJ,iBAAkBC,EAAG,SAAS,CAC1B,OAAQ,CACJ,OAAQN,EACR,SAAUA,CACd,EACA,OAAQE,CACZ,CAAC,CACL,CACJ,CAAC,EAEKK,EAAmEC,EACnEP,EAAO,EACPA,EAAO,CACb,EAGaQ,EAQRJ,EAAe,CAChB,WAAY,qBACZ,QAAS,EACT,OAAQ,CACJ,qBAAsBC,EAAG,SAAS,CAC9B,OAAQ,CACJ,UAAWC,EACX,SAAUP,CACd,EACA,OAAQE,CACZ,CAAC,CACL,CACJ,CAAC,EC7DD,IAAMQ,EAAyC,OAAO,OAAO,CACzD,OAAQ,GACR,SAAU,EACd,CAAC,EAQD,SAASC,GAAyC,CAC9C,OAAI,OAAO,WAAW,SAAa,IACxBD,EAEJ,OAAO,OAAO,CACjB,OAAQ,WAAW,SAAS,OAC5B,SAAU,WAAW,SAAS,IAClC,CAAC,CACL,CAEA,SAASE,EAAqBC,EAAiBC,EAAuB,CAClE,QAAQ,MAAM,6BAA6BD,CAAO,GAAIC,GAAS,EAAE,CACrE,CAsBA,IAAIC,EAAgC,KAOpC,SAASC,GAAyB,CAC9BC,EAAuB,CAC3B,CAEA,SAASC,EAAyB,CAC9B,OAAAC,EACA,SAAAC,CACJ,EAA6B,CACzB,OAAO,KAAK,UAAU,CAACD,EAAQC,CAAQ,CAAC,CAC5C,CAEA,SAASH,EAAuBI,EAAQ,GAAa,CACjD,IAAMC,EAAQP,EACd,GAAIO,IAAU,KACV,OAEJ,IAAMC,EAAgBZ,EAAqB,EACrCa,EAAcN,EAAyBK,CAAa,EACtD,CAACF,GAASC,EAAM,2BAA6BE,IAGjDF,EAAM,yBAA2BE,EACjCC,EAAyBF,CAAa,EAC1C,CAUA,SAASE,EAAyBH,EAA+B,CAC7D,IAAMI,EAAaX,GAAY,WAC/B,GAAIW,IAAe,OACf,OAEJ,IAAMC,EAAOD,EAAW,OAAO,EAAE,KAAK,EAClCC,EAAK,OAAS,IACbA,EAAK,MAAkBL,CAAK,CAErC,CAQA,SAASM,EAAkBC,EAA2B,CAClD,IAAMH,EAAaX,GAAY,WAC/B,GAAIW,IAAe,OACf,MAAO,GAEX,IAAMC,EAAOD,EAAW,OAAO,EAAE,KAAK,EACtC,OAAOC,EAAK,OAAS,IAASA,EAAK,QAAUE,CACjD,CAEA,SAASC,EAAoBD,EAA8B,CACvD,GAAId,IAAe,KACf,OAAAA,EAAW,WAAW,IAAIc,CAAO,EAC1Bd,EAEX,IAAMgB,EAAU,WAAW,QACrBC,EAAoBD,EAAQ,UAC5BE,EAAuBF,EAAQ,aAC/BL,EAAa,IAAI,IAAa,CAACG,CAAO,CAAC,EACvCK,EAAoB,IAAY,CAClCjB,EAAuB,CAC3B,EACMkB,EAAyC,SAC3CC,EACAC,EACAC,EACI,CACJN,EAAkB,KAAKD,EAASK,EAAMC,EAAQC,CAAG,EACjDJ,EAAkB,CACtB,EACMK,EAA+C,SACjDH,EACAC,EACAC,EACI,CACJL,EAAqB,KAAKF,EAASK,EAAMC,EAAQC,CAAG,EACpDJ,EAAkB,CACtB,EACA,GAAI,CACAH,EAAQ,UAAYI,EACpBJ,EAAQ,aAAeQ,EACvB,WAAW,iBAAiB,WAAYvB,CAAgB,EACxD,WAAW,iBAAiB,aAAcA,CAAgB,CAC9D,OAASF,EAAO,CAIZ,MAAIiB,EAAQ,eAAiBQ,IACzBR,EAAQ,aAAeE,GAEvBF,EAAQ,YAAcI,IACtBJ,EAAQ,UAAYC,GAExB,WAAW,oBAAoB,WAAYhB,CAAgB,EAC3D,WAAW,oBAAoB,aAAcA,CAAgB,EACvDF,CACV,CACA,OAAAC,EAAa,CACT,UAAWoB,EACX,aAAcI,EACd,kBAAAP,EACA,qBAAAC,EACA,WAAAP,EACA,yBAA0B,IAC9B,EACOX,CACX,CAEA,SAASyB,EAAoBX,EAAwB,CACjD,IAAMP,EAAQP,EAKd,GAJIO,IAAU,OAGdA,EAAM,WAAW,OAAOO,CAAO,EAC3BP,EAAM,WAAW,KAAO,GACxB,OAEJ,IAAMS,EAAU,WAAW,QAKvBA,EAAQ,YAAcT,EAAM,YAC5BS,EAAQ,UAAYT,EAAM,mBAE1BS,EAAQ,eAAiBT,EAAM,eAC/BS,EAAQ,aAAeT,EAAM,sBAEjC,WAAW,oBAAoB,WAAYN,CAAgB,EAC3D,WAAW,oBAAoB,aAAcA,CAAgB,EAC7DD,EAAa,IACjB,CA8BO,SAAS0B,EAA2B,CACvC,UAAAC,EACA,cAAAC,CACJ,EAA4C,CACxC,GAAIA,EAAc,QACd,OAGJ,IAAMC,EAAQF,EAAU,SAASG,CAA2B,EAEtDhB,EAAmB,CAAC,CAAE,OAAAV,EAAQ,SAAAC,CAAS,IAAM,CAC/C,IAAM0B,EAAQF,EAAM,YAAY,EAC5BE,EAAM,SAAW,SAGrBA,EAAM,OACD,iBAAiB,CAAE,OAAA3B,EAAQ,SAAAC,CAAS,CAAC,EACrC,MAAON,GACJF,EACI,qEACAE,CACJ,CACJ,CACR,EAQMiC,EACFD,GACO,CACHA,EAAM,SAAW,SAAWlB,EAAkBC,CAAO,GAIrDZ,EAAuB,EAAI,CAEnC,EACM+B,EAAcJ,EAAM,UAAU,IAAM,CACtCG,EAAeH,EAAM,YAAY,CAAC,CACtC,CAAC,EAED,GAAI,CACAd,EAAoBD,CAAO,CAC/B,OAASf,EAAO,CACZ,MAAAkC,EAAY,EACNlC,CACV,CAKAiC,EAAeH,EAAM,YAAY,CAAC,EAElCD,EAAc,iBACV,QACA,IAAM,CACFK,EAAY,EACZR,EAAoBX,CAAO,CAC/B,EACA,CAAE,KAAM,EAAK,CACjB,CACJ,CChRA,IAAMoB,EAAqD,OAAO,OAAO,CAAC,CAAC,EAUpE,SAASC,GAAyD,CACrE,OAAOC,EACH,qBACAF,EACA,CACI,QAAQ,CACJ,UAAAG,EACA,cAAAC,CACJ,EAA8C,CAC1CC,EAA2B,CAAE,UAAAF,EAAW,cAAAC,CAAc,CAAC,CAC3D,CACJ,CACJ,CACJ",
6
- "names": ["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
- }
@@ -1,7 +0,0 @@
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
- var t=Symbol("DatadogAppProviderModule");function p(e,d,n){if(e.length===0)throw new Error("A Datadog App provider module requires an id.");return Object.freeze({id:e,config:Object.freeze({...d}),[t]:n})}function l(e,d){try{console.error(`Installing the "${e}" Datadog App provider module failed; the remaining modules and the app still run.`,d)}catch{}}function g(e,d,n){let r=new Set;for(let o of e){if(r.has(o.id))throw new Error(`DatadogAppProvider received duplicate module "${o.id}".`);r.add(o.id)}let i=Object.freeze({embedding:d,disposeSignal:n});for(let o of e)try{o[t].install(i)}catch(a){l(o.id,a)}}export{p as a,g as b};
7
- //# sourceMappingURL=chunk-MF7HCOXQ.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/embedding/react/config.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"],
5
- "mappings": "AAEA,IAAMA,EAA8C,OAChD,0BACJ,EAoDO,SAASC,EAIZC,EACAC,EACAC,EACsC,CACtC,GAAIF,EAAG,SAAW,EACd,MAAM,IAAI,MAAM,+CAA+C,EAEnE,OAAO,OAAO,OAAO,CACjB,GAAAA,EACA,OAAQ,OAAO,OAAO,CAAE,GAAGC,CAAO,CAAC,EACnC,CAACH,CAA4B,EAAGI,CACpC,CAAC,CACL,CAIA,SAASC,EAAqBC,EAAkBC,EAAsB,CAClE,GAAI,CACA,QAAQ,MACJ,mBAAmBD,CAAQ,qFAC3BC,CACJ,CACJ,MAAQ,CAER,CACJ,CAYO,SAASC,EACZC,EACAC,EACAC,EACI,CACJ,IAAMC,EAAY,IAAI,IACtB,QAAWC,KAAUJ,EAAS,CAC1B,GAAIG,EAAU,IAAIC,EAAO,EAAE,EACvB,MAAM,IAAI,MACN,iDAAiDA,EAAO,EAAE,IAC9D,EAEJD,EAAU,IAAIC,EAAO,EAAE,CAC3B,CACA,IAAMC,EAAyC,OAAO,OAAO,CACzD,UAAAJ,EACA,cAAAC,CACJ,CAAC,EACD,QAAWE,KAAUJ,EACjB,GAAI,CACAI,EAAOb,CAA4B,EAAE,QAAQc,CAAM,CACvD,OAASP,EAAgB,CACrBF,EAAqBQ,EAAO,GAAIN,CAAK,CACzC,CAER",
6
- "names": ["providerModuleImplementation", "createDatadogAppProviderModule", "id", "config", "implementation", "reportInstallFailure", "moduleId", "error", "installDatadogAppProviderModules", "modules", "embedding", "disposeSignal", "moduleIds", "module", "handle"]
7
- }
@@ -1,7 +0,0 @@
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{b as mn}from"./chunk-MF7HCOXQ.js";import{c as bn}from"./chunk-2V2HASKF.js";import{A as y,B as k,C as M,D as Ee,a as Fe,b as r,c as p,d,e as a,f as qe,g as En,h as gn,i as He,j as Tn,k as Cn,l as et,m as It,n as B,o as tt,p as On,q as yn,r as _t,s as Dt,t as S,u as J,v as H,w as b,x as me,y as L,z as c}from"./chunk-LEEYMNMO.js";import{createElement as Yo,useEffect as Qo,useState as qo}from"react";var lo=/^https:\/\/(?:[a-zA-Z0-9-]+\.)*(?:datadoghq\.(?:com|eu)|ddog-gov\.com)$/,uo=/^https:\/\/(?:[a-zA-Z0-9-]+\.)*(?:datad0g\.com|datad0g\.eu|staging\.dog|prod\.dog)$/,po=/^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/;function Rn(t){return lo.test(t)||uo.test(t)||po.test(t)}var vn="dd-apps-frontend-bootstrap",An=1;function fo(t,e,n){let{data:o}=n;return n.source!==t||n.ports.length!==0||!y(o)||o.namespace!==vn||o.version!==An||o.type!=="accepted"&&o.type!=="rejected-origin"||o.attemptId!==e?{status:"ignored"}:Rn(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 In(t,e,n,o=1e4){if(n.aborted)return Promise.resolve(c({code:"ABORTED"}));let i=t.parent;if(i===t)return Promise.resolve(c({code:"TRANSPORT_FAILED",cause:new Error("The app is not running in an iframe.")}));let s=me("bootstrap"),l=new MessageChannel;return new Promise(u=>{let f=!1,m=!1,h=!1,C,_=P=>{f||(f=!0,t.removeEventListener("message",O),n.removeEventListener("abort",D),C!==void 0&&globalThis.clearTimeout(C),P.ok||(M("failed app bootstrap port",()=>l.port1.close()),m||M("untransferred app bootstrap port",()=>l.port2.close())),u(P))},O=P=>{let T=fo(i,s,P);T.status==="accepted"?_(L(l.port1)):T.status==="rejected-origin"&&_(c({code:"ORIGIN_REJECTED",origin:T.origin}))},D=()=>_(c({code:"ABORTED"})),x=()=>{if(!(h||f)){h=!0,C=globalThis.setTimeout(()=>_(c({code:"TIMED_OUT",timeoutMs:o})),Math.max(0,o));try{i.postMessage({namespace:vn,version:An,type:"request",attemptId:s,documentId:e},"*",[l.port2]),m=!0}catch(P){_(c({code:"TRANSPORT_FAILED",cause:P}))}}};if(t.addEventListener("message",O),n.addEventListener("abort",D,{once:!0}),n.aborted){D();return}x()})}var _n=me("document");var Dn="dd-apps-frontend-compatibility",Pn=1,mo=64;function Eo(t,e,n,o){return n.aborted?Promise.resolve({ok:!1,error:{code:"ABORTED"}}):new Promise(i=>{let s=!1,l,u=h=>{s||(s=!0,t.removeEventListener("message",f),n.removeEventListener("abort",m),l!==void 0&&globalThis.clearTimeout(l),i(h))},f=h=>u({ok:!0,value:h}),m=()=>u({ok:!1,error:{code:"ABORTED"}});t.addEventListener("message",f),n.addEventListener("abort",m,{once:!0}),l=globalThis.setTimeout(()=>u({ok:!1,error:{code:"TIMED_OUT",timeoutMs:e}}),Math.max(0,e));try{t.start(),o?.()}catch(h){u({ok:!1,error:{code:"TRANSPORT_FAILED",cause:h}})}})}function Ln(t){if(!(!Array.isArray(t)||t.length===0||t.length>mo||!Array.from(t).every(e=>Number.isSafeInteger(e)&&e>0)||new Set(t).size!==t.length))return[...t].sort((e,n)=>e-n)}function go(t,e){let n=t.filter(u=>e.includes(u));if(n.length>0)return{ok:!0,value:Math.max(...n)};let o=Math.min(...t),i=Math.max(...t),s=Math.min(...e),l=Math.max(...e);return i<s?{ok:!1,error:{code:"APP_PROTOCOL_TOO_OLD",appProtocols:t,hostProtocols:e}}:l<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 Mn(t,e,n,o){let i=Ln(e);if(!i)return t.close(),{ok:!1,error:{code:"TRANSPORT_FAILED",cause:new Error("The app protocol registry is invalid.")}};let s=await Eo(t,n,o,()=>{t.postMessage({namespace:Dn,version:Pn,type:"offer",role:"app",protocols:i})});if(t.close(),!s.ok)return s;let{data:l,ports:u}=s.value;if(!y(l)||l.namespace!==Dn||l.version!==Pn||l.type!=="answer"||l.role!=="host"){for(let C of u)C.close();return{ok:!1,error:{code:"TRANSPORT_FAILED",cause:new Error("The host returned an invalid compatibility answer.")}}}let f=Ln(l.protocols);if(!f){for(let C of u)C.close();return{ok:!1,error:{code:"TRANSPORT_FAILED",cause:new Error("The host returned an invalid supported-protocol list.")}}}let m=go(i,f);if(!m.ok){for(let C of u)C.close();return m}let[h]=u;if(u.length!==1||h===void 0){for(let C of u)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:m.value,operationalPort:h}}}import{connect as Po,PortMessenger as Lo,Reply as Mo}from"penpal";var pt="dd-apps-frontend-heartbeat",ht=1,Nn=Object.freeze({intervalMs:En,timeoutMs:gn});function rt(t){try{t.postMessage({namespace:pt,version:ht,type:"close"})}catch{}}function wn(t,e){rt(e),globalThis.setTimeout(()=>{M("failed Penpal connection",()=>t.destroy()),M("failed operational port",()=>e.close())},He)}var K,re,ie,nt,Q,ot,V,Pt,Lt,Mt,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(!(!y(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){b("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)||(d(this,re,void 0),d(this,ie,0),r(this,K)!==void 0&&(globalThis.clearTimeout(r(this,K)),d(this,K,void 0)),a(this,V,Pt).call(this,this.policy.intervalMs))}}});this.port.addEventListener("message",r(this,ot))}port;onDead;policy;side;start(){r(this,nt)||r(this,Q)||(d(this,nt,!0),a(this,V,Pt).call(this,this.policy.intervalMs))}stop(){r(this,Q)||(d(this,Q,!0),d(this,re,void 0),r(this,K)!==void 0&&(globalThis.clearTimeout(r(this,K)),d(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,Pt=function(e){r(this,Q)||d(this,K,globalThis.setTimeout(()=>a(this,V,Lt).call(this),Math.max(0,e)))},Lt=function(){if(r(this,Q))return;let e=me("heartbeat");d(this,re,e);try{this.port.postMessage({namespace:pt,version:ht,type:"ping",nonce:e})}catch(n){H("could not send a heartbeat probe",{side:this.side,misses:r(this,ie),cause:S(n)}),a(this,V,Mt).call(this,e);return}d(this,K,globalThis.setTimeout(()=>a(this,V,Mt).call(this,e),Math.max(0,this.policy.timeoutMs)))},Mt=function(e){if(!(r(this,Q)||r(this,re)!==e)){if(d(this,re,void 0),d(this,ie,r(this,ie)+1),r(this,ie)>=2){b("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}H("a heartbeat probe went unanswered",{side:this.side,misses:r(this,ie),probeTimeoutMs:this.policy.timeoutMs}),a(this,V,Lt).call(this)}},ft=function(e){r(this,Q)||(this.stop(),this.onDead(e))};import{Reply as To}from"penpal";function Co(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 wt(t){return Array.isArray(t)&&t.every(De)}function Pe(t){return Array.isArray(t)&&t.every(e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>0)}function Oo(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=>y(e)&&typeof e.message=="string"&&Oo(e.path))}function Le(t,e){try{let n=t["~standard"].validate(e);return Co(n)?(Promise.resolve(n).catch(()=>{}),c([{message:"Embedding value schemas must be synchronous.",path:[]}])):n.issues?c(n.issues.map(o=>({message:o.message,path:yo(o.path)}))):L(n.value)}catch(n){return c([{message:n instanceof Error?n.message:"The value parser rejected this value.",path:[]}])}}function yo(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 l=it(s,[...e,Array.isArray(t)?Number(i):i],n);if(l)return l}return e}}function xe(t,e){return e.map(n=>({message:n.message,path:[t,...n.path]}))}function Et(t){return Object.entries(t.fields).filter(([,e])=>e.kind==="value").map(([e])=>e)}function Sn(t,e,n){let o=new Set(t);if(n){let s=[...o].find(l=>!Object.prototype.hasOwnProperty.call(e,l));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 kn(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 gt(t,e){let n=Sn(t,e,!0);return n&&kn(n)}function kt(t,e){let n=Sn(t,e,!1);return n&&kn(n)}function Ut(t,e,n){let o;try{o=n.get()}catch(s){return b("a host value provider threw while being read",{side:"host",field:t,cause:S(s)}),c([{message:"The host value provider threw while being read.",path:[t]}])}let i=Le(e,o);if(!i.ok)return c(xe(t,i.error));try{return L(globalThis.structuredClone(i.value))}catch{let s=it(i.value)??[];return c([{message:"The host value is not structured-clone-safe.",path:[t,...s]}])}}function Tt(t,e,n){return b("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(!y(n))return c([{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 c([{message:`Unknown function input "${o}".`,path:[t,"inputs",o]}]);let i=Object.create(null);for(let[s,l]of Object.entries(e.inputs)){let u=Le(l,Object.hasOwn(n,s)?n[s]:void 0);if(!u.ok)return c(u.error.map(f=>({message:f.message,path:[t,"inputs",s,...f.path]})));i[s]=u.value}try{return L(globalThis.structuredClone(i))}catch{let s=it(i)??[];return c([{message:"The function inputs are not structured-clone-safe.",path:[t,"inputs",...s]}])}}function Un(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 Vn=Object.freeze({"~standard":{version:1,vendor:"@datadog/apps-frontend",validate(t){return Un(t)?{value:t}:{issues:[{message:"Expected a MessagePort."}]}}}});function st(t){Un(t)&&M("discarded function result MessagePort",()=>t.close())}function Nt(t,e=[]){return c([{message:"The function result is not structured-clone-safe.",path:[t,...e]}])}function Fn(t,e,n){let o=Le(e.result,n);if(!o.ok)return c(xe(t,o.error));if(e.result===Vn){let i=o.value;try{let s=globalThis.structuredClone(i,{transfer:[i]});return L(new To(L(s),{transferables:[s]}))}catch{return Nt(t)}}try{return L(L(globalThis.structuredClone(o.value)))}catch{let i=it(o.value)??[];return Nt(t,i)}}function Hn(t,e,n){let o=Le(e.result,n);if(!o.ok)return c(xe(t,o.error));if(e.result===Vn)return L(o.value);try{return L(globalThis.structuredClone(o.value))}catch{let i=it(o.value)??[];return Nt(t,i)}}import{ErrorCode as bo,PenpalError as Ro}from"penpal";function vo(t){let e=t.wanted,n=t.hostVersions;return De(e)&&wt(n)&&!n.includes(e)&&n.some(o=>o>e)}function Ao(t){let e=t.wanted,n=t.hostVersions;return De(e)&&wt(n)&&!n.includes(e)&&n.every(o=>o<e)}var xn={ORIGIN_REJECTED:t=>typeof t.origin=="string",APP_PROTOCOL_TOO_OLD:t=>Pe(t.appProtocols)&&Pe(t.hostProtocols),HOST_PROTOCOL_TOO_OLD:t=>Pe(t.appProtocols)&&Pe(t.hostProtocols),PROTOCOL_INCOMPATIBLE:t=>Pe(t.appProtocols)&&Pe(t.hostProtocols),PEER_LACKS_MODULE:t=>typeof t.identifier=="string",APP_MAJOR_TOO_OLD:vo,HOST_MAJOR_TOO_OLD:Ao,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},Io={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(y(t)&&typeof t.code=="string"){let n=t.code;if(e.includes(n)&&Object.prototype.hasOwnProperty.call(xn,n)){let o=xn[n];if(o(t)){if(n==="UNRECOGNIZED")return{code:n,rawCode:t.rawCode,raw:void 0};let i={code:n};for(let s of Io[n])i[s]=t[s];return i}}}return{code:"UNRECOGNIZED",rawCode:y(t)&&typeof t.code=="string"?t.code:"MALFORMED_ERROR",raw:void 0}}function ge(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 l=new Error(`DATADOG_APP_INPUT_FUNCTION_${i}: ${s}`,{cause:n});return l.name="DatadogAppInputFunctionError",b("a Datadog host function call failed",{side:"app",target:o,error:J(n)}),Object.assign(l,{code:i})}function jn(t,e){return y(t)&&t.code==="ABORTED"?{code:"ABORTED"}:y(t)&&t.code==="TIMED_OUT"?{code:"TIMED_OUT",timeoutMs:e}:y(t)&&t.code==="DISCONNECTED"?{code:"DISCONNECTED"}:t instanceof Ro&&t.code===bo.ConnectionTimeout?{code:"TIMED_OUT",timeoutMs:e}:{code:"TRANSPORT_FAILED",cause:t}}function Bn(t){if(!y(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 zn(t){if(!y(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(!y(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,l)=>s-l),o=n[n.length-1];if(o===void 0)return c({code:"HOST_MAJOR_TOO_OLD",wanted:t,hostVersions:n});let i=e.find(({version:s})=>s===t);return i?L(i):c(t<o?{code:"APP_MAJOR_TOO_OLD",wanted:t,hostVersions:n}:{code:"HOST_MAJOR_TOO_OLD",wanted:t,hostVersions:n})}function Wn(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 Ne,xt=class{constructor(e){this.value=e;p(this,Ne,new Set)}value;get(){return this.value}subscribe(e){return r(this,Ne).add(e),()=>{r(this,Ne).delete(e)}}set(e){return Object.is(this.value,e)?!1:(this.value=e,!0)}notify(){Ee(r(this,Ne))}freeze(){r(this,Ne).clear()}};Ne=new WeakMap;var Ht=0;function $n(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,Me,Ot,je,Bt,yt=class{constructor(e,n,o,i,s,l){this.role=e;this.remote=n;this.penpal=o;this.port=i;this.modules=s;this.operationTimeoutMs=l;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}d(this,Be,e),e.start()}send(e,n){if(this.closed)return;let o;try{o=n()}catch(l){b("an outbound embedding message could not be sent",{side:this.role,operation:e,cause:S(l)}),this.noteDisconnected();return}let i=globalThis.setTimeout(()=>{r(this,Oe).delete(i),b("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=(l,u)=>{r(this,Oe).delete(i)&&(globalThis.clearTimeout(i),l&&(b("an outbound embedding message was rejected",{side:this.role,operation:e,cause:S(u)}),this.noteDisconnected()))};o.then(()=>s(!1),l=>s(!0,l))}noteDisconnected(e=!1){this.close(e)}close(e=!0){if(r(this,ze))return;d(this,ze,!0);let n;if(e){rt(this.port);try{n=this.remote.__ddClose()}catch{}}r(this,Be)?.stop(),d(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),He)}async settleRemoteResult(e,n){return this.closed?(e.then(o=>{n.onDiscardedResult?.(o)},()=>{}),c(n.disconnectedError)):new Promise(o=>{let i=!1,s,l=m=>{i||(i=!0,s!==void 0&&globalThis.clearTimeout(s),n.signal?.removeEventListener("abort",u),this.closeSignal.removeEventListener("abort",f),o(m))},u=()=>{n.onCancel(),l(c(n.abortError))},f=()=>l(c(n.disconnectedError));if(n.signal?.addEventListener("abort",u,{once:!0}),this.closeSignal.addEventListener("abort",f,{once:!0}),n.signal?.aborted){u();return}if(this.closeSignal.aborted){f();return}s=globalThis.setTimeout(()=>{n.onCancel(),l(c(n.timeoutError(n.timeoutMs)))},Math.max(0,n.timeoutMs)),e.then(m=>{if(i){n.onDiscardedResult?.(m);return}if(y(m)&&m.ok===!0){l(L(m.value));return}n.onDiscardedResult?.(m),l(c(n.normalize(y(m)?m.error:m)))},()=>{this.noteDisconnected(),l(c(n.disconnectedError))})})}async claim(e,n={}){if(this.closed)return c({code:"DISCONNECTED"});if(n.signal?.aborted)return c({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 b("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,Me).call(this,i),this.noteDisconnected(),c({code:"DISCONNECTED"})}s=s.then(O=>O,()=>(this.noteDisconnected(),c({code:"DISCONNECTED"})));let l=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(!l.ok)return a(this,I,Me).call(this,i),l;if(!y(l.value)||!y(l.value.values))return a(this,I,Me).call(this,i),this.send("__ddRelease",()=>this.remote.__ddRelease(i)),c({code:"INVALID_RESULT",issues:[{message:"Malformed claim success payload.",path:[]}]});let u=gt(Et(e),l.value.values);if(u)return a(this,I,Me).call(this,i),this.send("__ddRelease",()=>this.remote.__ddRelease(i)),c(u);let f=new Map,m={},h={contract:e,values:f,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"){m[O]=(...T)=>this.callFunction(i,h,O,D,T);continue}let x=Le(D.schema,l.value.values[O]);if(!x.ok)return a(this,I,Me).call(this,i),this.send("__ddRelease",()=>this.remote.__ddRelease(i)),c({code:"INVALID_RESULT",issues:xe(O,x.error)});let P=new xt(x.value);f.set(O,P),m[O]=P}r(this,Te).set(i,h);let C=r(this,Z).get(i);C&&this.receiveValues(i,C);let _=h.invalidation??r(this,q).get(i);return a(this,I,Me).call(this,i),_?(a(this,I,Ot).call(this,i,h,!0,_),c(_)):L({fields:m,release:()=>a(this,I,Ot).call(this,i,h,!0),onValuesChanged:O=>h.released?()=>{}:(h.valueListeners.add(O),()=>h.valueListeners.delete(O)),onInvalidated:O=>{let D=h.invalidation;return D?(globalThis.queueMicrotask(()=>O(D)),()=>{}):h.released?()=>{}:(h.invalidationListeners.add(O),()=>h.invalidationListeners.delete(O))}})}async callFunction(e,n,o,i,s){if(this.closed)throw ge(n.contract,o,{code:"DISCONNECTED"});if(n.released)throw ge(n.contract,o,{code:"ABORTED"});if(s.length!==1)throw ge(n.contract,o,{code:"INVALID_ARGUMENT",issues:[{message:`Expected one named inputs object, received ${s.length} arguments.`,path:[o,"inputs"]}]});let l=Vt(o,i,s[0]);if(!l.ok)throw ge(n.contract,o,{code:"INVALID_ARGUMENT",issues:l.error});let u=me("call"),f;try{f=this.remote.__ddCall({claimId:e,callId:u,field:o,inputs:l.value})}catch{throw this.noteDisconnected(),ge(n.contract,o,{code:"DISCONNECTED"})}let m=await this.settleRemoteResult(f,{timeoutMs:$n(i),signal:n.releaseController.signal,onCancel:()=>{this.send("__ddCancel",()=>this.remote.__ddCancel({claimId:e,callId:u}))},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=>{y(C)&&C.ok===!0&&st(C.value)}});if(!m.ok){let C=m.error.code==="INVALID_ARGUMENT"?{code:"CONTRACT_INCOMPATIBLE",field:o}:m.error;throw ge(n.contract,o,C)}let h=Hn(o,i,m.value);if(!h.ok)throw ge(n.contract,o,{code:"INVALID_RESULT",issues:h.error});return h.value}receiveValues(e,n){if(!k(e,B)){b("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(!y(n)){let f={code:"INVALID_RESULT",issues:[{message:"The host value snapshot must be an object.",path:[]}]};o?a(this,I,je).call(this,e,o,f,!0):i?(r(this,q).set(e,f),r(this,Z).delete(e)):b("ignored a __ddValues envelope for an unknown claim",{side:this.role,claimId:e,receivedValues:typeof n});return}if(!o){if(!i)return;let m=r(this,Z).has(e)?kt(Et(i),n):gt(Et(i),n);if(m){r(this,q).set(e,m),r(this,Z).delete(e);return}if(!r(this,q).has(e)){let h=r(this,Z).get(e);r(this,Z).set(e,Object.freeze({...h,...n}))}return}let s=o.hydrated?kt(o.values.keys(),n):gt(o.values.keys(),n);if(s){a(this,I,je).call(this,e,o,s,!0);return}o.hydrated=!0;let l=[];for(let[f,m]of Object.entries(n)){let h=o.values.get(f),C=o.contract.fields[f];if(!h||!C||C.kind!=="value")continue;let _=Le(C.schema,m);if(!_.ok){let O={code:"INVALID_RESULT",issues:xe(f,_.error)};a(this,I,je).call(this,e,o,O,!0);return}l.push([h,_.value])}let u=[];for(let[f,m]of l)f.set(m)&&u.push(f);for(let f of u)f.notify();u.length>0&&Ee(o.valueListeners)}receiveInvalidation(e,n){if(!k(e,B)){b("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 c({code:"DISCONNECTED"});let n=Bn(e);if(n)return c(n);if(r(this,F).has(e.claimId))return c({code:"INVALID_RESULT",issues:[{message:`Claim id "${e.claimId}" is already live.`,path:["claimId"]}]});if(r(this,F).size>=It)return c({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 c({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 c({code:"INVALID_RESULT",issues:[{message:`The host provider for "${e.identifier}" is disposed.`,path:[]}]});let l=new Map,u={releases:[],module:s,fields:l};if(r(this,F).set(e.claimId,u),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}),u.releases.push(()=>s.signal?.removeEventListener("abort",T))}let f={},m={ready:!1},h=!1,C=!1,_=!1,O=new Set,D=new Map,x=()=>{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))},P=()=>{if(r(this,F).has(e.claimId)){if(!m.ready){h=!0;return}C||(C=!0,globalThis.queueMicrotask(x))}};for(let T of e.fields){let A=s.contract.fields[T];if(!A)return this.receiveRelease(e.claimId),c({code:"CONTRACT_INCOMPATIBLE",field:T});if(l.set(T,A),A.kind==="function"){let j=Object.hasOwn(s.implementation,T)?s.implementation[T]:void 0;if(!y(j)||typeof j.invoke!="function")return this.receiveRelease(e.claimId),c({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),c({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),P()})}catch(j){return this.receiveRelease(e.claimId),c({code:"INVALID_RESULT",issues:Tt(e.identifier,T,j)})}if(typeof W!="function")return this.receiveRelease(e.claimId),c({code:"INVALID_RESULT",issues:[{message:"The host value provider did not return an unsubscribe function.",path:[T]}]});if(r(this,F).get(e.claimId)!==u)return M(`unsubscribe for interrupted claim ${e.claimId}`,W),this.closed?c({code:"DISCONNECTED"}):c({code:"INVALID_RESULT",issues:[{message:`The host provider for "${e.identifier}" was disposed during claim setup.`,path:[]}]});u.releases.push(W);let oe=Ut(T,A.schema,U);if(!oe.ok)return this.receiveRelease(e.claimId),c({code:"INVALID_RESULT",issues:Tt(e.identifier,T,oe.error)});f[T]=oe.value}return m.ready=!0,h&&P(),L({values:f})}async receiveFunctionCall(e){if(this.closed)return c({code:"DISCONNECTED"});let n=zn(e);if(n)return c(n);let o=r(this,F).get(e.claimId);if(!o)return c({code:"DISCONNECTED"});let i=o.fields.get(e.field);if(!i||i.kind!=="function")return c({code:"CONTRACT_INCOMPATIBLE",field:e.field});if(r(this,se).has(e.callId))return c({code:"INVALID_ARGUMENT",issues:[{message:`Function call id "${e.callId}" is already active.`,path:["callId"]}]});if(Ht>=On)return c({code:"FUNCTION_FAILED",field:e.field});let s=Vt(e.field,i,e.inputs);if(!s.ok)return b("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}),c({code:"INVALID_ARGUMENT",issues:[{message:"The function inputs do not satisfy the host schema.",path:[e.field,"inputs"]}]});let l=Object.hasOwn(o.module.implementation,e.field)?o.module.implementation[e.field]:void 0;if(!y(l)||typeof l.invoke!="function")return c({code:"CONTRACT_INCOMPATIBLE",field:e.field});let u=new AbortController,f=()=>{},m=new Promise(A=>{f=A}),h={claimId:e.claimId,controller:u,interrupt(A){u.signal.aborted||(u.abort(),f({status:"interrupted",reason:A}))}};Ht+=1,r(this,se).set(e.callId,h);let C=$n(i),_=globalThis.performance.now()+C,O=globalThis.setTimeout(()=>h.interrupt("timed-out"),C),D;try{let A=l.invoke(s.value,Object.freeze({signal:u.signal}));globalThis.performance.now()>=_&&h.interrupt("timed-out"),D=Promise.resolve(A).then(U=>globalThis.performance.now()>=_?(h.interrupt("timed-out"),st(U),{status:"interrupted",reason:"timed-out"}):{status:"returned",value:U},U=>globalThis.performance.now()>=_?(h.interrupt("timed-out"),{status:"interrupted",reason:"timed-out"}):{status:"threw",cause:U})}catch(A){globalThis.performance.now()>=_&&h.interrupt("timed-out"),D=Promise.resolve({status:"threw",cause:A})}let x=D.finally(()=>{Ht-=1,r(this,se).get(e.callId)===h&&r(this,se).delete(e.callId)}),P=await Promise.race([x,m]);if(globalThis.clearTimeout(O),P.status==="interrupted")return x.then(A=>{A.status==="returned"&&st(A.value)}),P.reason==="timed-out"?c({code:"TIMED_OUT",timeoutMs:C}):c({code:"DISCONNECTED"});if(this.closed||u.signal.aborted||r(this,F).get(e.claimId)!==o)return P.status==="returned"&&st(P.value),c({code:"DISCONNECTED"});if(P.status==="threw")return b("a host function implementation threw",{side:this.role,claimId:e.claimId,callId:e.callId,target:`${o.module.contract.identifier}.${e.field}`,cause:S(P.cause)}),c({code:"FUNCTION_FAILED",field:e.field});let T=Fn(e.field,i,P.value);return T.ok?T.value:(b("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}),c({code:"INVALID_RESULT",issues:[{message:"The host function returned a result that does not satisfy its schema.",path:[e.field]}]}))}receiveFunctionCancel(e){if(!y(e)||!k(e.claimId,B)||!k(e.callId,tt)){b("ignored a malformed __ddCancel envelope",{side:this.role,request:y(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)){b("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)M(`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)||(d(this,dt,!0),M("Penpal connection",()=>this.penpal.destroy()),M("operational port",()=>this.port.close()))},Me=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"?H:b)("a live claim was invalidated",{side:this.role,claimId:e,identifier:n.contract.identifier,version:n.contract.version,observedListeners:s.length,error:J(o)}),Ee(s,o)},Bt=function(e,n){let o=r(this,F).get(e);o&&(b("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 No(t,e){if(!y(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=Wn(e,this.modules);return o?Promise.resolve(c(o)):this.endpoint.claim(e,n)}};function wo(t){return y(t)&&t.role==="host"&&Array.isArray(t.modules)}function So(t){let e=new Set,n=[];for(let o of t){if(!y(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 ko(t,e,n,o,i,s,l){let u,f,m=!1,h=!1,C,_=new Promise((E,R)=>{C=R});try{f=new mt(t,E=>{u?u.noteDisconnected(E):(m=!0,E||t.close(),C?.({code:"DISCONNECTED"}))},l,e)}catch(E){return M("failed operational port",()=>t.close()),c({code:"TRANSPORT_FAILED",cause:E})}let O=!1,D=0,x=()=>{},P=new Promise(E=>{x=E}),T=E=>{O||(O=!0,x(E))},A=(E,R)=>{let w=Y=>(H("an embedding operation was refused",{side:e,operation:R,expectedRole:E,reason:Y,pendingEndpointOperations:D}),new Error(Y));return u?u.role===E?Promise.resolve(u):Promise.reject(w("The embedding operation is not valid here.")):O||D>=yn?Promise.reject(w("The embedding endpoint is not ready for work.")):(D+=1,P.then(Y=>{if(!Y||Y.role!==E)throw w("The embedding operation is not valid here.");return Y}).finally(()=>{D-=1}))},U=e==="host"?{role:"host",modules:i.map(({contract:E})=>({identifier:E.identifier,version:E.version})),surfaceId:s}:{role:"app"},W=(E,R,w,Y)=>(Y.ok||H(`${E} was rejected`,{side:e,request:No(R,w),error:J(Y.error)}),Y),oe={__ddDescribe:()=>U,__ddClaim:E=>A("host","__ddClaim").then(R=>R.receiveClaim(E).then(w=>W("__ddClaim",E,["claimId","identifier","version","fields"],w))),__ddRelease:E=>A("host","__ddRelease").then(R=>R.receiveRelease(E)),__ddValues:(E,R)=>A("app","__ddValues").then(w=>w.receiveValues(E,R)),__ddCall:E=>A("host","__ddCall").then(R=>R.receiveFunctionCall(E).then(w=>(W("__ddCall",E,["claimId","callId","field"],w instanceof Mo?w.value:w),w))),__ddCancel:E=>A("host","__ddCancel").then(R=>R.receiveFunctionCancel(E)),__ddInvalidate:(E,R)=>A("app","__ddInvalidate").then(w=>w.receiveInvalidation(E,R)),__ddClose:()=>(u||(h=!0),A(e,"__ddClose").then(E=>E.close(!1)))},j;try{j=Po({messenger:new Lo({port:t}),methods:oe,timeout:n})}catch(E){return f.stop(),rt(t),globalThis.setTimeout(()=>t.close(),He),c({code:"TRANSPORT_FAILED",cause:E})}let ln,un,pn=()=>ln?.({code:"ABORTED"}),hn=new Promise((E,R)=>{ln=R}),fn=new Promise((E,R)=>{un=R}),co=globalThis.setTimeout(()=>un?.({code:"TIMED_OUT"}),Math.max(0,n));o.addEventListener("abort",pn,{once:!0});let At="handshake";try{if(o.aborted)throw Object.assign(new Error("The connection was aborted."),{code:"ABORTED"});let E=await Promise.race([j.promise,hn,fn,_]);At="peer-description";let R=await Promise.race([E.__ddDescribe(),hn,fn,_]);if(At="validation",!(e==="app"?wo(R):y(R)&&R.role==="app"))throw new Error(`Expected an embedding ${e==="app"?"host":"app"} using the operational protocol.`);if(u=new yt(e,E,j,t,i,n),m)throw Object.assign(new Error("The transport disconnected before establishment completed."),{code:"DISCONNECTED"});if(h)throw Object.assign(new Error("The peer requested to close before establishment completed."),{code:"DISCONNECTED"});return T(u),u.attachHeartbeat(f),L({endpoint:u,description:R})}catch(E){let R=jn(E,n);return H("the operational protocol could not be established",{side:e,stage:At,timeoutMs:n,describedPeer:!!u,error:J(R),cause:S(E)}),f.stop(),u?u.close():wn(j,t),c(R)}finally{T(void 0),globalThis.clearTimeout(co),o.removeEventListener("abort",pn)}}function Uo(t){let e=t.endpoint,n=t.description;return{connection:new Wt(e,So(n.modules)),surfaceId:typeof n.surfaceId=="string"?n.surfaceId:void 0,closeSignal:e.closeSignal,close:()=>e.close()}}async function Gn(t,e,n,o){let i=await ko(t,"app",e,n,[],void 0,o);return i.ok?L(Uo(i.value)):i}var Ho=[1];async function xo(t,e,n=1e4){if(e.aborted)return t.close(),c({code:"ABORTED"});let o=await Mn(t,Ho,n,e);return o.ok?Gn(o.value.operationalPort,n,e,Nn):o}var We,$t=class{constructor(){p(this,We)}next(){let e=r(this,We)??Tn;return d(this,We,Math.min(e*2,Cn)),e}reset(){d(this,We,void 0)}};We=new WeakMap;function jo(){return typeof globalThis.window<"u"&&globalThis.window.parent!==globalThis.window}function Bo(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,ye,$e,ke,v,Jn,Jt,Kt,Zt,Xt,bt,Kn,we,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,ye,0);p(this,$e,!1);p(this,ke,!1);if(!jo()){d(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(),d(this,ee,void 0),a(this,v,Zt).call(this),a(this,v,bt).call(this);let e=r(this,de);d(this,de,void 0),a(this,v,we).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,ye=new WeakMap,$e=new WeakMap,ke=new WeakMap,v=new WeakSet,Jn=async function(e){let n=await In(globalThis.window,_n,e);return n.ok?xo(n.value,e):n},Jt=async function(){if(r(this,ae).signal.aborted||r(this,ke)||r(this,$e)||r(this,de))return;d(this,$e,!0),d(this,ye,r(this,ye)+1);let e=new AbortController;d(this,ee,e);let n;try{n=await a(this,v,Jn).call(this,e.signal)}catch(i){n={ok:!1,error:{code:"TRANSPORT_FAILED",cause:i}}}if(d(this,$e,!1),r(this,ee)===e&&d(this,ee,void 0),r(this,ae).signal.aborted||r(this,ke)){n.ok&&n.value.close();return}if(!n.ok){if(d(this,te,n.error),!Bo(n.error)){a(this,v,bt).call(this),b("the app connection was rejected",{side:"app",attempt:r(this,ye),retryable:!1,error:J(n.error)}),a(this,v,we).call(this,{state:"rejected",error:n.error});return}a(this,v,we).call(this,r(this,z).state==="reconnecting"?{state:"reconnecting",lastError:n.error}:{state:"connecting",error:n.error}),a(this,v,Kt).call(this);return}d(this,de,n.value),d(this,te,void 0),r(this,ct).reset(),a(this,v,bt).call(this);let o=()=>{r(this,ae).signal.aborted||r(this,de)!==n.value||(d(this,de,void 0),d(this,te,{code:"DISCONNECTED"}),H("the app lost its established connection",{side:"app",attempt:r(this,ye),surfaceId:n.value.surfaceId}),a(this,v,Xt).call(this),a(this,v,we).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,we).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();H("retrying the app connection",{side:"app",state:r(this,z).state,failedAttempts:r(this,ye),retryInMs:e,giveUpAfterMs:et,error:r(this,te)&&J(r(this,te))}),d(this,ce,globalThis.setTimeout(()=>{d(this,ce,void 0),a(this,v,Jt).call(this)},e))},Zt=function(){r(this,ce)!==void 0&&(globalThis.clearTimeout(r(this,ce)),d(this,ce,void 0))},Xt=function(){r(this,le)===void 0&&d(this,le,globalThis.setTimeout(()=>{d(this,le,void 0),a(this,v,Kn).call(this)},et))},bt=function(){r(this,le)!==void 0&&(globalThis.clearTimeout(r(this,le)),d(this,le,void 0))},Kn=function(){if(r(this,ae).signal.aborted||r(this,z).state==="connected"||r(this,z).state==="closed")return;d(this,ke,!0),a(this,v,Zt).call(this),r(this,ee)?.abort(),d(this,ee,void 0);let e=r(this,te)??{code:"TIMED_OUT",timeoutMs:et};b("the app gave up connecting to its Datadog host",{side:"app",state:r(this,z).state,failedAttempts:r(this,ye),gaveUpAfterMs:et,error:J(e)}),a(this,v,we).call(this,{state:"rejected",error:e})},we=function(e){r(this,z)!==e&&(d(this,z,e),Ee(r(this,Se)))};var Zn=Object.freeze({connect(){return new Gt}});function Xn(t){return t.join(", ")}function zo(t){return t.map(e=>`${e.path.length>0?e.path.join("."):"(root)"}: ${e.message}`).join("; ")}function Wo(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 (${Wo(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 ${Xn(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 ${Xn(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 $o=0,Go=Object.freeze({status:"pending"}),Jo=Object.freeze({status:"unavailable"}),Ko=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."}),Yn=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 Go}function Qn(){return Jo}function Zo(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)),d(this,pe,void 0));let n=()=>e();r(this,Re).add(n),r(this,ve)||(d(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&&d(this,pe,globalThis.setTimeout(()=>{d(this,pe,void 0),r(this,Re).size===0&&r(this,ve)&&(d(this,ve,!1),this.owner.deactivate(this.resource))},$o)))}})}owner;resource;notify(){Ee(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,g,qn,eo,to,on,Ge,be,ue,Ue,nn=class{constructor(e,n){p(this,g);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));d(this,$,n),d(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,g,be).call(this),d(this,G,e.connection),a(this,g,Ue).call(this,en()),a(this,g,qn).call(this,e.connection);return;case"connecting":case"reconnecting":this.reset();return;case"not-embedded":d(this,G,void 0),a(this,g,be).call(this),a(this,g,Ue).call(this,Qn());return;case"rejected":d(this,G,void 0),a(this,g,be).call(this),a(this,g,ue).call(this,Yt(e.error));return;case"closed":d(this,G,void 0),a(this,g,be).call(this),a(this,g,ue).call(this,Ko);return;default:return e}}fail(e){d(this,G,void 0),a(this,g,be).call(this),a(this,g,ue).call(this,e)}reset(){d(this,G,void 0),a(this,g,be).call(this),a(this,g,Ue).call(this,en())}};Ae=new WeakMap,$=new WeakMap,Ie=new WeakMap,G=new WeakMap,ne=new WeakMap,he=new WeakMap,Je=new WeakMap,g=new WeakSet,qn=function(e){let n=new AbortController;d(this,ne,n);let o;try{o=e.claim(r(this,$),{signal:n.signal})}catch(i){b("a claim could not be requested",{side:"app",identifier:r(this,$).identifier,current:a(this,g,Ge).call(this,e,n),cause:S(i)}),a(this,g,Ge).call(this,e,n)&&(d(this,ne,void 0),a(this,g,ue).call(this,qt));return}o.then(i=>{if(!a(this,g,Ge).call(this,e,n)){i.ok&&i.value.release();return}if(d(this,ne,void 0),!i.ok){if(i.error.code==="PEER_LACKS_MODULE"){H("the Datadog host does not offer this module",{side:"app",identifier:r(this,$).identifier,version:r(this,$).version}),a(this,g,Ue).call(this,Qn());return}if(i.error.code==="ABORTED"){a(this,g,ue).call(this,qt);return}a(this,g,ue).call(this,Qt(i.error));return}a(this,g,eo).call(this,e,i.value)},i=>{b("a claim request rejected",{side:"app",identifier:r(this,$).identifier,current:a(this,g,Ge).call(this,e,n),cause:S(i)}),a(this,g,Ge).call(this,e,n)&&(d(this,ne,void 0),a(this,g,ue).call(this,qt))})},eo=function(e,n){if(!r(this,Ae).isActive||r(this,G)!==e||r(this,he)){n.release();return}d(this,he,n),r(this,Je).push(n.onInvalidated(o=>a(this,g,to).call(this,n,o))),r(this,Je).push(n.onValuesChanged(()=>{r(this,he)===n&&a(this,g,on).call(this,n)})),a(this,g,on).call(this,n)},to=function(e,n){if(r(this,he)!==e)return;let o=Qt(n);a(this,g,be).call(this),a(this,g,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,l]of n){let u=e.fields[s];i[s]=l.kind==="value"?u.get():u}if(r(this,Ie).status==="ready"){let s=r(this,Ie).fields;if(o.every(l=>Object.is(s[l],i[l])))return}a(this,g,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},be=function(){r(this,ne)?.abort(),d(this,ne,void 0);for(let n of r(this,Je).splice(0))n();let e=r(this,he);d(this,he,void 0),e?.release()},ue=function(e){b("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,g,Ue).call(this,Zo(e))},Ue=function(e){r(this,Ie)!==e&&(d(this,Ie,e),r(this,Ae).notify())};var tn=Object.freeze({state:"connecting"});function Xo(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));d(this,Ke,new vt(e,this))}sync(e){a(this,Xe,Rt).call(this,e?Xo(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&&(d(this,Ze,e),r(this,Ke).notify())};var lt,X,ut,fe,Ye,_e,Qe,Ve,N,no,oo,ro,io,an,dn,cn,sn=class{constructor(e){this.connector=e;p(this,N);p(this,lt,new WeakMap);p(this,X,new Set);p(this,ut,{activate:e=>a(this,N,ro).call(this,e),deactivate:e=>a(this,N,io).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)||d(this,Qe,new rn(r(this,ut))),r(this,Qe)}start(){d(this,Ve,r(this,Ve)+1),r(this,Ve)===1&&a(this,N,no).call(this);let e=!0;return()=>{e&&(e=!1,d(this,Ve,r(this,Ve)-1),r(this,Ve)===0&&a(this,N,oo).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,N=new WeakSet,no=function(){d(this,_e,void 0);for(let n of r(this,X))n.reset();let e;try{e=this.connector.connect()}catch(n){a(this,N,cn).call(this,"connect",n);return}d(this,fe,e);try{d(this,Ye,e.subscribe(()=>a(this,N,an).call(this,e))),a(this,N,an).call(this,e)}catch(n){a(this,N,dn).call(this,e),a(this,N,cn).call(this,"subscribe",n);return}},oo=function(){let e=r(this,fe);e&&a(this,N,dn).call(this,e),d(this,_e,void 0);for(let n of r(this,X))n.reset()},ro=function(e){if(r(this,X).add(e),r(this,_e)){e.fail(r(this,_e));return}e.sync(r(this,fe)?.getSnapshot())},io=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;d(this,fe,void 0);let n=r(this,Ye);d(this,Ye,void 0),n&&M("embedding connection handle unsubscribe",()=>n());for(let o of r(this,X))M("embedding claim resource reset",()=>o.reset());M("embedding connection handle close",()=>e.close())},cn=function(e,n){b("the embedding connection could not be started",{side:"app",step:e,affectedResources:r(this,X).size,cause:S(n)}),d(this,_e,Yn);for(let o of r(this,X))o.fail(Yn)};function so(t){return new sn(t)}var ao=so(Zn),er=bn(ao),tr=Object.freeze([]),Ei=({children:t,modules:e=tr})=>{let[n]=qo(()=>e);return Qo(()=>{let o=new AbortController;return mn(n,ao,o.signal),()=>o.abort()},[n]),Yo(er,null,t)};export{Ei as a};
7
- //# sourceMappingURL=chunk-VVRISDII.js.map