@datadog/apps-frontend 0.0.2 → 0.0.4

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.
@@ -3,5 +3,5 @@
3
3
  * Copyright 2019-Present Datadog, Inc.
4
4
  */
5
5
 
6
- var so=Object.defineProperty;var mn=t=>{throw TypeError(t)};var ao=(t,e,n)=>e in t?so(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var xe=(t,e,n)=>ao(t,typeof e!="symbol"?e+"":e,n),Rt=(t,e,n)=>e.has(t)||mn("Cannot "+n);var r=(t,e,n)=>(Rt(t,e,"read from private field"),n?n.call(t):e.get(t)),p=(t,e,n)=>e.has(t)?mn("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),d=(t,e,n,o)=>(Rt(t,e,"write to private field"),o?o.call(t,n):e.set(t,n),n),a=(t,e,n)=>(Rt(t,e,"access private method"),n);var co="[Datadog Apps embedding]";function _(t,e=0){if(!(t instanceof Error))return t;try{let n={name:t.name,message:t.message};return typeof t.stack=="string"&&(n.stack=t.stack),t.cause!==void 0&&(n.cause=e<3?_(t.cause,e+1):"(cause chain truncated)"),n}catch{return"(cause could not be described)"}}function J(t){return"cause"in t?{...t,cause:_(t.cause)}:t}function gn(t,e,n){try{globalThis.console?.[t](`${co} ${e}`,n)}catch{}}function U(t,e={}){gn("warn",t,e)}function O(t,e={}){gn("error",t,e)}var En=0;function me(t){return En+=1,`${t}:${lo()}:${En.toString(36)}`}function lo(){let t=new Uint8Array(8);globalThis.crypto.getRandomValues(t);let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}function N(t){return{ok:!0,value:t}}function u(t){return{ok:!1,error:t}}function b(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function L(t,e){return typeof t=="string"&&t.length>0&&(e===void 0||t.length<=e)}function P(t,e){try{e()}catch(n){O("a teardown step failed",{description:t,cause:_(n)})}}function ge(t,...e){for(let n of[...t])try{n(...e)}catch(o){O("an embedding listener threw",{cause:_(o)}),globalThis.queueMicrotask(()=>{throw o})}}var uo=/^https:\/\/(?:[a-zA-Z0-9-]+\.)*(?:datadoghq\.(?:com|eu)|ddog-gov\.com)$/,po=/^https:\/\/(?:[a-zA-Z0-9-]+\.)*(?:datad0g\.com|staging\.dog|prod\.dog)$/,ho=/^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/;function Tn(t){return uo.test(t)||po.test(t)||ho.test(t)}var yn="dd-apps-frontend-bootstrap",Cn=1,fo=1e4;function mo(t,e,n){let{data:o}=n;return n.source!==t||n.ports.length!==0||!b(o)||o.namespace!==yn||o.version!==Cn||o.type!=="accepted"&&o.type!=="rejected-origin"||o.attemptId!==e?{status:"ignored"}:Tn(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 bn(t,e,n,o=fo){if(n.aborted)return Promise.resolve(u({code:"ABORTED"}));let i=t.parent;if(i===t)return Promise.resolve(u({code:"TRANSPORT_FAILED",cause:new Error("The app is not running in an iframe.")}));let s=me("bootstrap"),l=new MessageChannel;return new Promise(c=>{let f=!1,h=!1,y=!1,C,T=M=>{f||(f=!0,t.removeEventListener("message",I),n.removeEventListener("abort",S),C!==void 0&&globalThis.clearTimeout(C),M.ok||(P("failed app bootstrap port",()=>l.port1.close()),h||P("untransferred app bootstrap port",()=>l.port2.close())),c(M))},I=M=>{let m=mo(i,s,M);m.status==="accepted"?T(N(l.port1)):m.status==="rejected-origin"&&T(u({code:"ORIGIN_REJECTED",origin:m.origin}))},S=()=>T(u({code:"ABORTED"})),k=()=>{if(!(y||f)){y=!0,C=globalThis.setTimeout(()=>T(u({code:"TIMED_OUT",timeoutMs:o})),Math.max(0,o));try{i.postMessage({namespace:yn,version:Cn,type:"request",attemptId:s,documentId:e},"*",[l.port2]),h=!0}catch(M){T(u({code:"TRANSPORT_FAILED",cause:M}))}}};if(t.addEventListener("message",I),n.addEventListener("abort",S,{once:!0}),n.aborted){S();return}k()})}var On=me("document");var vn="dd-apps-frontend-compatibility",An=1,go=64;function Eo(t,e,n,o){return n.aborted?Promise.resolve({ok:!1,error:{code:"ABORTED"}}):new Promise(i=>{let s=!1,l,c=y=>{s||(s=!0,t.removeEventListener("message",f),n.removeEventListener("abort",h),l!==void 0&&globalThis.clearTimeout(l),i(y))},f=y=>c({ok:!0,value:y}),h=()=>c({ok:!1,error:{code:"ABORTED"}});t.addEventListener("message",f),n.addEventListener("abort",h,{once:!0}),l=globalThis.setTimeout(()=>c({ok:!1,error:{code:"TIMED_OUT",timeoutMs:e}}),Math.max(0,e));try{t.start(),o?.()}catch(y){c({ok:!1,error:{code:"TRANSPORT_FAILED",cause:y}})}})}function Rn(t){if(!(!Array.isArray(t)||t.length===0||t.length>go||!Array.from(t).every(e=>Number.isSafeInteger(e)&&e>0)||new Set(t).size!==t.length))return[...t].sort((e,n)=>e-n)}function To(t,e){let n=t.filter(c=>e.includes(c));if(n.length>0)return{ok:!0,value:Math.max(...n)};let o=Math.min(...t),i=Math.max(...t),s=Math.min(...e),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 In(t,e,n,o){let i=Rn(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:vn,version:An,type:"offer",role:"app",protocols:i})});if(t.close(),!s.ok)return s;let{data:l,ports:c}=s.value;if(!b(l)||l.namespace!==vn||l.version!==An||l.type!=="answer"||l.role!=="host"){for(let C of c)C.close();return{ok:!1,error:{code:"TRANSPORT_FAILED",cause:new Error("The host returned an invalid compatibility answer.")}}}let f=Rn(l.protocols);if(!f){for(let C of c)C.close();return{ok:!1,error:{code:"TRANSPORT_FAILED",cause:new Error("The host returned an invalid supported-protocol list.")}}}let h=To(i,f);if(!h.ok){for(let C of c)C.close();return h}let[y]=c;if(c.length!==1||y===void 0){for(let C of c)C.close();return{ok:!1,error:{code:"TRANSPORT_FAILED",cause:new Error("A compatible host must transfer exactly one operational port.")}}}return{ok:!0,value:{protocol:h.value,operationalPort:y}}}import{connect as Mo,PortMessenger as Lo}from"penpal";var dt="dd-apps-frontend-heartbeat",ct=1,et=250,_n=Object.freeze({intervalMs:1e4,timeoutMs:5e3});function tt(t){try{t.postMessage({namespace:dt,version:ct,type:"close"})}catch{}}function Dn(t,e){tt(e),globalThis.setTimeout(()=>{P("failed Penpal connection",()=>t.destroy()),P("failed operational port",()=>e.close())},et)}var X,re,ie,Qe,Q,qe,F,Dt,wt,St,lt,ut=class{constructor(e,n,o,i){this.port=e;this.onDead=n;this.policy=o;this.side=i;p(this,F);p(this,X);p(this,re);p(this,ie,0);p(this,Qe,!1);p(this,Q,!1);p(this,qe,e=>{let n=e.data;if(!(!b(n)||n.namespace!==dt||n.version!==ct)){if(n.type==="close"){a(this,F,lt).call(this);return}if(L(n.nonce)){if(n.type==="ping"){try{this.port.postMessage({namespace:dt,version:ct,type:"pong",nonce:n.nonce})}catch(o){O("could not answer a heartbeat probe",{side:this.side,cause:_(o)}),a(this,F,lt).call(this)}return}n.type!=="pong"||n.nonce!==r(this,re)||(d(this,re,void 0),d(this,ie,0),r(this,X)!==void 0&&(globalThis.clearTimeout(r(this,X)),d(this,X,void 0)),a(this,F,Dt).call(this,this.policy.intervalMs))}}});this.port.addEventListener("message",r(this,qe))}port;onDead;policy;side;start(){r(this,Qe)||r(this,Q)||(d(this,Qe,!0),a(this,F,Dt).call(this,this.policy.intervalMs))}stop(){r(this,Q)||(d(this,Q,!0),d(this,re,void 0),r(this,X)!==void 0&&(globalThis.clearTimeout(r(this,X)),d(this,X,void 0)),this.port.removeEventListener("message",r(this,qe)))}};X=new WeakMap,re=new WeakMap,ie=new WeakMap,Qe=new WeakMap,Q=new WeakMap,qe=new WeakMap,F=new WeakSet,Dt=function(e){r(this,Q)||d(this,X,globalThis.setTimeout(()=>a(this,F,wt).call(this),Math.max(0,e)))},wt=function(){if(r(this,Q))return;let e=me("heartbeat");d(this,re,e);try{this.port.postMessage({namespace:dt,version:ct,type:"ping",nonce:e})}catch(n){U("could not send a heartbeat probe",{side:this.side,misses:r(this,ie),cause:_(n)}),a(this,F,St).call(this,e);return}d(this,X,globalThis.setTimeout(()=>a(this,F,St).call(this,e),Math.max(0,this.policy.timeoutMs)))},St=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){O("the peer stopped answering heartbeats",{side:this.side,misses:r(this,ie),probeTimeoutMs:this.policy.timeoutMs,intervalMs:this.policy.intervalMs}),a(this,F,lt).call(this);return}U("a heartbeat probe went unanswered",{side:this.side,misses:r(this,ie),probeTimeoutMs:this.policy.timeoutMs}),a(this,F,wt).call(this)}},lt=function(){r(this,Q)||(this.stop(),this.onDead())};function Mt(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 Lt(t){return Array.isArray(t)&&t.every(De)}function we(t){return Array.isArray(t)&&t.every(e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>0)}function yo(t){return Array.isArray(t)&&t.every(e=>typeof e=="string"||typeof e=="number"&&Number.isSafeInteger(e)&&e>=0)}function Nt(t){return Array.isArray(t)&&t.every(e=>b(e)&&typeof e.message=="string"&&yo(e.path))}function Ue(t,e){try{let n=t["~standard"].validate(e);return Mt(n)?(Promise.resolve(n).catch(()=>{}),u([{message:"Embedding value schemas must be synchronous.",path:[]}])):n.issues?u(n.issues.map(o=>({message:o.message,path:Co(o.path)}))):N(n.value)}catch(n){return u([{message:n instanceof Error?n.message:"The value parser rejected this value.",path:[]}])}}function Co(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 pt(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=pt(s,[...e,Array.isArray(t)?Number(i):i],n);if(l)return l}return e}}function nt(t,e){return e.map(n=>({message:n.message,path:[t,...n.path]}))}function ht(t){return Object.entries(t.fields).filter(([,e])=>e.kind==="value").map(([e])=>e)}function wn(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 Sn(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 ft(t,e){let n=wn(t,e,!0);return n&&Sn(n)}function Pt(t,e){let n=wn(t,e,!1);return n&&Sn(n)}function kt(t,e,n){let o;try{o=n.get()}catch(s){return O("a host value provider threw while being read",{side:"host",field:t,cause:_(s)}),u([{message:"The host value provider threw while being read.",path:[t]}])}let i=Ue(e,o);if(!i.ok)return u(nt(t,i.error));try{return N(globalThis.structuredClone(i.value))}catch{let s=pt(i.value)??[];return u([{message:"The host value is not structured-clone-safe.",path:[t,...s]}])}}function mt(t,e,n){return O("a host value could not be provided",{side:"host",target:`${t}.${e}`,details:_(n)}),[{message:"The host could not provide a value that satisfies this field schema.",path:[e]}]}function Ft(t,e,n){if(!b(n))return u([{message:"Expected a named inputs object.",path:[t,"inputs"]}]);let i=Object.keys(e.inputs).find(c=>!Object.prototype.hasOwnProperty.call(n,c)),s=Object.keys(n).find(c=>!Object.prototype.hasOwnProperty.call(e.inputs,c));if(i!==void 0||s!==void 0){let c=i??s??"(unknown)";return u([{message:i!==void 0?`Missing function input "${i}".`:`Unknown function input "${s}".`,path:[t,"inputs",c]}])}let l=Object.create(null);for(let[c,f]of Object.entries(e.inputs)){let h=Ue(f,n[c]);if(!h.ok)return u(h.error.map(y=>({message:y.message,path:[t,"inputs",c,...y.path]})));l[c]=h.value}try{return N(globalThis.structuredClone(l))}catch{let c=pt(l)??[];return u([{message:"The function inputs are not structured-clone-safe.",path:[t,"inputs",...c]}])}}function Vt(t,e,n){let o=Ue(e.result,n);if(!o.ok)return u(nt(t,o.error));try{return N(globalThis.structuredClone(o.value))}catch{let i=pt(o.value)??[];return u([{message:"The function result is not structured-clone-safe.",path:[t,...i]}])}}import{ErrorCode as bo,PenpalError as Oo}from"penpal";function vo(t){let e=t.wanted,n=t.hostVersions;return De(e)&&Lt(n)&&!n.includes(e)&&n.some(o=>o>e)}function Ao(t){let e=t.wanted,n=t.hostVersions;return De(e)&&Lt(n)&&!n.includes(e)&&n.every(o=>o<e)}var Mn={ORIGIN_REJECTED:t=>typeof t.origin=="string",APP_PROTOCOL_TOO_OLD:t=>we(t.appProtocols)&&we(t.hostProtocols),HOST_PROTOCOL_TOO_OLD:t=>we(t.appProtocols)&&we(t.hostProtocols),PROTOCOL_INCOMPATIBLE:t=>we(t.appProtocols)&&we(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=>Nt(t.issues),FUNCTION_FAILED:t=>typeof t.field=="string",INVALID_RESULT:t=>Nt(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},Ro={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 Et(t,e){if(b(t)&&typeof t.code=="string"){let n=t.code;if(e.includes(n)&&Object.prototype.hasOwnProperty.call(Mn,n)){let o=Mn[n];if(o(t)){if(n==="UNRECOGNIZED")return{code:n,rawCode:t.rawCode,raw:void 0};let i={code:n};for(let s of Ro[n])i[s]=t[s];return i}}}return{code:"UNRECOGNIZED",rawCode:b(t)&&typeof t.code=="string"?t.code:"MALFORMED_ERROR",raw:void 0}}function Ee(t,e,n){let o=`${t.identifier}.${e}`,i=n.code==="UNRECOGNIZED"?"UNKNOWN":n.code,s;switch(n.code){case"INVALID_ARGUMENT":s=`The inputs passed to "${o}" are invalid: ${n.issues[0]?.message??"the schema rejected them"}.`;break;case"INVALID_RESULT":s=`Datadog returned an invalid result from "${o}": ${n.issues[0]?.message??"the schema rejected it"}. The app and host may be using incompatible schema implementations.`;break;case"FUNCTION_FAILED":s=`Datadog could not complete "${o}". Screenshot this message and contact support if the problem continues.`;break;case"TIMED_OUT":s=`"${o}" did not finish within ${n.timeoutMs} ms. It may still complete in Datadog; do not automatically retry an action that is not idempotent.`;break;case"CONTRACT_INCOMPATIBLE":s=`The Datadog host contract for "${o}" does not match the schema compiled into this app. Update the app or contact support.`;break;case"ABORTED":s=`The inputs used by "${o}" were released before it completed. Its outcome is unknown; wait for the inputs to become ready before calling it again.`;break;case"DISCONNECTED":s=`The Datadog connection closed before "${o}" completed. Its outcome is unknown; reconnect before trying again.`;break;case"UNRECOGNIZED":s=`Datadog returned an unrecognized failure for "${o}" (${n.rawCode}). Screenshot this message and contact support.`;break;default:s=n}let l=new Error(`DATADOG_APP_INPUT_FUNCTION_${i}: ${s}`,{cause:n});return l.name="DatadogAppInputFunctionError",O("a Datadog host function call failed",{side:"app",target:o,error:J(n)}),Object.assign(l,{code:i})}function Ln(t,e){return b(t)&&t.code==="ABORTED"?{code:"ABORTED"}:b(t)&&t.code==="TIMED_OUT"?{code:"TIMED_OUT",timeoutMs:e}:b(t)&&t.code==="DISCONNECTED"?{code:"DISCONNECTED"}:t instanceof Oo&&t.code===bo.ConnectionTimeout?{code:"TIMED_OUT",timeoutMs:e}:{code:"TRANSPORT_FAILED",cause:t}}function Nn(t){if(!b(t))return{code:"INVALID_RESULT",issues:[{message:"Malformed __ddClaim envelope: expected an object.",path:[]}]};if(!L(t.claimId,256))return{code:"INVALID_RESULT",issues:[{message:`"claimId" must contain between 1 and ${256} characters.`,path:["claimId"]}]};if(!L(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>128)return{code:"INVALID_RESULT",issues:[{message:`"fields" must contain between 1 and ${128} entries.`,path:["fields"]}]};if(!t.fields.every(e=>typeof e=="string"&&e.length>0&&e.length<=256)||new Set(t.fields).size!==t.fields.length)return{code:"INVALID_RESULT",issues:[{message:`"fields" must contain unique non-empty strings of at most ${256} characters.`,path:["fields"]}]}}function Pn(t){if(!b(t))return{code:"INVALID_ARGUMENT",issues:[{message:"Malformed __ddCall envelope: expected an object.",path:[]}]};if(!L(t.claimId,256))return{code:"INVALID_ARGUMENT",issues:[{message:`"claimId" must contain between 1 and ${256} characters.`,path:["claimId"]}]};if(!L(t.callId,256))return{code:"INVALID_ARGUMENT",issues:[{message:`"callId" must contain between 1 and ${256} characters.`,path:["callId"]}]};if(!L(t.field))return{code:"INVALID_ARGUMENT",issues:[{message:'"field" must be a non-empty string.',path:["field"]}]};if(!b(t.inputs))return{code:"INVALID_ARGUMENT",issues:[{message:'"inputs" must be an object.',path:["inputs"]}]}}function xt(t,e){let n=e.map(({version:s})=>s).sort((s,l)=>s-l),o=n[n.length-1];if(o===void 0)return u({code:"HOST_MAJOR_TOO_OLD",wanted:t,hostVersions:n});let i=e.find(({version:s})=>s===t);return i?N(i):u(t<o?{code:"APP_MAJOR_TOO_OLD",wanted:t,hostVersions:n}:{code:"HOST_MAJOR_TOO_OLD",wanted:t,hostVersions:n})}function kn(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=xt(t.version,n);return o.ok?void 0:o.error}var Me,Ht=class{constructor(e){this.value=e;p(this,Me,new Set)}value;get(){return this.value}subscribe(e){return r(this,Me).add(e),()=>{r(this,Me).delete(e)}}set(e){return Object.is(this.value,e)?!1:(this.value=e,!0)}notify(){ge(r(this,Me))}freeze(){r(this,Me).clear()}};Me=new WeakMap;var Ut=0,ot,V,se,Te,ye,K,q,Ce,je,Be,rt,R,jt,Se,Tt,He,Bt,yt=class{constructor(e,n,o,i,s,l,c){this.role=e;this.remote=n;this.penpal=o;this.port=i;this.modules=s;this.operationTimeoutMs=l;this.functionCallTimeoutMs=c;p(this,R);p(this,ot,new AbortController);p(this,V,new Map);p(this,se,new Map);p(this,Te,new Map);p(this,ye,new Map);p(this,K,new Map);p(this,q,new Map);p(this,Ce,new Set);p(this,je);p(this,Be,!1);p(this,rt,!1)}role;remote;penpal;port;modules;operationTimeoutMs;functionCallTimeoutMs;get closed(){return r(this,Be)}get closeSignal(){return r(this,ot).signal}attachHeartbeat(e){if(this.closed){e.stop();return}d(this,je,e),e.start()}send(e,n){if(this.closed)return;let o;try{o=n()}catch(l){O("an outbound embedding message could not be sent",{side:this.role,operation:e,cause:_(l)}),this.noteDisconnected();return}let i=globalThis.setTimeout(()=>{r(this,Ce).delete(i),O("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,Ce).add(i);let s=(l,c)=>{r(this,Ce).delete(i)&&(globalThis.clearTimeout(i),l&&(O("an outbound embedding message was rejected",{side:this.role,operation:e,cause:_(c)}),this.noteDisconnected()))};o.then(()=>s(!1),l=>s(!0,l))}noteDisconnected(){this.close(!1)}close(e=!0){if(r(this,Be))return;d(this,Be,!0);let n;if(e){tt(this.port);try{n=this.remote.__ddClose()}catch{}}r(this,je)?.stop(),d(this,je,void 0);for(let o of r(this,Ce))globalThis.clearTimeout(o);r(this,Ce).clear(),r(this,ot).abort();for(let o of[...r(this,V).keys()])this.receiveRelease(o);for(let[o,i]of[...r(this,Te).entries()])a(this,R,He).call(this,o,i,{code:"DISCONNECTED"},!1);if(r(this,ye).clear(),r(this,K).clear(),r(this,q).clear(),!n){a(this,R,jt).call(this);return}n.catch(()=>{}),globalThis.setTimeout(()=>a(this,R,jt).call(this),et)}async settleRemoteResult(e,n){return this.closed?u(n.disconnectedError):new Promise(o=>{let i=!1,s,l=h=>{i||(i=!0,s!==void 0&&globalThis.clearTimeout(s),n.signal?.removeEventListener("abort",c),this.closeSignal.removeEventListener("abort",f),o(h))},c=()=>{n.onCancel(),l(u(n.abortError))},f=()=>l(u(n.disconnectedError));if(n.signal?.addEventListener("abort",c,{once:!0}),this.closeSignal.addEventListener("abort",f,{once:!0}),n.signal?.aborted){c();return}if(this.closeSignal.aborted){f();return}s=globalThis.setTimeout(()=>{n.onCancel(),l(u(n.timeoutError(n.timeoutMs)))},Math.max(0,n.timeoutMs)),e.then(h=>{if(b(h)&&h.ok===!0){l(N(h.value));return}l(u(n.normalize(b(h)?h.error:h)))},()=>{this.noteDisconnected(),l(u(n.disconnectedError))})})}async claim(e,n={}){if(this.closed)return u({code:"DISCONNECTED"});if(n.signal?.aborted)return u({code:"ABORTED"});let o=me("claim");r(this,ye).set(o,e);let i;try{i=this.remote.__ddClaim({claimId:o,identifier:e.identifier,version:e.version,fields:Object.keys(e.fields)})}catch(T){return O("a claim could not be sent to the Datadog host",{side:this.role,claimId:o,identifier:e.identifier,version:e.version,cause:_(T)}),a(this,R,Se).call(this,o),this.noteDisconnected(),u({code:"DISCONNECTED"})}i=i.then(T=>T,()=>(this.noteDisconnected(),u({code:"DISCONNECTED"})));let s=await this.settleRemoteResult(i,{timeoutMs:n.timeoutMs??5e3,signal:n.signal,onCancel:()=>{this.send("__ddRelease",()=>this.remote.__ddRelease(o))},timeoutError:T=>({code:"TIMED_OUT",timeoutMs:T}),abortError:{code:"ABORTED"},disconnectedError:{code:"DISCONNECTED"},normalize:T=>Et(T,["PEER_LACKS_MODULE","APP_MAJOR_TOO_OLD","HOST_MAJOR_TOO_OLD","CONTRACT_INCOMPATIBLE","INVALID_RESULT","TIMED_OUT","ABORTED","DISCONNECTED","UNRECOGNIZED"])});if(!s.ok)return a(this,R,Se).call(this,o),s;if(!b(s.value)||!b(s.value.values))return a(this,R,Se).call(this,o),this.send("__ddRelease",()=>this.remote.__ddRelease(o)),u({code:"INVALID_RESULT",issues:[{message:"Malformed claim success payload.",path:[]}]});let l=ft(ht(e),s.value.values);if(l)return a(this,R,Se).call(this,o),this.send("__ddRelease",()=>this.remote.__ddRelease(o)),u(l);let c=new Map,f={},h={contract:e,values:c,valueListeners:new Set,invalidationListeners:new Set,releaseController:new AbortController,released:!1,hydrated:!1};for(let[T,I]of Object.entries(e.fields)){if(I.kind==="function"){f[T]=(...M)=>this.callFunction(o,h,T,I,M);continue}let S=Ue(I.schema,s.value.values[T]);if(!S.ok)return a(this,R,Se).call(this,o),this.send("__ddRelease",()=>this.remote.__ddRelease(o)),u({code:"INVALID_RESULT",issues:nt(T,S.error)});let k=new Ht(S.value);c.set(T,k),f[T]=k}r(this,Te).set(o,h);let y=r(this,K).get(o);y&&this.receiveValues(o,y);let C=h.invalidation??r(this,q).get(o);return a(this,R,Se).call(this,o),C?(a(this,R,Tt).call(this,o,h,!0,C),u(C)):N({fields:f,release:()=>a(this,R,Tt).call(this,o,h,!0),onValuesChanged:T=>h.released?()=>{}:(h.valueListeners.add(T),()=>h.valueListeners.delete(T)),onInvalidated:T=>{let I=h.invalidation;return I?(globalThis.queueMicrotask(()=>T(I)),()=>{}):h.released?()=>{}:(h.invalidationListeners.add(T),()=>h.invalidationListeners.delete(T))}})}async callFunction(e,n,o,i,s){if(this.closed)throw Ee(n.contract,o,{code:"DISCONNECTED"});if(n.released)throw Ee(n.contract,o,{code:"ABORTED"});if(s.length!==1)throw Ee(n.contract,o,{code:"INVALID_ARGUMENT",issues:[{message:`Expected one named inputs object, received ${s.length} arguments.`,path:[o,"inputs"]}]});let l=Ft(o,i,s[0]);if(!l.ok)throw Ee(n.contract,o,{code:"INVALID_ARGUMENT",issues:l.error});let c=me("call"),f;try{f=this.remote.__ddCall({claimId:e,callId:c,field:o,inputs:l.value})}catch{throw this.noteDisconnected(),Ee(n.contract,o,{code:"DISCONNECTED"})}let h=await this.settleRemoteResult(f,{timeoutMs:this.functionCallTimeoutMs!==void 0?this.functionCallTimeoutMs+250:this.operationTimeoutMs,signal:n.releaseController.signal,onCancel:()=>{this.send("__ddCancel",()=>this.remote.__ddCancel({claimId:e,callId:c}))},timeoutError:C=>({code:"TIMED_OUT",timeoutMs:C}),abortError:{code:"ABORTED"},disconnectedError:{code:"DISCONNECTED"},normalize:C=>Et(C,["CONTRACT_INCOMPATIBLE","INVALID_ARGUMENT","FUNCTION_FAILED","INVALID_RESULT","TIMED_OUT","ABORTED","DISCONNECTED","UNRECOGNIZED"])});if(!h.ok){let C=h.error.code==="INVALID_ARGUMENT"?{code:"CONTRACT_INCOMPATIBLE",field:o}:h.error;throw Ee(n.contract,o,C)}let y=Vt(o,i,h.value);if(!y.ok)throw Ee(n.contract,o,{code:"INVALID_RESULT",issues:y.error});return y.value}receiveValues(e,n){if(!L(e,256)){O("ignored a __ddValues envelope with an invalid claim id",{side:this.role,claimId:e,maxClaimIdLength:256});return}let o=r(this,Te).get(e),i=r(this,ye).get(e);if(!b(n)){let f={code:"INVALID_RESULT",issues:[{message:"The host value snapshot must be an object.",path:[]}]};o?a(this,R,He).call(this,e,o,f,!0):i?(r(this,q).set(e,f),r(this,K).delete(e)):O("ignored a __ddValues envelope for an unknown claim",{side:this.role,claimId:e,receivedValues:typeof n});return}if(!o){if(!i)return;let h=r(this,K).has(e)?Pt(ht(i),n):ft(ht(i),n);if(h){r(this,q).set(e,h),r(this,K).delete(e);return}if(!r(this,q).has(e)){let y=r(this,K).get(e);r(this,K).set(e,Object.freeze({...y,...n}))}return}let s=o.hydrated?Pt(o.values.keys(),n):ft(o.values.keys(),n);if(s){a(this,R,He).call(this,e,o,s,!0);return}o.hydrated=!0;let l=[];for(let[f,h]of Object.entries(n)){let y=o.values.get(f),C=o.contract.fields[f];if(!y||!C||C.kind!=="value")continue;let T=Ue(C.schema,h);if(!T.ok){let I={code:"INVALID_RESULT",issues:nt(f,T.error)};a(this,R,He).call(this,e,o,I,!0);return}l.push([y,T.value])}let c=[];for(let[f,h]of l)f.set(h)&&c.push(f);for(let f of c)f.notify();c.length>0&&ge(o.valueListeners)}receiveInvalidation(e,n){if(!L(e,256)){O("ignored a __ddInvalidate envelope with an invalid claim id",{side:this.role,claimId:e,maxClaimIdLength:256});return}let o=Et(n,["INVALID_RESULT","UNRECOGNIZED"]),i=r(this,Te).get(e);if(i){a(this,R,He).call(this,e,i,o,!1);return}r(this,ye).has(e)&&r(this,q).set(e,o)}async receiveClaim(e){if(this.closed)return u({code:"DISCONNECTED"});let n=Nn(e);if(n)return u(n);if(r(this,V).has(e.claimId))return u({code:"INVALID_RESULT",issues:[{message:`Claim id "${e.claimId}" is already live.`,path:["claimId"]}]});if(r(this,V).size>=128)return u({code:"INVALID_RESULT",issues:[{message:`The peer exceeded the limit of ${128} simultaneous claims.`,path:["claimId"]}]});let o=this.modules.filter(({contract:m})=>m.identifier===e.identifier);if(o.length===0)return u({code:"PEER_LACKS_MODULE",identifier:e.identifier});let i=xt(e.version,o.map(m=>({version:m.contract.version,module:m})));if(!i.ok)return i;let s=i.value.module;if(s.signal?.aborted)return u({code:"INVALID_RESULT",issues:[{message:`The host provider for "${e.identifier}" is disposed.`,path:[]}]});let l=new Map,c={releases:[],module:s,fields:l};if(r(this,V).set(e.claimId,c),s.signal){let m=()=>a(this,R,Bt).call(this,e.claimId,[{message:`The host provider for "${e.identifier}" was disposed.`,path:[]}]);s.signal.addEventListener("abort",m,{once:!0}),c.releases.push(()=>s.signal?.removeEventListener("abort",m))}let f={},h={ready:!1},y=!1,C=!1,T=!1,I=new Set,S=new Map,k=()=>{if(C=!1,!r(this,V).has(e.claimId))return;let m=!T;if(!m&&I.size===0)return;let D=m?[...S.keys()]:[...I];T=!0,I.clear();let z={};for(let B of D){let oe=S.get(B);if(!oe)continue;let H=kt(B,oe.field.schema,oe.provider);if(!H.ok){a(this,R,Bt).call(this,e.claimId,mt(e.identifier,B,H.error));return}z[B]=H.value}this.send("__ddValues",()=>this.remote.__ddValues(e.claimId,z))},M=()=>{if(r(this,V).has(e.claimId)){if(!h.ready){y=!0;return}C||(C=!0,globalThis.queueMicrotask(k))}};for(let m of e.fields){let D=s.contract.fields[m];if(!D)return this.receiveRelease(e.claimId),u({code:"CONTRACT_INCOMPATIBLE",field:m});if(l.set(m,D),D.kind==="function"){let H=Object.hasOwn(s.implementation,m)?s.implementation[m]:void 0;if(!b(H)||typeof H.invoke!="function")return this.receiveRelease(e.claimId),u({code:"INVALID_RESULT",issues:[{message:"The host implementation is not a callable function field.",path:[m]}]});continue}let z=Object.hasOwn(s.implementation,m)?s.implementation[m]:void 0;if(!z||typeof z.get!="function"||typeof z.subscribe!="function")return this.receiveRelease(e.claimId),u({code:"INVALID_RESULT",issues:[{message:"The host implementation is not a live value.",path:[m]}]});S.set(m,{field:D,provider:z});let B;try{B=z.subscribe(()=>{I.add(m),M()})}catch(H){return this.receiveRelease(e.claimId),u({code:"INVALID_RESULT",issues:mt(e.identifier,m,H)})}if(typeof B!="function")return this.receiveRelease(e.claimId),u({code:"INVALID_RESULT",issues:[{message:"The host value provider did not return an unsubscribe function.",path:[m]}]});if(r(this,V).get(e.claimId)!==c)return P(`unsubscribe for interrupted claim ${e.claimId}`,B),this.closed?u({code:"DISCONNECTED"}):u({code:"INVALID_RESULT",issues:[{message:`The host provider for "${e.identifier}" was disposed during claim setup.`,path:[]}]});c.releases.push(B);let oe=kt(m,D.schema,z);if(!oe.ok)return this.receiveRelease(e.claimId),u({code:"INVALID_RESULT",issues:mt(e.identifier,m,oe.error)});f[m]=oe.value}return h.ready=!0,y&&M(),N({values:f})}async receiveFunctionCall(e){if(this.closed)return u({code:"DISCONNECTED"});let n=Pn(e);if(n)return u(n);let o=r(this,V).get(e.claimId);if(!o)return u({code:"DISCONNECTED"});let i=o.fields.get(e.field);if(!i||i.kind!=="function")return u({code:"CONTRACT_INCOMPATIBLE",field:e.field});if(r(this,se).has(e.callId))return u({code:"INVALID_ARGUMENT",issues:[{message:`Function call id "${e.callId}" is already active.`,path:["callId"]}]});if(Ut>=128)return u({code:"FUNCTION_FAILED",field:e.field});let s=Ft(e.field,i,e.inputs);if(!s.ok)return O("the host rejected the inputs of a function call",{side:this.role,claimId:e.claimId,callId:e.callId,target:`${o.module.contract.identifier}.${e.field}`,issueCount:s.error.length}),u({code:"INVALID_ARGUMENT",issues:[{message:"The function inputs do not satisfy the host schema.",path:[e.field,"inputs"]}]});let l=Object.hasOwn(o.module.implementation,e.field)?o.module.implementation[e.field]:void 0;if(!b(l)||typeof l.invoke!="function")return u({code:"CONTRACT_INCOMPATIBLE",field:e.field});let c=new AbortController,f=()=>{},h=new Promise(m=>{f=m}),y={claimId:e.claimId,controller:c,interrupt(m){c.signal.aborted||(c.abort(),f({status:"interrupted",reason:m}))}};Ut+=1,r(this,se).set(e.callId,y);let C=globalThis.performance.now()+Math.max(0,this.operationTimeoutMs),T=globalThis.setTimeout(()=>y.interrupt("timed-out"),Math.max(0,this.operationTimeoutMs)),I;try{let m=l.invoke(s.value,Object.freeze({signal:c.signal}));!Mt(m)&&globalThis.performance.now()>=C&&y.interrupt("timed-out"),I=Promise.resolve(m).then(D=>({status:"returned",value:D}),D=>({status:"threw",cause:D}))}catch(m){globalThis.performance.now()>=C&&y.interrupt("timed-out"),I=Promise.resolve({status:"threw",cause:m})}let S=I.finally(()=>{Ut-=1,r(this,se).get(e.callId)===y&&r(this,se).delete(e.callId)}),k=await Promise.race([S,h]);if(globalThis.clearTimeout(T),k.status==="interrupted")return k.reason==="timed-out"?u({code:"TIMED_OUT",timeoutMs:this.operationTimeoutMs}):u({code:"DISCONNECTED"});if(this.closed||c.signal.aborted||r(this,V).get(e.claimId)!==o)return u({code:"DISCONNECTED"});if(k.status==="threw")return O("a host function implementation threw",{side:this.role,claimId:e.claimId,callId:e.callId,target:`${o.module.contract.identifier}.${e.field}`,cause:_(k.cause)}),u({code:"FUNCTION_FAILED",field:e.field});let M=Vt(e.field,i,k.value);return M.ok||O("a host function returned an invalid result",{side:this.role,claimId:e.claimId,callId:e.callId,target:`${o.module.contract.identifier}.${e.field}`,issues:M.error}),M.ok?N(M.value):u({code:"INVALID_RESULT",issues:[{message:"The host function returned a result that does not satisfy its schema.",path:[e.field]}]})}receiveFunctionCancel(e){if(!b(e)||!L(e.claimId,256)||!L(e.callId,256)){O("ignored a malformed __ddCancel envelope",{side:this.role,request:b(e)?{claimId:e.claimId,callId:e.callId}:{malformed:!0,received:typeof e}});return}let n=r(this,se).get(e.callId);n?.claimId===e.claimId&&n.interrupt("cancelled")}receiveRelease(e){if(!L(e,256)){O("ignored a __ddRelease with an invalid claim id",{side:this.role,claimId:e,maxClaimIdLength:256});return}let n=r(this,V).get(e);if(n){r(this,V).delete(e);for(let o of r(this,se).values())o.claimId===e&&o.interrupt("cancelled");for(let o of n.releases)P(`unsubscribe for claim ${e}`,o)}}};ot=new WeakMap,V=new WeakMap,se=new WeakMap,Te=new WeakMap,ye=new WeakMap,K=new WeakMap,q=new WeakMap,Ce=new WeakMap,je=new WeakMap,Be=new WeakMap,rt=new WeakMap,R=new WeakSet,jt=function(){r(this,rt)||(d(this,rt,!0),P("Penpal connection",()=>this.penpal.destroy()),P("operational port",()=>this.port.close()))},Se=function(e){r(this,ye).delete(e),r(this,K).delete(e),r(this,q).delete(e)},Tt=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},He=function(e,n,o,i){let s=[...n.invalidationListeners];if(!a(this,R,Tt).call(this,e,n,i,o))return;(o.code==="DISCONNECTED"?U:O)("a live claim was invalidated",{side:this.role,claimId:e,identifier:n.contract.identifier,version:n.contract.version,observedListeners:s.length,error:J(o)}),ge(s,o)},Bt=function(e,n){let o=r(this,V).get(e);o&&(O("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(!b(t))return{malformed:!0,received:typeof t};let n={};for(let o of e)n[o]=t[o];return n}var $t=class{constructor(e,n){this.endpoint=e;this.modules=n}endpoint;modules;claim(e,n){if(this.endpoint.closed||n?.signal?.aborted)return this.endpoint.claim(e,n);let o=kn(e,this.modules);return o?Promise.resolve(u(o)):this.endpoint.claim(e,n)}};function Po(t){return b(t)&&t.role==="host"&&Array.isArray(t.modules)}function ko(t){if(!(typeof t!="number"||!Number.isFinite(t)||t<=0))return Math.min(t,6e5)}function Fo(t){let e=new Set,n=[];for(let o of t){if(!b(o)||!L(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 Vo(t,e,n,o,i,s,l){let c,f,h=!1,y=!1,C,T=new Promise((g,v)=>{C=v});try{f=new ut(t,()=>{c?c.noteDisconnected():(h=!0,t.close(),C?.({code:"DISCONNECTED"}))},l,e)}catch(g){return P("failed operational port",()=>t.close()),u({code:"TRANSPORT_FAILED",cause:g})}let I=!1,S=0,k=()=>{},M=new Promise(g=>{k=g}),m=g=>{I||(I=!0,k(g))},D=(g,v)=>{let x=Y=>(U("an embedding operation was refused",{side:e,operation:v,expectedRole:g,reason:Y,pendingEndpointOperations:S}),new Error(Y));return c?c.role===g?Promise.resolve(c):Promise.reject(x("The embedding operation is not valid here.")):I||S>=32?Promise.reject(x("The embedding endpoint is not ready for work.")):(S+=1,M.then(Y=>{if(!Y||Y.role!==g)throw x("The embedding operation is not valid here.");return Y}).finally(()=>{S-=1}))},z=e==="host"?{role:"host",modules:i.map(({contract:g})=>({identifier:g.identifier,version:g.version})),surfaceId:s,functionCallTimeoutMs:n}:{role:"app"},B=(g,v,x,Y)=>(Y.ok||U(`${g} was rejected`,{side:e,request:No(v,x),error:J(Y.error)}),Y),oe={__ddDescribe:()=>z,__ddClaim:g=>D("host","__ddClaim").then(v=>v.receiveClaim(g).then(x=>B("__ddClaim",g,["claimId","identifier","version","fields"],x))),__ddRelease:g=>D("host","__ddRelease").then(v=>v.receiveRelease(g)),__ddValues:(g,v)=>D("app","__ddValues").then(x=>x.receiveValues(g,v)),__ddCall:g=>D("host","__ddCall").then(v=>v.receiveFunctionCall(g).then(x=>B("__ddCall",g,["claimId","callId","field"],x))),__ddCancel:g=>D("host","__ddCancel").then(v=>v.receiveFunctionCancel(g)),__ddInvalidate:(g,v)=>D("app","__ddInvalidate").then(x=>x.receiveInvalidation(g,v)),__ddClose:()=>(c||(y=!0),D(e,"__ddClose").then(g=>g.close(!1)))},H;try{H=Mo({messenger:new Lo({port:t}),methods:oe,timeout:n})}catch(g){return f.stop(),tt(t),globalThis.setTimeout(()=>t.close(),et),u({code:"TRANSPORT_FAILED",cause:g})}let ln,un,pn=()=>ln?.({code:"ABORTED"}),hn=new Promise((g,v)=>{ln=v}),fn=new Promise((g,v)=>{un=v}),io=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 g=await Promise.race([H.promise,hn,fn,T]);At="peer-description";let v=await Promise.race([g.__ddDescribe(),hn,fn,T]);if(At="validation",!(e==="app"?Po(v):b(v)&&v.role==="app"))throw new Error(`Expected an embedding ${e==="app"?"host":"app"} using the operational protocol.`);if(c=new yt(e,g,H,t,i,n,e==="app"?ko(v.functionCallTimeoutMs):void 0),h)throw Object.assign(new Error("The transport disconnected before establishment completed."),{code:"DISCONNECTED"});if(y)throw Object.assign(new Error("The peer requested to close before establishment completed."),{code:"DISCONNECTED"});return m(c),c.attachHeartbeat(f),N({endpoint:c,description:v})}catch(g){let v=Ln(g,n);return U("the operational protocol could not be established",{side:e,stage:At,timeoutMs:n,describedPeer:!!c,error:J(v),cause:_(g)}),f.stop(),c?c.close():Dn(H,t),u(v)}finally{m(void 0),globalThis.clearTimeout(io),o.removeEventListener("abort",pn)}}function xo(t){let e=t.endpoint,n=t.description;return{connection:new $t(e,Fo(n.modules)),surfaceId:typeof n.surfaceId=="string"?n.surfaceId:void 0,closeSignal:e.closeSignal,close:()=>e.close()}}async function Vn(t,e,n,o){let i=await Vo(t,"app",e,n,[],void 0,o);return i.ok?N(xo(i.value)):i}var Ho=1e3,Ct=45e3,jo=1e4,Bo=1e4,$o=[1];async function Wo(t,e,n=Bo){if(e.aborted)return t.close(),u({code:"ABORTED"});let o=await In(t,$o,n,e);return o.ok?Vn(o.value.operationalPort,n,e,_n):o}var $e,Wt=class{constructor(){p(this,$e)}next(){let e=r(this,$e)??Ho;return d(this,$e,Math.min(e*2,jo)),e}reset(){d(this,$e,void 0)}};$e=new WeakMap;function Go(){return typeof globalThis.window<"u"&&globalThis.window.parent!==globalThis.window}function zo(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,Ne,it,j,de,ee,ce,le,te,be,We,Pe,A,xn,zt,Jt,Xt,Kt,bt,Un,Le,Gt=class{constructor(){p(this,A);p(this,ae,new AbortController);p(this,Ne,new Set);p(this,it,new Wt);p(this,j,{state:"connecting"});p(this,de);p(this,ee);p(this,ce);p(this,le);p(this,te);p(this,be,0);p(this,We,!1);p(this,Pe,!1);if(!Go()){d(this,j,{state:"not-embedded"});return}a(this,A,Kt).call(this),a(this,A,zt).call(this)}getSnapshot(){return r(this,j)}subscribe(e){return r(this,Ne).add(e),()=>{r(this,Ne).delete(e)}}close(){if(r(this,j).state==="closed")return;r(this,ae).abort(),r(this,ee)?.abort(),d(this,ee,void 0),a(this,A,Xt).call(this),a(this,A,bt).call(this);let e=r(this,de);d(this,de,void 0),a(this,A,Le).call(this,{state:"closed"}),e?.close(),r(this,Ne).clear()}};ae=new WeakMap,Ne=new WeakMap,it=new WeakMap,j=new WeakMap,de=new WeakMap,ee=new WeakMap,ce=new WeakMap,le=new WeakMap,te=new WeakMap,be=new WeakMap,We=new WeakMap,Pe=new WeakMap,A=new WeakSet,xn=async function(e){let n=await bn(globalThis.window,On,e);return n.ok?Wo(n.value,e):n},zt=async function(){if(r(this,ae).signal.aborted||r(this,Pe)||r(this,We)||r(this,de))return;d(this,We,!0),d(this,be,r(this,be)+1);let e=new AbortController;d(this,ee,e);let n;try{n=await a(this,A,xn).call(this,e.signal)}catch(i){n={ok:!1,error:{code:"TRANSPORT_FAILED",cause:i}}}if(d(this,We,!1),r(this,ee)===e&&d(this,ee,void 0),r(this,ae).signal.aborted||r(this,Pe)){n.ok&&n.value.close();return}if(!n.ok){if(d(this,te,n.error),!zo(n.error)){a(this,A,bt).call(this),O("the app connection was rejected",{side:"app",attempt:r(this,be),retryable:!1,error:J(n.error)}),a(this,A,Le).call(this,{state:"rejected",error:n.error});return}a(this,A,Le).call(this,r(this,j).state==="reconnecting"?{state:"reconnecting",lastError:n.error}:{state:"connecting",error:n.error}),a(this,A,Jt).call(this);return}d(this,de,n.value),d(this,te,void 0),r(this,it).reset(),a(this,A,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"}),U("the app lost its established connection",{side:"app",attempt:r(this,be),surfaceId:n.value.surfaceId}),a(this,A,Kt).call(this),a(this,A,Le).call(this,{state:"reconnecting",lastError:r(this,te)}),a(this,A,Jt).call(this))};if(n.value.closeSignal.addEventListener("abort",o,{once:!0}),n.value.closeSignal.aborted){o();return}a(this,A,Le).call(this,{state:"connected",connection:n.value.connection,surfaceId:n.value.surfaceId})},Jt=function(){if(r(this,ae).signal.aborted||r(this,Pe)||r(this,ce)!==void 0)return;let e=r(this,it).next();U("retrying the app connection",{side:"app",state:r(this,j).state,failedAttempts:r(this,be),retryInMs:e,giveUpAfterMs:Ct,error:r(this,te)&&J(r(this,te))}),d(this,ce,globalThis.setTimeout(()=>{d(this,ce,void 0),a(this,A,zt).call(this)},e))},Xt=function(){r(this,ce)!==void 0&&(globalThis.clearTimeout(r(this,ce)),d(this,ce,void 0))},Kt=function(){r(this,le)===void 0&&d(this,le,globalThis.setTimeout(()=>{d(this,le,void 0),a(this,A,Un).call(this)},Ct))},bt=function(){r(this,le)!==void 0&&(globalThis.clearTimeout(r(this,le)),d(this,le,void 0))},Un=function(){if(r(this,ae).signal.aborted||r(this,j).state==="connected"||r(this,j).state==="closed")return;d(this,Pe,!0),a(this,A,Xt).call(this),r(this,ee)?.abort(),d(this,ee,void 0);let e=r(this,te)??{code:"TIMED_OUT",timeoutMs:Ct};O("the app gave up connecting to its Datadog host",{side:"app",state:r(this,j).state,failedAttempts:r(this,be),gaveUpAfterMs:Ct,error:J(e)}),a(this,A,Le).call(this,{state:"rejected",error:e})},Le=function(e){r(this,j)!==e&&(d(this,j,e),ge(r(this,Ne)))};var Hn=Object.freeze({connect(){return new Gt}});function jn(t){return t.join(", ")}function Jo(t){return t.map(e=>`${e.path.length>0?e.path.join("."):"(root)"}: ${e.message}`).join("; ")}function Xo(t){let e;try{if(t instanceof Error)e=t.message||t.name;else if(typeof t=="string")e=t;else try{e=JSON.stringify(t)??String(t)}catch{e=Object.prototype.toString.call(t)}}catch{e="(cause could not be described)"}return e.length>200?`${e.slice(0,200)}\u2026`:e}function Zt(t){switch(t.code){case"TIMED_OUT":return{code:"TIMED_OUT",action:"retry",message:`TIMED_OUT: the Datadog host did not complete the connection within ${t.timeoutMs}ms. Reload the app to try again.`};case"ORIGIN_REJECTED":return{code:"ORIGIN_REJECTED",action:"contact-support",message:`ORIGIN_REJECTED: the embedding connection failed origin validation for "${t.origin}". Screenshot this message and contact support.`};case"APP_PROTOCOL_TOO_OLD":return{code:"APP_PROTOCOL_TOO_OLD",action:"update-app",message:`APP_PROTOCOL_TOO_OLD: this app supports embedding protocols ${t.appProtocols.join(", ")}, while the Datadog host requires ${t.hostProtocols.join(", ")}. Update @datadog/apps-frontend, rebuild this app, and upload the new bundle.`};case"HOST_PROTOCOL_TOO_OLD":return{code:"HOST_PROTOCOL_TOO_OLD",action:"contact-support",message:`HOST_PROTOCOL_TOO_OLD: this app supports embedding protocols ${t.appProtocols.join(", ")}, newer than the Datadog host's ${t.hostProtocols.join(", ")}. Rebuilding the app will not fix this; screenshot this message and contact support.`};case"PROTOCOL_INCOMPATIBLE":return{code:"PROTOCOL_INCOMPATIBLE",action:"contact-support",message:`PROTOCOL_INCOMPATIBLE: this app supports embedding protocols ${t.appProtocols.join(", ")}, while the Datadog host supports ${t.hostProtocols.join(", ")}. The sets do not overlap; screenshot this message and contact support.`};case"DISCONNECTED":return{code:"CONNECTION_LOST",action:"retry",message:"CONNECTION_LOST: the Datadog host stopped responding and the connection could not be re-established. Reload the app to try again."};case"TRANSPORT_FAILED":return{code:"UNKNOWN",action:"contact-support",message:`TRANSPORT_FAILED: the local embedding transport failed (${Xo(t.cause)}). Screenshot this message and contact support.`};case"UNRECOGNIZED":return{code:"UNKNOWN",action:"contact-support",message:`UNRECOGNIZED: the peer reported failure code "${t.rawCode}", which this app build does not know. Screenshot this message and contact support.`};case"ABORTED":return{code:"UNKNOWN",action:"contact-support",message:"ABORTED: the embedding connection was cancelled unexpectedly. Screenshot this message and contact support."};default:return t}}function Yt(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 ${jn(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 ${jn(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 (${Jo(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 Zt(t);default:return t}}var Ko=0,Zo=Object.freeze({status:"pending"}),Yo=Object.freeze({status:"unavailable"}),Qo=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."}),Bn=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 qt(){return Zo}function $n(){return Yo}function qo(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 ve,pe,Ae,vt=class{constructor(e,n){this.owner=e;this.resource=n;p(this,ve,new Set);p(this,pe);p(this,Ae,!1);xe(this,"subscribe",e=>{r(this,pe)!==void 0&&(globalThis.clearTimeout(r(this,pe)),d(this,pe,void 0));let n=()=>e();r(this,ve).add(n),r(this,Ae)||(d(this,Ae,!0),this.owner.activate(this.resource));let o=!0;return()=>{o&&(o=!1,r(this,ve).delete(n),r(this,ve).size===0&&r(this,pe)===void 0&&d(this,pe,globalThis.setTimeout(()=>{d(this,pe,void 0),r(this,ve).size===0&&r(this,Ae)&&(d(this,Ae,!1),this.owner.deactivate(this.resource))},Ko)))}})}owner;resource;notify(){ge(r(this,ve))}get isActive(){return r(this,Ae)}};ve=new WeakMap,pe=new WeakMap,Ae=new WeakMap;var Re,W,Ie,G,ne,he,ze,E,Wn,Gn,zn,nn,Ge,Oe,ue,ke,tn=class{constructor(e,n){p(this,E);p(this,Re);p(this,W);p(this,Ie,qt());p(this,G);p(this,ne);p(this,he);p(this,ze,[]);xe(this,"getSnapshot",()=>r(this,Ie));xe(this,"subscribe",e=>r(this,Re).subscribe(e));d(this,W,n),d(this,Re,new vt(e,this))}sync(e){if(!e){this.reset();return}switch(e.state){case"connected":if(r(this,G)===e.connection)return;a(this,E,Oe).call(this),d(this,G,e.connection),a(this,E,ke).call(this,qt()),a(this,E,Wn).call(this,e.connection);return;case"connecting":case"reconnecting":this.reset();return;case"not-embedded":d(this,G,void 0),a(this,E,Oe).call(this),a(this,E,ke).call(this,$n());return;case"rejected":d(this,G,void 0),a(this,E,Oe).call(this),a(this,E,ue).call(this,Zt(e.error));return;case"closed":d(this,G,void 0),a(this,E,Oe).call(this),a(this,E,ue).call(this,Qo);return;default:return e}}fail(e){d(this,G,void 0),a(this,E,Oe).call(this),a(this,E,ue).call(this,e)}reset(){d(this,G,void 0),a(this,E,Oe).call(this),a(this,E,ke).call(this,qt())}};Re=new WeakMap,W=new WeakMap,Ie=new WeakMap,G=new WeakMap,ne=new WeakMap,he=new WeakMap,ze=new WeakMap,E=new WeakSet,Wn=function(e){let n=new AbortController;d(this,ne,n);let o;try{o=e.claim(r(this,W),{signal:n.signal})}catch(i){O("a claim could not be requested",{side:"app",identifier:r(this,W).identifier,current:a(this,E,Ge).call(this,e,n),cause:_(i)}),a(this,E,Ge).call(this,e,n)&&(d(this,ne,void 0),a(this,E,ue).call(this,Qt));return}o.then(i=>{if(!a(this,E,Ge).call(this,e,n)){i.ok&&i.value.release();return}if(d(this,ne,void 0),!i.ok){if(i.error.code==="PEER_LACKS_MODULE"){U("the Datadog host does not offer this module",{side:"app",identifier:r(this,W).identifier,version:r(this,W).version}),a(this,E,ke).call(this,$n());return}if(i.error.code==="ABORTED"){a(this,E,ue).call(this,Qt);return}a(this,E,ue).call(this,Yt(i.error));return}a(this,E,Gn).call(this,e,i.value)},i=>{O("a claim request rejected",{side:"app",identifier:r(this,W).identifier,current:a(this,E,Ge).call(this,e,n),cause:_(i)}),a(this,E,Ge).call(this,e,n)&&(d(this,ne,void 0),a(this,E,ue).call(this,Qt))})},Gn=function(e,n){if(!r(this,Re).isActive||r(this,G)!==e||r(this,he)){n.release();return}d(this,he,n),r(this,ze).push(n.onInvalidated(o=>a(this,E,zn).call(this,n,o))),r(this,ze).push(n.onValuesChanged(()=>{r(this,he)===n&&a(this,E,nn).call(this,n)})),a(this,E,nn).call(this,n)},zn=function(e,n){if(r(this,he)!==e)return;let o=Yt(n);a(this,E,Oe).call(this),a(this,E,ue).call(this,o)},nn=function(e){let n=Object.entries(r(this,W).fields),o=n.map(([s])=>s),i=Object.create(null);for(let[s,l]of n){let c=e.fields[s];i[s]=l.kind==="value"?c.get():c}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,E,ke).call(this,Object.freeze({status:"ready",fields:Object.freeze(i)}))},Ge=function(e,n){return r(this,Re).isActive&&r(this,G)===e&&r(this,ne)===n&&!n.signal.aborted},Oe=function(){r(this,ne)?.abort(),d(this,ne,void 0);for(let n of r(this,ze).splice(0))n();let e=r(this,he);d(this,he,void 0),e?.release()},ue=function(e){O("a Datadog App claim failed",{side:"app",identifier:r(this,W).identifier,version:r(this,W).version,code:e.code,action:e.action,reason:e.message}),a(this,E,ke).call(this,qo(e))},ke=function(e){r(this,Ie)!==e&&(d(this,Ie,e),r(this,Re).notify())};var en=Object.freeze({state:"connecting"});function er(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 Je,Xe,Ke,Ot,on=class{constructor(e){p(this,Ke);p(this,Je);p(this,Xe,en);xe(this,"getSnapshot",()=>r(this,Xe));xe(this,"subscribe",e=>r(this,Je).subscribe(e));d(this,Je,new vt(e,this))}sync(e){a(this,Ke,Ot).call(this,e?er(e):en)}fail(e){a(this,Ke,Ot).call(this,{state:"rejected",error:{code:"TRANSPORT_FAILED",cause:e}})}reset(){a(this,Ke,Ot).call(this,en)}};Je=new WeakMap,Xe=new WeakMap,Ke=new WeakSet,Ot=function(e){r(this,Xe)!==e&&(d(this,Xe,e),r(this,Je).notify())};var st,Z,at,fe,Ze,_e,Ye,Fe,w,Jn,Xn,Kn,Zn,sn,an,dn,rn=class{constructor(e){this.connector=e;p(this,w);p(this,st,new WeakMap);p(this,Z,new Set);p(this,at,{activate:e=>a(this,w,Kn).call(this,e),deactivate:e=>a(this,w,Zn).call(this,e)});p(this,fe);p(this,Ze);p(this,_e);p(this,Ye);p(this,Fe,0)}connector;getClaim(e){let n=e,o=r(this,st).get(n);if(o)return o;let i=new tn(r(this,at),e);return r(this,st).set(n,i),i}getEmbeddingMetadata(){return r(this,Ye)||d(this,Ye,new on(r(this,at))),r(this,Ye)}start(){d(this,Fe,r(this,Fe)+1),r(this,Fe)===1&&a(this,w,Jn).call(this);let e=!0;return()=>{e&&(e=!1,d(this,Fe,r(this,Fe)-1),r(this,Fe)===0&&a(this,w,Xn).call(this))}}};st=new WeakMap,Z=new WeakMap,at=new WeakMap,fe=new WeakMap,Ze=new WeakMap,_e=new WeakMap,Ye=new WeakMap,Fe=new WeakMap,w=new WeakSet,Jn=function(){d(this,_e,void 0);for(let n of r(this,Z))n.reset();let e;try{e=this.connector.connect()}catch(n){a(this,w,dn).call(this,"connect",n);return}d(this,fe,e);try{d(this,Ze,e.subscribe(()=>a(this,w,sn).call(this,e))),a(this,w,sn).call(this,e)}catch(n){a(this,w,an).call(this,e),a(this,w,dn).call(this,"subscribe",n);return}},Xn=function(){let e=r(this,fe);e&&a(this,w,an).call(this,e),d(this,_e,void 0);for(let n of r(this,Z))n.reset()},Kn=function(e){if(r(this,Z).add(e),r(this,_e)){e.fail(r(this,_e));return}e.sync(r(this,fe)?.getSnapshot())},Zn=function(e){r(this,Z).delete(e),e.reset()},sn=function(e){if(r(this,fe)!==e)return;let n=e.getSnapshot();for(let o of r(this,Z))o.sync(n)},an=function(e){if(r(this,fe)!==e)return;d(this,fe,void 0);let n=r(this,Ze);d(this,Ze,void 0),n&&P("embedding connection handle unsubscribe",()=>n());for(let o of r(this,Z))P("embedding claim resource reset",()=>o.reset());P("embedding connection handle close",()=>e.close())},dn=function(e,n){O("the embedding connection could not be started",{side:"app",step:e,affectedResources:r(this,Z).size,cause:_(n)}),d(this,_e,Bn);for(let o of r(this,Z))o.fail(Bn)};function Yn(t){return new rn(t)}import{createContext as nr,createElement as or,useContext as rr,useEffect as ir}from"react";var Ve=new WeakMap,tr=3e4;function Qn(t){let e=Ve.get(t);if(e)return e.cleanupTimer!==void 0&&(globalThis.clearTimeout(e.cleanupTimer),e.cleanupTimer=void 0),e;let n={release:t.start()};return Ve.set(t,n),n}function qn(t){let e=Ve.get(t);return e?(Ve.delete(t),e.cleanupTimer!==void 0&&globalThis.clearTimeout(e.cleanupTimer),e.release):t.start()}function eo(t,e){Ve.get(t)!==e||e.cleanupTimer!==void 0||(e.cleanupTimer=globalThis.setTimeout(()=>{Ve.get(t)===e&&(Ve.delete(t),e.release())},tr))}var to=nr(null);function no(t){return function({children:n}){return ir(()=>qn(t),[]),or(to.Provider,{value:t},n)}}function oo(){let t=rr(to);if(!t)throw new Error("Datadog App hooks must be used within DatadogAppProvider.");return t}var sr=Yn(Hn),ar=no(sr);import{useSyncExternalStore as dr}from"react";var cn=new WeakMap;function ro(t){return t==="connecting"||t==="reconnecting"}function cr(t,e){let n=cn.get(e);if(!n){let o=Qn(t),i;n=new Promise(f=>{i=f}),cn.set(e,n);let s,l=!1,c=()=>{l||ro(e.getSnapshot().state)||(l=!0,s?.(),cn.delete(e),eo(t,o),i())};s=e.subscribe(c),l?s():c()}throw n}function lr(){throw new Error("useDatadogAppEmbedding does not support server rendering: the Datadog App embedding connection only exists in the browser.")}function ur(t){throw new Error(t.state==="rejected"?`The Datadog App embedding connection was rejected: ${t.error.code}.`:"The Datadog App embedding connection closed.")}function pr(t){let e=oo(),n=e.getEmbeddingMetadata(),o=dr(n.subscribe,n.getSnapshot,lr);return t?.suspense&&(ro(o.state)&&cr(e,n),(o.state==="rejected"||o.state==="closed")&&ur(o)),o}export{ar as DatadogAppProvider,pr as useDatadogAppEmbedding};
6
+ import{a as yn,b as Rn,c as vn,d as An}from"../../_chunks/chunk-2V2HASKF.js";import{A as b,B as k,C as L,D as ge,a as Fe,b as r,c as p,d,e as a,f as qe,g as gn,h as En,i as xe,j as Tn,k as Cn,l as et,m as It,n as B,o as tt,p as On,q as bn,r as _t,s as Dt,t as S,u as J,v as x,w as y,x as me,y as w,z as l}from"../../_chunks/chunk-X34MSTJH.js";var ho=/^https:\/\/(?:[a-zA-Z0-9-]+\.)*(?:datadoghq\.(?:com|eu)|ddog-gov\.com)$/,fo=/^https:\/\/(?:[a-zA-Z0-9-]+\.)*(?:datad0g\.com|datad0g\.eu|staging\.dog|prod\.dog)$/,mo=/^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/;function In(t){return ho.test(t)||fo.test(t)||mo.test(t)}var _n="dd-apps-frontend-bootstrap",Dn=1;function Eo(t,e,n){let{data:o}=n;return n.source!==t||n.ports.length!==0||!b(o)||o.namespace!==_n||o.version!==Dn||o.type!=="accepted"&&o.type!=="rejected-origin"||o.attemptId!==e?{status:"ignored"}:In(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 Mn(t,e,n,o=1e4){if(n.aborted)return Promise.resolve(l({code:"ABORTED"}));let i=t.parent;if(i===t)return Promise.resolve(l({code:"TRANSPORT_FAILED",cause:new Error("The app is not running in an iframe.")}));let s=me("bootstrap"),c=new MessageChannel;return new Promise(u=>{let h=!1,m=!1,f=!1,C,_=M=>{h||(h=!0,t.removeEventListener("message",O),n.removeEventListener("abort",D),C!==void 0&&globalThis.clearTimeout(C),M.ok||(L("failed app bootstrap port",()=>c.port1.close()),m||L("untransferred app bootstrap port",()=>c.port2.close())),u(M))},O=M=>{let T=Eo(i,s,M);T.status==="accepted"?_(w(c.port1)):T.status==="rejected-origin"&&_(l({code:"ORIGIN_REJECTED",origin:T.origin}))},D=()=>_(l({code:"ABORTED"})),H=()=>{if(!(f||h)){f=!0,C=globalThis.setTimeout(()=>_(l({code:"TIMED_OUT",timeoutMs:o})),Math.max(0,o));try{i.postMessage({namespace:_n,version:Dn,type:"request",attemptId:s,documentId:e},"*",[c.port2]),m=!0}catch(M){_(l({code:"TRANSPORT_FAILED",cause:M}))}}};if(t.addEventListener("message",O),n.addEventListener("abort",D,{once:!0}),n.aborted){D();return}H()})}var wn=me("document");var Ln="dd-apps-frontend-compatibility",Pn=1,To=64;function Co(t,e,n,o){return n.aborted?Promise.resolve({ok:!1,error:{code:"ABORTED"}}):new Promise(i=>{let s=!1,c,u=f=>{s||(s=!0,t.removeEventListener("message",h),n.removeEventListener("abort",m),c!==void 0&&globalThis.clearTimeout(c),i(f))},h=f=>u({ok:!0,value:f}),m=()=>u({ok:!1,error:{code:"ABORTED"}});t.addEventListener("message",h),n.addEventListener("abort",m,{once:!0}),c=globalThis.setTimeout(()=>u({ok:!1,error:{code:"TIMED_OUT",timeoutMs:e}}),Math.max(0,e));try{t.start(),o?.()}catch(f){u({ok:!1,error:{code:"TRANSPORT_FAILED",cause:f}})}})}function Nn(t){if(!(!Array.isArray(t)||t.length===0||t.length>To||!Array.from(t).every(e=>Number.isSafeInteger(e)&&e>0)||new Set(t).size!==t.length))return[...t].sort((e,n)=>e-n)}function Oo(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),c=Math.max(...e);return i<s?{ok:!1,error:{code:"APP_PROTOCOL_TOO_OLD",appProtocols:t,hostProtocols:e}}:c<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 Sn(t,e,n,o){let i=Nn(e);if(!i)return t.close(),{ok:!1,error:{code:"TRANSPORT_FAILED",cause:new Error("The app protocol registry is invalid.")}};let s=await Co(t,n,o,()=>{t.postMessage({namespace:Ln,version:Pn,type:"offer",role:"app",protocols:i})});if(t.close(),!s.ok)return s;let{data:c,ports:u}=s.value;if(!b(c)||c.namespace!==Ln||c.version!==Pn||c.type!=="answer"||c.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 h=Nn(c.protocols);if(!h){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=Oo(i,h);if(!m.ok){for(let C of u)C.close();return m}let[f]=u;if(u.length!==1||f===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:f}}}import{connect as Po,PortMessenger as No,Reply as So}from"penpal";var pt="dd-apps-frontend-heartbeat",ht=1,kn=Object.freeze({intervalMs:gn,timeoutMs:En});function rt(t){try{t.postMessage({namespace:pt,version:ht,type:"close"})}catch{}}function Un(t,e){rt(e),globalThis.setTimeout(()=>{L("failed Penpal connection",()=>t.destroy()),L("failed operational port",()=>e.close())},xe)}var K,re,ie,nt,Q,ot,V,Mt,wt,Lt,ft,mt=class{constructor(e,n,o,i){this.port=e;this.onDead=n;this.policy=o;this.side=i;p(this,V);p(this,K);p(this,re);p(this,ie,0);p(this,nt,!1);p(this,Q,!1);p(this,ot,e=>{let n=e.data;if(!(!b(n)||n.namespace!==pt||n.version!==ht)){if(n.type==="close"){a(this,V,ft).call(this,!1);return}if(k(n.nonce)){if(n.type==="ping"){try{this.port.postMessage({namespace:pt,version:ht,type:"pong",nonce:n.nonce})}catch(o){y("could not answer a heartbeat probe",{side:this.side,cause:S(o)}),a(this,V,ft).call(this,!0)}return}n.type!=="pong"||n.nonce!==r(this,re)||(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,Mt).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,Mt).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,Mt=function(e){r(this,Q)||d(this,K,globalThis.setTimeout(()=>a(this,V,wt).call(this),Math.max(0,e)))},wt=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){x("could not send a heartbeat probe",{side:this.side,misses:r(this,ie),cause:S(n)}),a(this,V,Lt).call(this,e);return}d(this,K,globalThis.setTimeout(()=>a(this,V,Lt).call(this,e),Math.max(0,this.policy.timeoutMs)))},Lt=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){y("the peer stopped answering heartbeats",{side:this.side,misses:r(this,ie),probeTimeoutMs:this.policy.timeoutMs,intervalMs:this.policy.intervalMs}),a(this,V,ft).call(this,!0);return}x("a heartbeat probe went unanswered",{side:this.side,misses:r(this,ie),probeTimeoutMs:this.policy.timeoutMs}),a(this,V,wt).call(this)}},ft=function(e){r(this,Q)||(this.stop(),this.onDead(e))};import{Reply as bo}from"penpal";function yo(t){return(typeof t=="object"&&t!==null||typeof t=="function")&&typeof t.then=="function"}function De(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=1}function Nt(t){return Array.isArray(t)&&t.every(De)}function Me(t){return Array.isArray(t)&&t.every(e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>0)}function Ro(t){return Array.isArray(t)&&t.every(e=>typeof e=="string"||typeof e=="number"&&Number.isSafeInteger(e)&&e>=0)}function St(t){return Array.isArray(t)&&t.every(e=>b(e)&&typeof e.message=="string"&&Ro(e.path))}function we(t,e){try{let n=t["~standard"].validate(e);return yo(n)?(Promise.resolve(n).catch(()=>{}),l([{message:"Embedding value schemas must be synchronous.",path:[]}])):n.issues?l(n.issues.map(o=>({message:o.message,path:vo(o.path)}))):w(n.value)}catch(n){return l([{message:n instanceof Error?n.message:"The value parser rejected this value.",path:[]}])}}function vo(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 c=it(s,[...e,Array.isArray(t)?Number(i):i],n);if(c)return c}return e}}function He(t,e){return e.map(n=>({message:n.message,path:[t,...n.path]}))}function gt(t){return Object.entries(t.fields).filter(([,e])=>e.kind==="value").map(([e])=>e)}function Vn(t,e,n){let o=new Set(t);if(n){let s=[...o].find(c=>!Object.prototype.hasOwnProperty.call(e,c));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 Fn(t){return{code:"INVALID_RESULT",issues:[{message:t.kind==="missing"?"The host value snapshot omitted a claimed field.":"The host value snapshot included an unclaimed field.",path:[t.field]}]}}function Et(t,e){let n=Vn(t,e,!0);return n&&Fn(n)}function kt(t,e){let n=Vn(t,e,!1);return n&&Fn(n)}function Ut(t,e,n){let o;try{o=n.get()}catch(s){return y("a host value provider threw while being read",{side:"host",field:t,cause:S(s)}),l([{message:"The host value provider threw while being read.",path:[t]}])}let i=we(e,o);if(!i.ok)return l(He(t,i.error));try{return w(globalThis.structuredClone(i.value))}catch{let s=it(i.value)??[];return l([{message:"The host value is not structured-clone-safe.",path:[t,...s]}])}}function Tt(t,e,n){return y("a host value could not be provided",{side:"host",target:`${t}.${e}`,details:S(n)}),[{message:"The host could not provide a value that satisfies this field schema.",path:[e]}]}function Vt(t,e,n){if(!b(n))return l([{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 l([{message:`Unknown function input "${o}".`,path:[t,"inputs",o]}]);let i=Object.create(null);for(let[s,c]of Object.entries(e.inputs)){let u=we(c,Object.hasOwn(n,s)?n[s]:void 0);if(!u.ok)return l(u.error.map(h=>({message:h.message,path:[t,"inputs",s,...h.path]})));i[s]=u.value}try{return w(globalThis.structuredClone(i))}catch{let s=it(i)??[];return l([{message:"The function inputs are not structured-clone-safe.",path:[t,"inputs",...s]}])}}function xn(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 Hn=Object.freeze({"~standard":{version:1,vendor:"@datadog/apps-frontend",validate(t){return xn(t)?{value:t}:{issues:[{message:"Expected a MessagePort."}]}}}});function st(t){xn(t)&&L("discarded function result MessagePort",()=>t.close())}function Pt(t,e=[]){return l([{message:"The function result is not structured-clone-safe.",path:[t,...e]}])}function jn(t,e,n){let o=we(e.result,n);if(!o.ok)return l(He(t,o.error));if(e.result===Hn){let i=o.value;try{let s=globalThis.structuredClone(i,{transfer:[i]});return w(new bo(w(s),{transferables:[s]}))}catch{return Pt(t)}}try{return w(w(globalThis.structuredClone(o.value)))}catch{let i=it(o.value)??[];return Pt(t,i)}}function Bn(t,e,n){let o=we(e.result,n);if(!o.ok)return l(He(t,o.error));if(e.result===Hn)return w(o.value);try{return w(globalThis.structuredClone(o.value))}catch{let i=it(o.value)??[];return Pt(t,i)}}import{ErrorCode as Ao,PenpalError as Io}from"penpal";function _o(t){let e=t.wanted,n=t.hostVersions;return De(e)&&Nt(n)&&!n.includes(e)&&n.some(o=>o>e)}function Do(t){let e=t.wanted,n=t.hostVersions;return De(e)&&Nt(n)&&!n.includes(e)&&n.every(o=>o<e)}var Wn={ORIGIN_REJECTED:t=>typeof t.origin=="string",APP_PROTOCOL_TOO_OLD:t=>Me(t.appProtocols)&&Me(t.hostProtocols),HOST_PROTOCOL_TOO_OLD:t=>Me(t.appProtocols)&&Me(t.hostProtocols),PROTOCOL_INCOMPATIBLE:t=>Me(t.appProtocols)&&Me(t.hostProtocols),PEER_LACKS_MODULE:t=>typeof t.identifier=="string",APP_MAJOR_TOO_OLD:_o,HOST_MAJOR_TOO_OLD:Do,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},Mo={ORIGIN_REJECTED:["origin"],APP_PROTOCOL_TOO_OLD:["appProtocols","hostProtocols"],HOST_PROTOCOL_TOO_OLD:["appProtocols","hostProtocols"],PROTOCOL_INCOMPATIBLE:["appProtocols","hostProtocols"],PEER_LACKS_MODULE:["identifier"],APP_MAJOR_TOO_OLD:["wanted","hostVersions"],HOST_MAJOR_TOO_OLD:["wanted","hostVersions"],CONTRACT_INCOMPATIBLE:["field"],INVALID_ARGUMENT:["issues"],FUNCTION_FAILED:["field"],INVALID_RESULT:["issues"],TIMED_OUT:["timeoutMs"],TRANSPORT_FAILED:[],ABORTED:[],DISCONNECTED:[],UNRECOGNIZED:["rawCode","raw"]};function Ct(t,e){if(b(t)&&typeof t.code=="string"){let n=t.code;if(e.includes(n)&&Object.prototype.hasOwnProperty.call(Wn,n)){let o=Wn[n];if(o(t)){if(n==="UNRECOGNIZED")return{code:n,rawCode:t.rawCode,raw:void 0};let i={code:n};for(let s of Mo[n])i[s]=t[s];return i}}}return{code:"UNRECOGNIZED",rawCode:b(t)&&typeof t.code=="string"?t.code:"MALFORMED_ERROR",raw:void 0}}function Ee(t,e,n){let o=`${t.identifier}.${e}`,i=n.code==="UNRECOGNIZED"?"UNKNOWN":n.code,s;switch(n.code){case"INVALID_ARGUMENT":s=`The inputs passed to "${o}" are invalid: ${n.issues[0]?.message??"the schema rejected them"}.`;break;case"INVALID_RESULT":s=`Datadog returned an invalid result from "${o}": ${n.issues[0]?.message??"the schema rejected it"}. The app and host may be using incompatible schema implementations.`;break;case"FUNCTION_FAILED":s=`Datadog could not complete "${o}". Screenshot this message and contact support if the problem continues.`;break;case"TIMED_OUT":s=`"${o}" did not finish within ${n.timeoutMs} ms. It may still complete in Datadog; do not automatically retry an action that is not idempotent.`;break;case"CONTRACT_INCOMPATIBLE":s=`The Datadog host contract for "${o}" does not match the schema compiled into this app. Update the app or contact support.`;break;case"ABORTED":s=`The inputs used by "${o}" were released before it completed. Its outcome is unknown; wait for the inputs to become ready before calling it again.`;break;case"DISCONNECTED":s=`The Datadog connection closed before "${o}" completed. Its outcome is unknown; reconnect before trying again.`;break;case"UNRECOGNIZED":s=`Datadog returned an unrecognized failure for "${o}" (${n.rawCode}). Screenshot this message and contact support.`;break;default:s=n}let c=new Error(`DATADOG_APP_INPUT_FUNCTION_${i}: ${s}`,{cause:n});return c.name="DatadogAppInputFunctionError",y("a Datadog host function call failed",{side:"app",target:o,error:J(n)}),Object.assign(c,{code:i})}function zn(t,e){return b(t)&&t.code==="ABORTED"?{code:"ABORTED"}:b(t)&&t.code==="TIMED_OUT"?{code:"TIMED_OUT",timeoutMs:e}:b(t)&&t.code==="DISCONNECTED"?{code:"DISCONNECTED"}:t instanceof Io&&t.code===Ao.ConnectionTimeout?{code:"TIMED_OUT",timeoutMs:e}:{code:"TRANSPORT_FAILED",cause:t}}function $n(t){if(!b(t))return{code:"INVALID_RESULT",issues:[{message:"Malformed __ddClaim envelope: expected an object.",path:[]}]};if(!k(t.claimId,B))return{code:"INVALID_RESULT",issues:[{message:`"claimId" must contain between 1 and ${B} characters.`,path:["claimId"]}]};if(!k(t.identifier))return{code:"INVALID_RESULT",issues:[{message:'"identifier" must be a non-empty string.',path:["identifier"]}]};if(!De(t.version))return{code:"INVALID_RESULT",issues:[{message:'"version" must be a positive integer.',path:["version"]}]};if(!Array.isArray(t.fields)||t.fields.length===0||t.fields.length>_t)return{code:"INVALID_RESULT",issues:[{message:`"fields" must contain between 1 and ${_t} entries.`,path:["fields"]}]};if(!t.fields.every(e=>typeof e=="string"&&e.length>0&&e.length<=Dt)||new Set(t.fields).size!==t.fields.length)return{code:"INVALID_RESULT",issues:[{message:`"fields" must contain unique non-empty strings of at most ${Dt} characters.`,path:["fields"]}]}}function Gn(t){if(!b(t))return{code:"INVALID_ARGUMENT",issues:[{message:"Malformed __ddCall envelope: expected an object.",path:[]}]};if(!k(t.claimId,B))return{code:"INVALID_ARGUMENT",issues:[{message:`"claimId" must contain between 1 and ${B} characters.`,path:["claimId"]}]};if(!k(t.callId,tt))return{code:"INVALID_ARGUMENT",issues:[{message:`"callId" must contain between 1 and ${tt} characters.`,path:["callId"]}]};if(!k(t.field))return{code:"INVALID_ARGUMENT",issues:[{message:'"field" must be a non-empty string.',path:["field"]}]};if(!b(t.inputs))return{code:"INVALID_ARGUMENT",issues:[{message:'"inputs" must be an object.',path:["inputs"]}]}}function Ft(t,e){let n=e.map(({version:s})=>s).sort((s,c)=>s-c),o=n[n.length-1];if(o===void 0)return l({code:"HOST_MAJOR_TOO_OLD",wanted:t,hostVersions:n});let i=e.find(({version:s})=>s===t);return i?w(i):l(t<o?{code:"APP_MAJOR_TOO_OLD",wanted:t,hostVersions:n}:{code:"HOST_MAJOR_TOO_OLD",wanted:t,hostVersions:n})}function Jn(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 Pe,Ht=class{constructor(e){this.value=e;p(this,Pe,new Set)}value;get(){return this.value}subscribe(e){return r(this,Pe).add(e),()=>{r(this,Pe).delete(e)}}set(e){return Object.is(this.value,e)?!1:(this.value=e,!0)}notify(){ge(r(this,Pe))}freeze(){r(this,Pe).clear()}};Pe=new WeakMap;var xt=0;function Kn(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,We,dt,I,jt,Le,Ot,je,Bt,bt=class{constructor(e,n,o,i,s,c){this.role=e;this.remote=n;this.penpal=o;this.port=i;this.modules=s;this.operationTimeoutMs=c;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,We,!1);p(this,dt,!1)}role;remote;penpal;port;modules;operationTimeoutMs;get closed(){return r(this,We)}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(c){y("an outbound embedding message could not be sent",{side:this.role,operation:e,cause:S(c)}),this.noteDisconnected();return}let i=globalThis.setTimeout(()=>{r(this,Oe).delete(i),y("an outbound embedding message was never acknowledged; closing the connection",{side:this.role,operation:e,timeoutMs:this.operationTimeoutMs}),this.close()},Math.max(0,this.operationTimeoutMs));r(this,Oe).add(i);let s=(c,u)=>{r(this,Oe).delete(i)&&(globalThis.clearTimeout(i),c&&(y("an outbound embedding message was rejected",{side:this.role,operation:e,cause:S(u)}),this.noteDisconnected()))};o.then(()=>s(!1),c=>s(!0,c))}noteDisconnected(e=!1){this.close(e)}close(e=!0){if(r(this,We))return;d(this,We,!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),xe)}async settleRemoteResult(e,n){return this.closed?(e.then(o=>{n.onDiscardedResult?.(o)},()=>{}),l(n.disconnectedError)):new Promise(o=>{let i=!1,s,c=m=>{i||(i=!0,s!==void 0&&globalThis.clearTimeout(s),n.signal?.removeEventListener("abort",u),this.closeSignal.removeEventListener("abort",h),o(m))},u=()=>{n.onCancel(),c(l(n.abortError))},h=()=>c(l(n.disconnectedError));if(n.signal?.addEventListener("abort",u,{once:!0}),this.closeSignal.addEventListener("abort",h,{once:!0}),n.signal?.aborted){u();return}if(this.closeSignal.aborted){h();return}s=globalThis.setTimeout(()=>{n.onCancel(),c(l(n.timeoutError(n.timeoutMs)))},Math.max(0,n.timeoutMs)),e.then(m=>{if(i){n.onDiscardedResult?.(m);return}if(b(m)&&m.ok===!0){c(w(m.value));return}n.onDiscardedResult?.(m),c(l(n.normalize(b(m)?m.error:m)))},()=>{this.noteDisconnected(),c(l(n.disconnectedError))})})}async claim(e,n={}){if(this.closed)return l({code:"DISCONNECTED"});if(n.signal?.aborted)return l({code:"ABORTED"});let o=n.timeoutMs??5e3;qe("ClaimOptions.timeoutMs",o);let i=me("claim");r(this,Ce).set(i,e);let s;try{s=this.remote.__ddClaim({claimId:i,identifier:e.identifier,version:e.version,fields:Object.keys(e.fields)})}catch(O){return y("a claim could not be sent to the Datadog host",{side:this.role,claimId:i,identifier:e.identifier,version:e.version,cause:S(O)}),a(this,I,Le).call(this,i),this.noteDisconnected(),l({code:"DISCONNECTED"})}s=s.then(O=>O,()=>(this.noteDisconnected(),l({code:"DISCONNECTED"})));let c=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(!c.ok)return a(this,I,Le).call(this,i),c;if(!b(c.value)||!b(c.value.values))return a(this,I,Le).call(this,i),this.send("__ddRelease",()=>this.remote.__ddRelease(i)),l({code:"INVALID_RESULT",issues:[{message:"Malformed claim success payload.",path:[]}]});let u=Et(gt(e),c.value.values);if(u)return a(this,I,Le).call(this,i),this.send("__ddRelease",()=>this.remote.__ddRelease(i)),l(u);let h=new Map,m={},f={contract:e,values:h,valueListeners:new Set,invalidationListeners:new Set,releaseController:new AbortController,released:!1,hydrated:!1};for(let[O,D]of Object.entries(e.fields)){if(D.kind==="function"){m[O]=(...T)=>this.callFunction(i,f,O,D,T);continue}let H=we(D.schema,c.value.values[O]);if(!H.ok)return a(this,I,Le).call(this,i),this.send("__ddRelease",()=>this.remote.__ddRelease(i)),l({code:"INVALID_RESULT",issues:He(O,H.error)});let M=new Ht(H.value);h.set(O,M),m[O]=M}r(this,Te).set(i,f);let C=r(this,Z).get(i);C&&this.receiveValues(i,C);let _=f.invalidation??r(this,q).get(i);return a(this,I,Le).call(this,i),_?(a(this,I,Ot).call(this,i,f,!0,_),l(_)):w({fields:m,release:()=>a(this,I,Ot).call(this,i,f,!0),onValuesChanged:O=>f.released?()=>{}:(f.valueListeners.add(O),()=>f.valueListeners.delete(O)),onInvalidated:O=>{let D=f.invalidation;return D?(globalThis.queueMicrotask(()=>O(D)),()=>{}):f.released?()=>{}:(f.invalidationListeners.add(O),()=>f.invalidationListeners.delete(O))}})}async callFunction(e,n,o,i,s){if(this.closed)throw Ee(n.contract,o,{code:"DISCONNECTED"});if(n.released)throw Ee(n.contract,o,{code:"ABORTED"});if(s.length!==1)throw Ee(n.contract,o,{code:"INVALID_ARGUMENT",issues:[{message:`Expected one named inputs object, received ${s.length} arguments.`,path:[o,"inputs"]}]});let c=Vt(o,i,s[0]);if(!c.ok)throw Ee(n.contract,o,{code:"INVALID_ARGUMENT",issues:c.error});let u=me("call"),h;try{h=this.remote.__ddCall({claimId:e,callId:u,field:o,inputs:c.value})}catch{throw this.noteDisconnected(),Ee(n.contract,o,{code:"DISCONNECTED"})}let m=await this.settleRemoteResult(h,{timeoutMs:Kn(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=>{b(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 Ee(n.contract,o,C)}let f=Bn(o,i,m.value);if(!f.ok)throw Ee(n.contract,o,{code:"INVALID_RESULT",issues:f.error});return f.value}receiveValues(e,n){if(!k(e,B)){y("ignored a __ddValues envelope with an invalid claim id",{side:this.role,claimId:e,maxClaimIdLength:B});return}let o=r(this,Te).get(e),i=r(this,Ce).get(e);if(!b(n)){let h={code:"INVALID_RESULT",issues:[{message:"The host value snapshot must be an object.",path:[]}]};o?a(this,I,je).call(this,e,o,h,!0):i?(r(this,q).set(e,h),r(this,Z).delete(e)):y("ignored a __ddValues envelope for an unknown claim",{side:this.role,claimId:e,receivedValues:typeof n});return}if(!o){if(!i)return;let m=r(this,Z).has(e)?kt(gt(i),n):Et(gt(i),n);if(m){r(this,q).set(e,m),r(this,Z).delete(e);return}if(!r(this,q).has(e)){let f=r(this,Z).get(e);r(this,Z).set(e,Object.freeze({...f,...n}))}return}let s=o.hydrated?kt(o.values.keys(),n):Et(o.values.keys(),n);if(s){a(this,I,je).call(this,e,o,s,!0);return}o.hydrated=!0;let c=[];for(let[h,m]of Object.entries(n)){let f=o.values.get(h),C=o.contract.fields[h];if(!f||!C||C.kind!=="value")continue;let _=we(C.schema,m);if(!_.ok){let O={code:"INVALID_RESULT",issues:He(h,_.error)};a(this,I,je).call(this,e,o,O,!0);return}c.push([f,_.value])}let u=[];for(let[h,m]of c)h.set(m)&&u.push(h);for(let h of u)h.notify();u.length>0&&ge(o.valueListeners)}receiveInvalidation(e,n){if(!k(e,B)){y("ignored a __ddInvalidate envelope with an invalid claim id",{side:this.role,claimId:e,maxClaimIdLength:B});return}let o=Ct(n,["INVALID_RESULT","UNRECOGNIZED"]),i=r(this,Te).get(e);if(i){a(this,I,je).call(this,e,i,o,!1);return}r(this,Ce).has(e)&&r(this,q).set(e,o)}async receiveClaim(e){if(this.closed)return l({code:"DISCONNECTED"});let n=$n(e);if(n)return l(n);if(r(this,F).has(e.claimId))return l({code:"INVALID_RESULT",issues:[{message:`Claim id "${e.claimId}" is already live.`,path:["claimId"]}]});if(r(this,F).size>=It)return l({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 l({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 l({code:"INVALID_RESULT",issues:[{message:`The host provider for "${e.identifier}" is disposed.`,path:[]}]});let c=new Map,u={releases:[],module:s,fields:c};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 h={},m={ready:!1},f=!1,C=!1,_=!1,O=new Set,D=new Map,H=()=>{if(C=!1,!r(this,F).has(e.claimId))return;let T=!_;if(!T&&O.size===0)return;let A=T?[...D.keys()]:[...O];_=!0,O.clear();let U={};for(let z of A){let oe=D.get(z);if(!oe)continue;let j=Ut(z,oe.field.schema,oe.provider);if(!j.ok){a(this,I,Bt).call(this,e.claimId,Tt(e.identifier,z,j.error));return}U[z]=j.value}this.send("__ddValues",()=>this.remote.__ddValues(e.claimId,U))},M=()=>{if(r(this,F).has(e.claimId)){if(!m.ready){f=!0;return}C||(C=!0,globalThis.queueMicrotask(H))}};for(let T of e.fields){let A=s.contract.fields[T];if(!A)return this.receiveRelease(e.claimId),l({code:"CONTRACT_INCOMPATIBLE",field:T});if(c.set(T,A),A.kind==="function"){let j=Object.hasOwn(s.implementation,T)?s.implementation[T]:void 0;if(!b(j)||typeof j.invoke!="function")return this.receiveRelease(e.claimId),l({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),l({code:"INVALID_RESULT",issues:[{message:"The host implementation is not a live value.",path:[T]}]});D.set(T,{field:A,provider:U});let z;try{z=U.subscribe(()=>{O.add(T),M()})}catch(j){return this.receiveRelease(e.claimId),l({code:"INVALID_RESULT",issues:Tt(e.identifier,T,j)})}if(typeof z!="function")return this.receiveRelease(e.claimId),l({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 L(`unsubscribe for interrupted claim ${e.claimId}`,z),this.closed?l({code:"DISCONNECTED"}):l({code:"INVALID_RESULT",issues:[{message:`The host provider for "${e.identifier}" was disposed during claim setup.`,path:[]}]});u.releases.push(z);let oe=Ut(T,A.schema,U);if(!oe.ok)return this.receiveRelease(e.claimId),l({code:"INVALID_RESULT",issues:Tt(e.identifier,T,oe.error)});h[T]=oe.value}return m.ready=!0,f&&M(),w({values:h})}async receiveFunctionCall(e){if(this.closed)return l({code:"DISCONNECTED"});let n=Gn(e);if(n)return l(n);let o=r(this,F).get(e.claimId);if(!o)return l({code:"DISCONNECTED"});let i=o.fields.get(e.field);if(!i||i.kind!=="function")return l({code:"CONTRACT_INCOMPATIBLE",field:e.field});if(r(this,se).has(e.callId))return l({code:"INVALID_ARGUMENT",issues:[{message:`Function call id "${e.callId}" is already active.`,path:["callId"]}]});if(xt>=On)return l({code:"FUNCTION_FAILED",field:e.field});let s=Vt(e.field,i,e.inputs);if(!s.ok)return y("the host rejected the inputs of a function call",{side:this.role,claimId:e.claimId,callId:e.callId,target:`${o.module.contract.identifier}.${e.field}`,issueCount:s.error.length}),l({code:"INVALID_ARGUMENT",issues:[{message:"The function inputs do not satisfy the host schema.",path:[e.field,"inputs"]}]});let c=Object.hasOwn(o.module.implementation,e.field)?o.module.implementation[e.field]:void 0;if(!b(c)||typeof c.invoke!="function")return l({code:"CONTRACT_INCOMPATIBLE",field:e.field});let u=new AbortController,h=()=>{},m=new Promise(A=>{h=A}),f={claimId:e.claimId,controller:u,interrupt(A){u.signal.aborted||(u.abort(),h({status:"interrupted",reason:A}))}};xt+=1,r(this,se).set(e.callId,f);let C=Kn(i),_=globalThis.performance.now()+C,O=globalThis.setTimeout(()=>f.interrupt("timed-out"),C),D;try{let A=c.invoke(s.value,Object.freeze({signal:u.signal}));globalThis.performance.now()>=_&&f.interrupt("timed-out"),D=Promise.resolve(A).then(U=>globalThis.performance.now()>=_?(f.interrupt("timed-out"),st(U),{status:"interrupted",reason:"timed-out"}):{status:"returned",value:U},U=>globalThis.performance.now()>=_?(f.interrupt("timed-out"),{status:"interrupted",reason:"timed-out"}):{status:"threw",cause:U})}catch(A){globalThis.performance.now()>=_&&f.interrupt("timed-out"),D=Promise.resolve({status:"threw",cause:A})}let H=D.finally(()=>{xt-=1,r(this,se).get(e.callId)===f&&r(this,se).delete(e.callId)}),M=await Promise.race([H,m]);if(globalThis.clearTimeout(O),M.status==="interrupted")return H.then(A=>{A.status==="returned"&&st(A.value)}),M.reason==="timed-out"?l({code:"TIMED_OUT",timeoutMs:C}):l({code:"DISCONNECTED"});if(this.closed||u.signal.aborted||r(this,F).get(e.claimId)!==o)return M.status==="returned"&&st(M.value),l({code:"DISCONNECTED"});if(M.status==="threw")return y("a host function implementation threw",{side:this.role,claimId:e.claimId,callId:e.callId,target:`${o.module.contract.identifier}.${e.field}`,cause:S(M.cause)}),l({code:"FUNCTION_FAILED",field:e.field});let T=jn(e.field,i,M.value);return T.ok?T.value:(y("a host function returned an invalid result",{side:this.role,claimId:e.claimId,callId:e.callId,target:`${o.module.contract.identifier}.${e.field}`,issues:T.error}),l({code:"INVALID_RESULT",issues:[{message:"The host function returned a result that does not satisfy its schema.",path:[e.field]}]}))}receiveFunctionCancel(e){if(!b(e)||!k(e.claimId,B)||!k(e.callId,tt)){y("ignored a malformed __ddCancel envelope",{side:this.role,request:b(e)?{claimId:e.claimId,callId:e.callId}:{malformed:!0,received:typeof e}});return}let n=r(this,se).get(e.callId);n?.claimId===e.claimId&&n.interrupt("cancelled")}receiveRelease(e){if(!k(e,B)){y("ignored a __ddRelease with an invalid claim id",{side:this.role,claimId:e,maxClaimIdLength:B});return}let n=r(this,F).get(e);if(n){r(this,F).delete(e);for(let o of r(this,se).values())o.claimId===e&&o.interrupt("cancelled");for(let o of n.releases)L(`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,We=new WeakMap,dt=new WeakMap,I=new WeakSet,jt=function(){r(this,dt)||(d(this,dt,!0),L("Penpal connection",()=>this.penpal.destroy()),L("operational port",()=>this.port.close()))},Le=function(e){r(this,Ce).delete(e),r(this,Z).delete(e),r(this,q).delete(e)},Ot=function(e,n,o,i){if(n.released)return!1;n.released=!0,n.invalidation=i,n.releaseController.abort();for(let s of n.values.values())s.freeze();return n.valueListeners.clear(),n.invalidationListeners.clear(),r(this,Te).delete(e),o&&this.send("__ddRelease",()=>this.remote.__ddRelease(e)),!0},je=function(e,n,o,i){let s=[...n.invalidationListeners];if(!a(this,I,Ot).call(this,e,n,i,o))return;(o.code==="DISCONNECTED"?x:y)("a live claim was invalidated",{side:this.role,claimId:e,identifier:n.contract.identifier,version:n.contract.version,observedListeners:s.length,error:J(o)}),ge(s,o)},Bt=function(e,n){let o=r(this,F).get(e);o&&(y("the host invalidated a claim it was serving",{side:this.role,claimId:e,identifier:o.module.contract.identifier,version:o.module.contract.version,issues:n}),this.receiveRelease(e),this.send("__ddInvalidate",()=>this.remote.__ddInvalidate(e,{code:"INVALID_RESULT",issues:n})))};function ko(t,e){if(!b(t))return{malformed:!0,received:typeof t};let n={};for(let o of e)n[o]=t[o];return n}var zt=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=Jn(e,this.modules);return o?Promise.resolve(l(o)):this.endpoint.claim(e,n)}};function Uo(t){return b(t)&&t.role==="host"&&Array.isArray(t.modules)}function Vo(t){let e=new Set,n=[];for(let o of t){if(!b(o)||!k(o.identifier)||!De(o.version))continue;let i=JSON.stringify([o.identifier,o.version]);e.has(i)||(e.add(i),n.push({identifier:o.identifier,version:o.version}))}return n}async function Fo(t,e,n,o,i,s,c){let u,h,m=!1,f=!1,C,_=new Promise((g,R)=>{C=R});try{h=new mt(t,g=>{u?u.noteDisconnected(g):(m=!0,g||t.close(),C?.({code:"DISCONNECTED"}))},c,e)}catch(g){return L("failed operational port",()=>t.close()),l({code:"TRANSPORT_FAILED",cause:g})}let O=!1,D=0,H=()=>{},M=new Promise(g=>{H=g}),T=g=>{O||(O=!0,H(g))},A=(g,R)=>{let N=Y=>(x("an embedding operation was refused",{side:e,operation:R,expectedRole:g,reason:Y,pendingEndpointOperations:D}),new Error(Y));return u?u.role===g?Promise.resolve(u):Promise.reject(N("The embedding operation is not valid here.")):O||D>=bn?Promise.reject(N("The embedding endpoint is not ready for work.")):(D+=1,M.then(Y=>{if(!Y||Y.role!==g)throw N("The embedding operation is not valid here.");return Y}).finally(()=>{D-=1}))},U=e==="host"?{role:"host",modules:i.map(({contract:g})=>({identifier:g.identifier,version:g.version})),surfaceId:s}:{role:"app"},z=(g,R,N,Y)=>(Y.ok||x(`${g} was rejected`,{side:e,request:ko(R,N),error:J(Y.error)}),Y),oe={__ddDescribe:()=>U,__ddClaim:g=>A("host","__ddClaim").then(R=>R.receiveClaim(g).then(N=>z("__ddClaim",g,["claimId","identifier","version","fields"],N))),__ddRelease:g=>A("host","__ddRelease").then(R=>R.receiveRelease(g)),__ddValues:(g,R)=>A("app","__ddValues").then(N=>N.receiveValues(g,R)),__ddCall:g=>A("host","__ddCall").then(R=>R.receiveFunctionCall(g).then(N=>(z("__ddCall",g,["claimId","callId","field"],N instanceof So?N.value:N),N))),__ddCancel:g=>A("host","__ddCancel").then(R=>R.receiveFunctionCancel(g)),__ddInvalidate:(g,R)=>A("app","__ddInvalidate").then(N=>N.receiveInvalidation(g,R)),__ddClose:()=>(u||(f=!0),A(e,"__ddClose").then(g=>g.close(!1)))},j;try{j=Po({messenger:new No({port:t}),methods:oe,timeout:n})}catch(g){return h.stop(),rt(t),globalThis.setTimeout(()=>t.close(),xe),l({code:"TRANSPORT_FAILED",cause:g})}let un,pn,hn=()=>un?.({code:"ABORTED"}),fn=new Promise((g,R)=>{un=R}),mn=new Promise((g,R)=>{pn=R}),po=globalThis.setTimeout(()=>pn?.({code:"TIMED_OUT"}),Math.max(0,n));o.addEventListener("abort",hn,{once:!0});let At="handshake";try{if(o.aborted)throw Object.assign(new Error("The connection was aborted."),{code:"ABORTED"});let g=await Promise.race([j.promise,fn,mn,_]);At="peer-description";let R=await Promise.race([g.__ddDescribe(),fn,mn,_]);if(At="validation",!(e==="app"?Uo(R):b(R)&&R.role==="app"))throw new Error(`Expected an embedding ${e==="app"?"host":"app"} using the operational protocol.`);if(u=new bt(e,g,j,t,i,n),m)throw Object.assign(new Error("The transport disconnected before establishment completed."),{code:"DISCONNECTED"});if(f)throw Object.assign(new Error("The peer requested to close before establishment completed."),{code:"DISCONNECTED"});return T(u),u.attachHeartbeat(h),w({endpoint:u,description:R})}catch(g){let R=zn(g,n);return x("the operational protocol could not be established",{side:e,stage:At,timeoutMs:n,describedPeer:!!u,error:J(R),cause:S(g)}),h.stop(),u?u.close():Un(j,t),l(R)}finally{T(void 0),globalThis.clearTimeout(po),o.removeEventListener("abort",hn)}}function xo(t){let e=t.endpoint,n=t.description;return{connection:new zt(e,Vo(n.modules)),surfaceId:typeof n.surfaceId=="string"?n.surfaceId:void 0,closeSignal:e.closeSignal,close:()=>e.close()}}async function Zn(t,e,n,o){let i=await Fo(t,"app",e,n,[],void 0,o);return i.ok?w(xo(i.value)):i}var Bo=[1];async function Wo(t,e,n=1e4){if(e.aborted)return t.close(),l({code:"ABORTED"});let o=await Sn(t,Bo,n,e);return o.ok?Zn(o.value.operationalPort,n,e,kn):o}var ze,$t=class{constructor(){p(this,ze)}next(){let e=r(this,ze)??Tn;return d(this,ze,Math.min(e*2,Cn)),e}reset(){d(this,ze,void 0)}};ze=new WeakMap;function zo(){return typeof globalThis.window<"u"&&globalThis.window.parent!==globalThis.window}function $o(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,W,de,ee,ce,le,te,be,$e,ke,v,Xn,Jt,Kt,Zt,Xt,yt,Yn,Ne,Gt=class{constructor(){p(this,v);p(this,ae,new AbortController);p(this,Se,new Set);p(this,ct,new $t);p(this,W,{state:"connecting"});p(this,de);p(this,ee);p(this,ce);p(this,le);p(this,te);p(this,be,0);p(this,$e,!1);p(this,ke,!1);if(!zo()){d(this,W,{state:"not-embedded"});return}a(this,v,Xt).call(this),a(this,v,Jt).call(this)}getSnapshot(){return r(this,W)}subscribe(e){return r(this,Se).add(e),()=>{r(this,Se).delete(e)}}close(){if(r(this,W).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,yt).call(this);let e=r(this,de);d(this,de,void 0),a(this,v,Ne).call(this,{state:"closed"}),e?.close(),r(this,Se).clear()}};ae=new WeakMap,Se=new WeakMap,ct=new WeakMap,W=new WeakMap,de=new WeakMap,ee=new WeakMap,ce=new WeakMap,le=new WeakMap,te=new WeakMap,be=new WeakMap,$e=new WeakMap,ke=new WeakMap,v=new WeakSet,Xn=async function(e){let n=await Mn(globalThis.window,wn,e);return n.ok?Wo(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,be,r(this,be)+1);let e=new AbortController;d(this,ee,e);let n;try{n=await a(this,v,Xn).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),!$o(n.error)){a(this,v,yt).call(this),y("the app connection was rejected",{side:"app",attempt:r(this,be),retryable:!1,error:J(n.error)}),a(this,v,Ne).call(this,{state:"rejected",error:n.error});return}a(this,v,Ne).call(this,r(this,W).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,yt).call(this);let o=()=>{r(this,ae).signal.aborted||r(this,de)!==n.value||(d(this,de,void 0),d(this,te,{code:"DISCONNECTED"}),x("the app lost its established connection",{side:"app",attempt:r(this,be),surfaceId:n.value.surfaceId}),a(this,v,Xt).call(this),a(this,v,Ne).call(this,{state:"reconnecting",lastError:r(this,te)}),a(this,v,Kt).call(this))};if(n.value.closeSignal.addEventListener("abort",o,{once:!0}),n.value.closeSignal.aborted){o();return}a(this,v,Ne).call(this,{state:"connected",connection:n.value.connection,surfaceId:n.value.surfaceId})},Kt=function(){if(r(this,ae).signal.aborted||r(this,ke)||r(this,ce)!==void 0)return;let e=r(this,ct).next();x("retrying the app connection",{side:"app",state:r(this,W).state,failedAttempts:r(this,be),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,Yn).call(this)},et))},yt=function(){r(this,le)!==void 0&&(globalThis.clearTimeout(r(this,le)),d(this,le,void 0))},Yn=function(){if(r(this,ae).signal.aborted||r(this,W).state==="connected"||r(this,W).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};y("the app gave up connecting to its Datadog host",{side:"app",state:r(this,W).state,failedAttempts:r(this,be),gaveUpAfterMs:et,error:J(e)}),a(this,v,Ne).call(this,{state:"rejected",error:e})},Ne=function(e){r(this,W)!==e&&(d(this,W,e),ge(r(this,Se)))};var Qn=Object.freeze({connect(){return new Gt}});function qn(t){return t.join(", ")}function Go(t){return t.map(e=>`${e.path.length>0?e.path.join("."):"(root)"}: ${e.message}`).join("; ")}function Jo(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 (${Jo(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 ${qn(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 ${qn(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 (${Go(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 Ko=0,Zo=Object.freeze({status:"pending"}),Xo=Object.freeze({status:"unavailable"}),Yo=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."}),eo=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 Zo}function to(){return Xo}function Qo(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))},Ko)))}})}owner;resource;notify(){ge(r(this,Re))}get isActive(){return r(this,ve)}};Re=new WeakMap,pe=new WeakMap,ve=new WeakMap;var Ae,$,Ie,G,ne,he,Je,E,no,oo,ro,on,Ge,ye,ue,Ue,nn=class{constructor(e,n){p(this,E);p(this,Ae);p(this,$);p(this,Ie,en());p(this,G);p(this,ne);p(this,he);p(this,Je,[]);Fe(this,"getSnapshot",()=>r(this,Ie));Fe(this,"subscribe",e=>r(this,Ae).subscribe(e));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,E,ye).call(this),d(this,G,e.connection),a(this,E,Ue).call(this,en()),a(this,E,no).call(this,e.connection);return;case"connecting":case"reconnecting":this.reset();return;case"not-embedded":d(this,G,void 0),a(this,E,ye).call(this),a(this,E,Ue).call(this,to());return;case"rejected":d(this,G,void 0),a(this,E,ye).call(this),a(this,E,ue).call(this,Yt(e.error));return;case"closed":d(this,G,void 0),a(this,E,ye).call(this),a(this,E,ue).call(this,Yo);return;default:return e}}fail(e){d(this,G,void 0),a(this,E,ye).call(this),a(this,E,ue).call(this,e)}reset(){d(this,G,void 0),a(this,E,ye).call(this),a(this,E,Ue).call(this,en())}};Ae=new WeakMap,$=new WeakMap,Ie=new WeakMap,G=new WeakMap,ne=new WeakMap,he=new WeakMap,Je=new WeakMap,E=new WeakSet,no=function(e){let n=new AbortController;d(this,ne,n);let o;try{o=e.claim(r(this,$),{signal:n.signal})}catch(i){y("a claim could not be requested",{side:"app",identifier:r(this,$).identifier,current:a(this,E,Ge).call(this,e,n),cause:S(i)}),a(this,E,Ge).call(this,e,n)&&(d(this,ne,void 0),a(this,E,ue).call(this,qt));return}o.then(i=>{if(!a(this,E,Ge).call(this,e,n)){i.ok&&i.value.release();return}if(d(this,ne,void 0),!i.ok){if(i.error.code==="PEER_LACKS_MODULE"){x("the Datadog host does not offer this module",{side:"app",identifier:r(this,$).identifier,version:r(this,$).version}),a(this,E,Ue).call(this,to());return}if(i.error.code==="ABORTED"){a(this,E,ue).call(this,qt);return}a(this,E,ue).call(this,Qt(i.error));return}a(this,E,oo).call(this,e,i.value)},i=>{y("a claim request rejected",{side:"app",identifier:r(this,$).identifier,current:a(this,E,Ge).call(this,e,n),cause:S(i)}),a(this,E,Ge).call(this,e,n)&&(d(this,ne,void 0),a(this,E,ue).call(this,qt))})},oo=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,E,ro).call(this,n,o))),r(this,Je).push(n.onValuesChanged(()=>{r(this,he)===n&&a(this,E,on).call(this,n)})),a(this,E,on).call(this,n)},ro=function(e,n){if(r(this,he)!==e)return;let o=Qt(n);a(this,E,ye).call(this),a(this,E,ue).call(this,o)},on=function(e){let n=Object.entries(r(this,$).fields),o=n.map(([s])=>s),i=Object.create(null);for(let[s,c]of n){let u=e.fields[s];i[s]=c.kind==="value"?u.get():u}if(r(this,Ie).status==="ready"){let s=r(this,Ie).fields;if(o.every(c=>Object.is(s[c],i[c])))return}a(this,E,Ue).call(this,Object.freeze({status:"ready",fields:Object.freeze(i)}))},Ge=function(e,n){return r(this,Ae).isActive&&r(this,G)===e&&r(this,ne)===n&&!n.signal.aborted},ye=function(){r(this,ne)?.abort(),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){y("a Datadog App claim failed",{side:"app",identifier:r(this,$).identifier,version:r(this,$).version,code:e.code,action:e.action,reason:e.message}),a(this,E,Ue).call(this,Qo(e))},Ue=function(e){r(this,Ie)!==e&&(d(this,Ie,e),r(this,Ae).notify())};var tn=Object.freeze({state:"connecting"});function qo(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?qo(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,P,io,so,ao,co,an,dn,cn,sn=class{constructor(e){this.connector=e;p(this,P);p(this,lt,new WeakMap);p(this,X,new Set);p(this,ut,{activate:e=>a(this,P,ao).call(this,e),deactivate:e=>a(this,P,co).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,P,io).call(this);let e=!0;return()=>{e&&(e=!1,d(this,Ve,r(this,Ve)-1),r(this,Ve)===0&&a(this,P,so).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,P=new WeakSet,io=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,P,cn).call(this,"connect",n);return}d(this,fe,e);try{d(this,Ye,e.subscribe(()=>a(this,P,an).call(this,e))),a(this,P,an).call(this,e)}catch(n){a(this,P,dn).call(this,e),a(this,P,cn).call(this,"subscribe",n);return}},so=function(){let e=r(this,fe);e&&a(this,P,dn).call(this,e),d(this,_e,void 0);for(let n of r(this,X))n.reset()},ao=function(e){if(r(this,X).add(e),r(this,_e)){e.fail(r(this,_e));return}e.sync(r(this,fe)?.getSnapshot())},co=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&&L("embedding connection handle unsubscribe",()=>n());for(let o of r(this,X))L("embedding claim resource reset",()=>o.reset());L("embedding connection handle close",()=>e.close())},cn=function(e,n){y("the embedding connection could not be started",{side:"app",step:e,affectedResources:r(this,X).size,cause:S(n)}),d(this,_e,eo);for(let o of r(this,X))o.fail(eo)};function lo(t){return new sn(t)}var er=lo(Qn),tr=vn(er);import{useSyncExternalStore as nr}from"react";var ln=new WeakMap;function uo(t){return t==="connecting"||t==="reconnecting"}function or(t,e){let n=ln.get(e);if(!n){let o=yn(t),i;n=new Promise(h=>{i=h}),ln.set(e,n);let s,c=!1,u=()=>{c||uo(e.getSnapshot().state)||(c=!0,s?.(),ln.delete(e),Rn(t,o),i())};s=e.subscribe(u),c?s():u()}throw n}function rr(){throw new Error("useDatadogAppEmbedding does not support server rendering: the Datadog App embedding connection only exists in the browser.")}function ir(t){throw new Error(t.state==="rejected"?`The Datadog App embedding connection was rejected: ${t.error.code}.`:"The Datadog App embedding connection closed.")}function sr(t){let e=An(),n=e.getEmbeddingMetadata(),o=nr(n.subscribe,n.getSnapshot,rr);return t?.suspense&&(uo(o.state)&&or(e,n),(o.state==="rejected"||o.state==="closed")&&ir(o)),o}export{tr as DatadogAppProvider,sr as useDatadogAppEmbedding};
7
7
  //# sourceMappingURL=index.js.map