1!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._posthogChunkIds=e._posthogChunkIds||{},e._posthogChunkIds[n]="01a0804f-843d-7812-a01e-d64631953452")}catch(e){}}();(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,381674,383938,845029,491421,454862,935792,689454,e=>{"use strict";var t=e.i(297068),r=e.i(96650),i=e.i(746632);function n(e,t){let r=t?.config;switch(t?.level){case"success":i.toast.success(e,r);return;case"warning":i.toast.warning(e,r);return;case"error":i.toast.error(e,r);return;case"info":i.toast.info(e,r);return;default:(0,i.toast)(e,r)}}e.s(["showAppHostToast",0,n],383938);var o=e.i(855911),a=e.i(156419),s=e.i(737093),c=e.i(779786),d=e.i(140937);let l=new Set(["VALIDATION_FAILED","NOT_AUTHENTICATED","NOT_FOUND","ALREADY_EXISTS","REVISION_CONFLICT","BATCH_CONFLICT","SCHEMA_VERSION_UNSUPPORTED","REFERENCE_RESTRICTED","REFERENCE_LIMIT_EXCEEDED","NOT_AUTHORIZED","CONNECTION_REQUIRED","OWNER_FROZEN","QUOTA_EXCEEDED","RATE_LIMITED","QUERY_TOO_COMPLEX","QUERY_TIMEOUT","RESPONSE_TOO_LARGE","CLEANUP_REQUIRED","INTERNAL_ERROR"]),p=new Set(["RATE_LIMITED","QUERY_TIMEOUT","INTERNAL_ERROR"]);function u(e){return new TextEncoder().encode(e).byteLength}function f(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}function g(e,t){return Object.keys(e).every(e=>t.includes(e))}function h(e){return Number.isSafeInteger(e)&&"number"==typeof e&&e>=0}function m(e){return void 0===e||"string"==typeof e}function y(e){return void 0===e||h(e)}function w(e){try{return!function(e){if(!f(e))throw TypeError("Invalid data error envelope");if(!g(e,["code","message","details","retryable"]))throw TypeError("Invalid data error envelope fields");if("string"!=typeof e.code||!l.has(e.code))throw TypeError("Invalid data error code");if("string"!=typeof e.message||0===e.message.length||u(e.message)>512)throw TypeError("Invalid data error message");if("boolean"!=typeof e.retryable)throw TypeError("Invalid data error retryability");let t=e.code;if(e.retryable&&!p.has(t))throw TypeError(`Data error ${t} cannot be retryable`);let r=function(e){if(void 0===e)return;if(!f(e))throw TypeError("Data error details must be an object");let t=function e(t,r,i){if(i.nodes+=1,i.nodes>256||r>8)throw TypeError("Data error details exceed structural bounds");if(null===t||"string"==typeof t||"boolean"==typeof t)return t;if("number"==typeof t){if(!Number.isFinite(t))throw TypeError("Data error details contain a non-finite number");return t}if(Array.isArray(t))return Object.freeze(t.map(t=>e(t,r+1,i)));if(!f(t))throw TypeError("Data error details must contain only JSON values");let n={};for(let[o,a]of Object.entries(t)){if(u(o)>256)throw TypeError("Data error detail key exceeds its byte limit");n[o]=e(a,r+1,i)}return Object.freeze(n)}(e,0,{nodes:0});if(!f(t))throw TypeError("Data error details must be an object");if(!function(e){switch(e.kind){case"validation":if(!g(e,["kind","issues"])||!Array.isArray(e.issues)||!e.issues.every(e=>f(e)&&g(e,["path","rule"])&&"string"==typeof e.path&&"string"==typeof e.rule))throw TypeError("Invalid validation error details");return;case"conflicts":if(!g(e,["kind","conflicts"])||!Array.isArray(e.conflicts)||!e.conflicts.every(e=>f(e)&&g(e,["index","id","uniqueKey","expectedRevision","actualRevision"])&&h(e.index)&&m(e.id)&&m(e.uniqueKey)&&("create"===e.expectedRevision||h(e.expectedRevision))&&y(e.actualRevision)))throw TypeError("Invalid conflict error details");return;case"references":if(!g(e,["kind","visibleIds","hiddenCount","totalCount"])||!Array.isArray(e.visibleIds)||!e.visibleIds.every(e=>"string"==typeof e)||!h(e.hiddenCount)||!h(e.totalCount))throw TypeError("Invalid reference error details");return;case"limit":if(!g(e,["kind","limit","current","retryAfterMs"])||!h(e.limit)||!y(e.current)||!y(e.retryAfterMs))throw TypeError("Invalid limit error details");return;case"cleanup":if(!g(e,["kind","affectedCount","maximumAtomicCount"])||!h(e.affectedCount)||!h(e.maximumAtomicCount))throw TypeError("Invalid cleanup error details");return;default:throw TypeError("Invalid data error detail kind")}}(t),u(JSON.stringify(t))>
116384)throw TypeError("Data error details exceed their byte limit");return t}(e.details);Object.freeze({code:t,message:e.message,...void 0===r?{}:{details:r},retryable:e.retryable})}(e),!0}catch{return!1}}var b=e.i(54144),v=e.i(537701);function I(e,t){return fetch(e,{credentials:"same-origin",...t})}let E=new Set(["TEAM_RUNTIME_SESSION_REQUIRED","STALE_RUNTIME_SESSION","INVALID_RUNTIME_SESSION"]);function T(e,t,r,i){let n=Error(e);return t&&(n.code=t),r&&(n.details=r),void 0!==i&&(n.retryable=i),n}async function R(e){try{let t=await e.clone().json();return(0,c.isObjectRecord)(t)&&"string"==typeof t.code?t.code:null}catch{return null}}async function O(e){let t=async t=>{let r=new Headers(e.init.headers);t&&r.set("X-Snow-App-Runtime-Token",t);let i=e.config?.workspaceRequest??I;return await i(e.input,{...e.init,headers:r})};if(e.config?.teamContext?.isTeamApp!==!0)return await t(null);let r=await e.config.getTeamRuntimeToken?.(),i=await t(r??null);if(i.ok||!e.config.refreshTeamRuntimeToken)return i;let n=await R(i);if(!n||!E.has(n))return i;let o=await e.config.refreshTeamRuntimeToken();return await t(o??null)}async function k(e){let t=await C(e),r=null;try{r=JSON.parse(t)}catch{r=null}if(!(0,c.isObjectRecord)(r)){if(e.ok)throw Error("SDK route returned an invalid response.");return{}}let{error:i,code:n,type:o,...a}=r;return{...a,..."string"==typeof i?{error:i}:{},..."string"==typeof n?{code:n}:{},..."string"==typeof o?{type:o}:{}}}function S(e){return(0,c.isObjectRecord)(e)?{..."string"==typeof e.error?{error:e.error}:{},..."string"==typeof e.code?{code:e.code}:{},...(0,c.isObjectRecord)(e.details)?{details:e.details}:{}}:{}}function A(e){return(0,c.isObjectRecord)(e)&&"text"===e.type&&"string"==typeof e.text}function N(e){return(0,c.isObjectRecord)(e)&&"string"==typeof e.id&&"string"==typeof e.app&&"string"==typeof e.label&&("connected"===e.status||"reconnect_required"===e.status)}function D(){return T(`HTTP response exceeds ${b.SDK_HTTP_LIMITS.MAX_RESPONSE_BYTES} bytes`,"HTTP_RESPONSE_TOO_LARGE")}async function P(e,t=b.SDK_HTTP_LIMITS.MAX_RESPONSE_BYTES){if(!function(e,t=b.SDK_HTTP_LIMITS.MAX_RESPONSE_BYTES){let r=e.headers.get("content-length");if(!r)return;let i=Number.parseInt(r,10);if(Number.isFinite(i)&&i>t)throw D()}(e,t),!e.body)return new Uint8Array;let r=e.body.getReader(),i=0,n=[];for(;;){let{done:e,value:o}=await r.read();if(e)break;if(o){if((i+=o.byteLength)>t){try{await r.cancel()}catch{}throw D()}n.push(o)}}let o=new Uint8Array(i),a=0;for(let e of n)o.set(e,a),a+=e.byteLength;return o}async function C(e){let t=await P(e);return new TextDecoder().decode(t)}async function _(e){let t=await e.config.sdkDataRuntimePreparation;if(!t)throw T("This data connection needs attention.","CONNECTION_REQUIRED");let r=await O({config:e.config,input:"/api/apps/sdk/data",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e.appId,method:e.method,runtimeSessionKey:e.config.sessionToken,runtimeDescriptor:t.descriptor,...void 0===e.alias?{}:{alias:e.alias},input:e.input})}}),i=await C(r),n=null;try{n=JSON.parse(i)}catch{n=null}if(!r.ok){if(!w(n))throw T("The operation could not be completed.","INTERNAL_ERROR");throw T(n.message,n.code,n.details,n.retryable)}if(!(0,c.isObjectRecord)(n)||!("result"in n))throw T("The operation could not be completed.","INTERNAL_ERROR");return n.result}async function j(e){let t=await e.config.sdkDataRuntimePreparation;if(!t)throw T("This file connection needs attention.","CONNECTION_REQUIRED");let r=await O({config:e.config,input:"/api/apps/sdk/owner-files",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e.config.appId,method:e.method,input
1:e.input,runtimeSessionKey:e.config.sessionToken,runtimeDescriptor:t.descriptor})}}),i=null;try{i=JSON.parse(new TextDecoder().decode(await P(r,2097152)))}catch(e){if(e instanceof Error&&"code"in e&&"HTTP_RESPONSE_TOO_LARGE"===e.code)throw T("The file response is too large.","RESPONSE_TOO_LARGE")}if(!r.ok){if(!w(i))throw T("The file operation could not be completed.","INTERNAL_ERROR");throw T(i.message,i.code,i.details,i.retryable)}if(!(0,c.isObjectRecord)(i)||!("result"in i))throw T("The file operation could not be completed.","INTERNAL_ERROR");return i.result}async function M(e){if(!e.sdkDataRuntimePreparation)return!1;let{descriptor:t}=await e.sdkDataRuntimePreparation,[r,i,n]=t.split(".");if(!r||!i||void 0!==n)throw T("This file connection needs attention.","CONNECTION_REQUIRED");try{let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=JSON.parse(atob(e.padEnd(4*Math.ceil(e.length/4),"=")));if(!(0,c.isObjectRecord)(t)||!(0,c.isObjectRecord)(t.metadata))throw TypeError("Invalid descriptor");let i=t.metadata.files;if(null==i)return!1;if(!(0,c.isObjectRecord)(i)||!Array.isArray(i.operations)||!Array.isArray(i.access)||"string"!=typeof i.declarationFingerprint||"number"!=typeof i.appAuthorityEpoch)throw TypeError("Invalid file declaration");return!0}catch{throw T("This file connection needs attention.","CONNECTION_REQUIRED")}}async function x(e){let t=e.replace?{idempotencyKey:e.idempotencyKey,size:e.blob.size,...e.replace}:{...e.options,idempotencyKey:e.idempotencyKey,type:e.blob.type||"application/octet-stream",size:e.blob.size},r=await j({config:e.config,method:e.replace?"reserveReplace":"reserveUpload",input:t});if((0,c.isObjectRecord)(r)&&"confirmed"===r.status&&(0,c.isObjectRecord)(r.file))return r.file;if(!(0,c.isObjectRecord)(r)||"reserved"!==r.status||"string"!=typeof r.uploadUrl||"string"!=typeof r.objectPath||"string"!=typeof r.reservationId||"string"!=typeof r.mediaType)throw T("The upload reservation was invalid.","INTERNAL_ERROR");if(!(await fetch(r.uploadUrl,{method:"PUT",body:e.blob,headers:{"Content-Type":r.mediaType,"x-upsert":"false"}})).ok)throw T("The file upload failed.","INTERNAL_ERROR");return j({config:e.config,method:e.replace?"confirmReplace":"confirmUpload",input:{reservationId:r.reservationId,objectPath:r.objectPath}})}async function L(e,t,r,i){let n=await O({config:i,input:"/api/apps/sdk/context",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,appId:e})}}),o=await k(n);if(!n.ok){if(429===n.status||"RATE_LIMITED"===o.code){let e=o.error||"App context limit reached. Please try again later.";r?.(e)}throw T(o.error||"App context update failed","string"==typeof o.code?o.code:void 0)}return o.result}async function U(e){let t="/api/apps/sdk/schedules";if(void 0!==e.path){if(!(0,v.isValidUUID)(e.path))throw Error("Invalid schedule id");t=`/api/apps/sdk/schedules/${encodeURIComponent(e.path)}`}let r=`${t}?appId=${encodeURIComponent(e.appId)}`,i=await O({config:e.config,input:r,init:{method:e.method,headers:{"Content-Type":"application/json"},body:e.body?JSON.stringify(e.body):void 0}}),n=await k(i);if(!i.ok){if(429===i.status||"RATE_LIMITED"===n.code){let t=n.error||"Schedule limit reached. Please try again later.";throw e.onRateLimited?.(t),Error(t)}throw Error(n.error||"Schedule request failed")}return n}async function q(e){let t,r=(e,t)=>({success:!1,error:e,...t?{errorCode:t}:{}});try{t=await O({config:e.config,input:"/api/apps/sdk/actions/call",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e.appId,actionName:e.actionName,input:e.input})}})}catch{return r("Action call failed","EXECUTION_ERROR")}let i=null;try{i=await k(t)}catch{if(t.ok)return r("Action call failed","EXECUTION_ERROR")}let n=(0,c.isObjectRecord)(i)?i:null,o="string"==typeof n?.error&&n.error.length>0?n.error:"Action call failed",a="string"==typeof n?.code?n.code:"EXECUTION_ERROR";if(!t.ok)return(429===t.status||"RATE_LIMITED"===a)&&e.onToast?.(o||"Rate limit reached. Please try again later."),"CREDITS_EXHAUSTED"===a&&e.onToast?.(o||"Credit limit exceeded."),r(o,a);let s=n&&"result"in n?n.result:i;return(0,c.isObjectRecord)(s)&&(void 0===s.content||Array.isArray(s.content)&&s.content.every(A))&&(!0===s.success||!1===s.success&&"string"==typeof s.error&&(void 0===s.errorCode||"string"==typeof s.errorCode))?s:r("Action call failed","EXECUTION_ERROR")}async function F(e){let t=await O({config:e.config,input:"/api/apps/sdk/notifications",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e.appId,appName:e.appName,input:e.input})}}),r=await k(t);if(!t.ok){if(429===t.status||"rate_limit"===r.type||"RATE_LIMITED"===r.code){let t=r.error||"Notification limit reached. Please try again later.";e.onToast?.(t)}
1throw T(r.error||"Notification send failed","string"==typeof r.code?r.code:void 0)}return r.result??r}async function K(e){var t;let r={appId:e.appId,providerSlug:e.input.app,tool:e.input.tool,...e.input.arguments?{arguments:e.input.arguments}:{},target:{type:"binding",bindingKey:e.input.binding,...e.input.selectionGrant?{selectionGrant:e.input.selectionGrant}:{}}},i=await O({config:e.config,input:"/api/apps/sdk/integrations/execute",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}}),n=await i.json().catch(()=>null),o=(0,c.isObjectRecord)(n)?n:null,a=S(n);if(!i.ok||(t=o?.result,!((0,c.isObjectRecord)(t)&&"boolean"==typeof t.successful&&(0,c.isObjectRecord)(t.data))||null!==t.error&&"string"!=typeof t.error)){let t=a.error||"Integration tool execution failed",r=a.code??"INTEGRATION_PROXY_FAILED";throw(429===i.status||"RATE_LIMITED"===r)&&e.onToast?.(t),"CREDITS_EXHAUSTED"===r&&e.onToast?.("Credit limit exceeded."),T(t,r,a.details)}return o.result}async function $(e){let t=await O({config:e.config,input:"/api/apps/sdk/integrations/selections/grant",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e.appId,providerSlug:e.providerSlug,bindingKey:e.bindingKey,tool:e.tool,connectionId:e.connectionId})}}),r=await t.json().catch(()=>null),i=(0,c.isObjectRecord)(r)?r:null,n=S(r);if(!t.ok||"string"!=typeof i?.selectionGrant)throw T(n.error||"Failed to authorize the selected account",n.code,n.details);return i.selectionGrant}async function z(e){let t=new URL("/api/apps/sdk/integrations/connections",window.location.origin);t.searchParams.set("appId",e.appId),t.searchParams.set("providerSlug",e.providerSlug);let r=await O({config:e.config,input:`${t.pathname}${t.search}`,init:{method:"GET"}}),i=await r.json().catch(()=>null),n=(0,c.isObjectRecord)(i)?i:null,o=S(i),a=n?.connections;if(!r.ok||!Array.isArray(a)||!a.every(N)){let t=o.error||"Failed to load integration connections";throw(429===r.status||"RATE_LIMITED"===o.code)&&e.onToast?.(t),T(t,o.code,o.details)}return a}async function G(e){let t=await O({config:e.config,input:"/api/apps/sdk/integrations/bindings/resolve",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e.appId,providerSlug:e.providerSlug,bindingKey:e.bindingKey,connectionId:e.connectionId})}});if(t.ok)return;let r=S(await t.json().catch(()=>null));throw T(r?.error||"Failed to save integration binding",r?.code,r?.details)}async function B(e,t,r){let i={method:e,redirect:"error",credentials:"omit"};"POST"===e&&(i.headers={"Content-Type":"application/json"},void 0!==r&&(i.body=JSON.stringify(r)));let n=await fetch(t,i);if(!n.ok)throw Error(`HTTP ${n.status}: ${n.statusText}`);let o=n.headers.get("content-type"),a=await C(n);return o?.includes("application/json")?JSON.parse(a):a}async function V(e){let t=await fetch(e,{redirect:"error",credentials:"omit"});if(!t.ok)throw Error(`HTTP ${t.status}: ${t.statusText}`);let r=await P(t),i=new ArrayBuffer(r.byteLength);new Uint8Array(i).set(r);let n=new Blob([i],{type:t.headers.get("content-type")??"application/octet-stream"});return await new Promise((e,t)=>{let r=new FileReader;r.onloadend=()=>{"string"==typeof r.result?e(r.result):t(Error("FileReader did not return a string"))},r.onerror=()=>{t(Error("Failed to read blob as data URL"))},r.readAsDataURL(n)})}function H(e,t,r){if(!(0,c.isObjectRecord)(e))throw Error(`${r}: params must be an object`);let i=e[t];if("string"!=typeof i)throw Error(`${r}: ${t} must be a string`);return i}var W=e.i(384891);async function J(e){let{id:t,method:r,params:i,config:n,iframe:o,targetOrigin:a}=e,{appId:s}=n;switch(r){case"ai.text":{let e;if(!(0,c.isObjectRecord)(i))throw Error("ai.text: params must be an object");let{model:r,input:d,stream:l,temperature:p,top_p:u,max_output_tokens:f,providerOptions:g,output:h,tools:m,maxToolRounds:y}=i;if("string"!=typeof r)throw Error("ai.text: model must be a string");if(!Array.isArray(d))throw Error("ai.text: input must be an array");let w=!0===l,b=await O({config:n,input:"/api/apps/sdk/ai/text",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:r,input:d,stream:w,temperature:p,top_p:u,max_output_tokens:f,providerOptions:g,output:h,tools:m,maxToolRounds:y,appI
1d:s})}});if(!b.ok){let e=await b.json(),t=(0,c.isObjectRecord)(e)?e:null;throw T("string"==typeof t?.error?t.error:"AI generation failed","string"==typeof t?.code?t.code:void 0)}if(!w){let e=await b.json();return{handled:!0,result:(0,c.isObjectRecord)(e)&&"result"in e?e.result:e}}if(!b.body)throw Error("ai.text: streaming response missing body");let v=b.body.getReader(),I=new TextDecoder,E="",R=[],k=null,S=()=>{if(0===R.length)return;let r=R.join("\n");if(R.length=0,r&&!k)try{(r=>{let i=function(e){let t=JSON.parse(e);if(!(0,c.isObjectRecord)(t)||"string"!=typeof t.type)throw Error("ai.text: invalid streaming event");if(("response.output_text.delta"===t.type||"response.reasoning.delta"===t.type)&&"string"==typeof t.delta)return{type:t.type,delta:t.delta};if("response.created"===t.type&&(0,c.isObjectRecord)(t.response)&&"string"==typeof t.response.id&&"string"==typeof t.response.model)return{type:t.type,response:{id:t.response.id,model:t.response.model}};if("response.output_text.done"===t.type&&"string"==typeof t.text)return{type:t.type,text:t.text};if("response.reasoning.done"===t.type&&"string"==typeof t.reasoning)return{type:t.type,reasoning:t.reasoning};if("response.completed"===t.type&&"response"in t)return{type:t.type,response:t.response};if("error"===t.type&&"error"in t)return{type:t.type,error:t.error};throw Error("ai.text: invalid streaming event")}(r);if("response.output_text.delta"===i.type)return o.contentWindow?.postMessage({type:"sdk-stream",id:t,event:"delta",delta:i.delta},a);if("response.reasoning.delta"===i.type)return o.contentWindow?.postMessage({type:"sdk-stream",id:t,event:"reasoning",delta:i.delta},a);if("error"===i.type){o.contentWindow?.postMessage({type:"sdk-stream",id:t,event:"error",error:i.error},a);let e=i.error;throw T((0,c.isObjectRecord)(e)&&"string"==typeof e.error?e.error:"string"==typeof e?e:"AI stream failed",(0,c.isObjectRecord)(e)&&"string"==typeof e.code?e.code:void 0)}"response.completed"===i.type&&(e=i.response)})(r)}catch(e){k=e instanceof Error?e:Error("AI stream failed")}},A=e=>{e?!e.startsWith(":")&&e.startsWith("data:")&&R.push(e.slice(5).trimStart()):S()};try{for(;;){let{done:e,value:t}=await v.read();if(e)break;let r=(E+=I.decode(t,{stream:!0})).indexOf("\n");for(;r>=0;){let e=E.slice(0,r);if(E=E.slice(r+1),e.endsWith("\r")&&(e=e.slice(0,-1)),A(e),k)break;r=E.indexOf("\n")}if(k)break}if(E+=I.decode()){let e=E;e.endsWith("\r")&&(e=e.slice(0,-1)),A(e)}S()}finally{await v.cancel().catch(()=>{})}if(k)throw k;if(void 0===e)throw Error("ai.text: stream ended without result");return o.contentWindow?.postMessage({type:"sdk-stream",id:t,event:"done"},a),{handled:!0,result:e}}case"ai.generateImage":{if(!(0,c.isObjectRecord)(i))throw Error("ai.generateImage: params must be an object");let{model:e,prompt:t,aspectRatio:r,size:o,resolution:a,outputFormat:d,seed:l,image:p,images:u,safetyTolerance:f,style:g,quality:h,background:m,inputFidelity:y,maskImageUrl:w}=i;if("string"!=typeof e)throw Error("ai.generateImage: model must be a string");if("string"!=typeof t)throw Error("ai.generateImage: prompt must be a string");let b=await O({config:n,input:"/api/apps/sdk/ai/image",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:e,prompt:t,aspectRatio:r,size:o,resolution:a,outputFormat:d,seed:l,image:p,images:u,safetyTolerance:f,style:g,quality:h,background:m,inputFidelity:y,maskImageUrl:w,appId:s})}}),v=await b.json(),I=(0,c.isObjectRecord)(v)?v:null;if(!b.ok)throw T("string"==typeof I?.error?I.error:"Image generation failed","string"==typeof I?.code?I.code:void 0);return{handled:!0,result:I?.result}}default:return{handled:!1}}}var Q=e.i(561746);let X=["html","markdown","links","screenshot"],Y=["desktop","mobile","fullPage"],Z=["success","info","warning","error"];var ee=e.i(17948),et=e.i(734500);function er(e){let t=Error(e.message);return t.code=e.code,e.details&&(t.details=e.details),t}function ei(e){let t=e.iframe.sandbox.contains("allow-same-origin")?window.location.origin:"*";e.iframe.contentWindow?.postMessage({type:"set-sdk-context",context:{appId:e.config.appId,appName:e.config.appName,userId:e.config.userId,userName:e.config.userName??""}},t)}async function en(e){if(!e.config.onPermissionPrompt)return null;let t=`${e.config.appId}:${e.operationId}`;if(e.permissionState.promptedOperationIds.has(t))return null;for(;e.permissionState.promptedOperationIds.size>=1e3;){let t=e.permissionState.promptedOperationIds.values().next().value;if("string"!=typeof t)break;e.permissionState.promptedOperationIds.delete(t)}e.permissionState.promptedOperationIds.add(t);try{return await e.config.onPermissionPrompt({appId:e.config.appId,appName:e.config.appName,a
1ppImage:e.config.appImage,permissionKey:e.permissionKey,sdkMethod:e.sdkMethod,targetUrl:e.targetUrl,targetDomain:e.targetDomain,source:e.config.source??"apps-page",operationId:e.operationId,declaredByApp:e.declaredByApp})}catch{return null}}function eo(e,t,r){if((0,W.isUrlAllowedByPatterns)(t,e.effectivePolicy.deniedDomains))throw er({code:"PERMISSION_DENIED",message:"Domain denied by user",details:r})}async function ea(e){if(e.policyState.effectivePolicy.effectivePermissions[e.permissionKey])return!1;let t=await en({config:e.config,permissionState:e.permissionState,operationId:e.permissionDetails.operationId,permissionKey:e.permissionKey,sdkMethod:e.permissionDetails.sdkMethod,targetUrl:e.permissionDetails.targetUrl,targetDomain:e.permissionDetails.targetDomain,declaredByApp:e.isPermissionRequested&&e.isManifestDomain});if(t?.decision==="granted"){if((t.scope??"always")==="once")return e.permissionState.deniedPermissions.delete(e.permissionKey),!0;if(t.effectivePolicy)return e.policyState.effectivePolicy=t.effectivePolicy,e.permissionState.deniedPermissions.delete(e.permissionKey),ei({config:e.config,policyState:e.policyState,iframe:e.iframe}),!1;throw er({code:"PERMISSION_REQUIRED",message:"Permission required for network access",details:e.permissionDetails})}if(t?.decision==="denied")throw t.effectivePolicy&&(e.policyState.effectivePolicy=t.effectivePolicy,ei({config:e.config,policyState:e.policyState,iframe:e.iframe})),er({code:"PERMISSION_DENIED",message:"Permission denied for network access",details:e.permissionDetails});throw er({code:"PERMISSION_REQUIRED",message:"Permission required for network access",details:e.permissionDetails})}async function es(e){let t=e.allowNetworkOperationOnce;if((0,et.canAccessHttpUrl)(e.policyState.effectivePolicy,e.url))return t;if(eo(e.policyState,e.url,e.permissionDetails),!e.isManifestDomain){let r=await en({config:e.config,permissionState:e.permissionState,operationId:e.permissionDetails.operationId,permissionKey:e.permissionKey,sdkMethod:e.permissionDetails.sdkMethod,targetUrl:e.url,targetDomain:e.permissionDetails.targetDomain,declaredByApp:!1});if(r?.effectivePolicy&&(e.policyState.effectivePolicy=r.effectivePolicy,ei({config:e.config,policyState:e.policyState,iframe:e.iframe})),r?.decision==="granted")(r.scope??"always")==="once"&&(t=!0),e.permissionState.deniedPermissions.delete(e.permissionKey);else if(r?.decision==="denied")throw er({code:"PERMISSION_DENIED",message:"Permission denied for network access",details:e.permissionDetails})}if(t)return!0;if(!(0,et.canAccessHttpUrl)(e.policyState.effectivePolicy,e.url))throw er({code:"DOMAIN_NOT_ALLOWED",message:`HTTP request blocked: ${e.permissionDetails.targetDomain} is not allowed`,details:{...e.permissionDetails,declaredByApp:e.isManifestDomain}});return!1}async function ec(e){let t,r="network.http",i=(0,W.getDomainFromUrl)(e.url),n={permissionKey:r,sdkMethod:e.sdkMethod,targetUrl:e.url,targetDomain:i,operationId:e.operationId};var o=e.url;try{t=new URL(o)}catch{throw er({code:"DOMAIN_NOT_ALLOWED",message:"HTTP request blocked: only HTTPS URLs are allowed",details:n})}if("https:"!==t.protocol)throw er({code:"DOMAIN_NOT_ALLOWED",message:"HTTP request blocked: only HTTPS URLs are allowed",details:n});e.permissionState.deniedPermissions.has(r)&&e.permissionState.deniedPermissions.delete(r);let a=e.policyState.effectivePolicy,s=!0===a.manifestRequestedPermissions[r],c=(0,W.isUrlAllowedByPatterns)(e.url,a.manifestRequestedDomains);eo(e.policyState,e.url,n);let d=await ea({config:e.config,policyState:e.policyState,permissionState:e.permissionState,iframe:e.iframe,permissionKey:r,permissionDetails:n,isPermissionRequested:s,isManifestDomain:c});if(d||await es({config:e.config,policyState:e.policyState,permissionState:e.permissionState,iframe:e.iframe,permissionKey:r,permissionDetails:n,url:e.url,isManifestDomain:c,allowNetworkOperationOnce:d}))return}function ed(e){let t=(0,ee.getSdkMethodPermissionKey)(e.sdkMethod);if(!t)throw er({code:"PERMISSION_REQUIRED",message:"Permission required for SDK access",details:{sdkMethod:e.sdkMethod,operationId:e.operationId}});if(!e.policyState.effectivePolicy.effectivePermissions[t])throw er({code:"PERMISSION_DENIED",message:`Permission denied for ${t}`,details:{permissionKey:t,sdkMethod:e.sdkMethod,operationId:e.operationId}})}let el=["dots","thumbnails","none"];function ep(e){return Error(`sdk.ui.lightbox.open: ${e}`)}function eu(e,t){let r,i,n,o;if("string"==typeof e)r=e;else if((0,c.isObjectRecord)(e))r=e.src,i=e.caption,n=e.alt;else throw ep(`images[${t}] must be a string or an object with src`);
1if("string"!=typeof r||0===r.length)throw ep(`images[${t}].src must be a non-empty string`);if(r.length>5242880)throw ep(`images[${t}].src exceeds the maximum length of 5242880 characters`);if(!((o=r.slice(0,12).toLowerCase()).startsWith("https://")||o.startsWith("data:image/")))throw ep(`images[${t}].src must be an https:// URL or a data:image/ URL`);let a={src:r};if(void 0!==i){if("string"!=typeof i)throw ep(`images[${t}].caption must be a string`);if(i.length>300)throw ep(`images[${t}].caption exceeds the maximum length of 300 characters`);let e=i.trim();e.length>0&&(a.caption=e)}if(void 0!==n){if("string"!=typeof n)throw ep(`images[${t}].alt must be a string`);if(n.length>200)throw ep(`images[${t}].alt exceeds the maximum length of 200 characters`);let e=n.trim();e.length>0&&(a.alt=e)}return a}var ef=e.i(640102);async function eg(e){var t;let{id:r,method:i,params:n,config:o,policyState:a,permissionState:s,iframe:l}=e,{appId:p,appName:u,httpHandler:f,onToast:g,onLightbox:h}=o,m=(0,c.isObjectRecord)(n)?n:null;switch(i){case"app.openRoute":{let e=H(n,"route","sdk.app.openRoute");return(0,d.requestOpenAppRoute)({appId:p,route:function(e){let t=e.trim();if(!t)throw Error("sdk.app.openRoute: route must be a non-empty string");let r=t.indexOf("#"),i=(r>=0?t.slice(0,r):t).trim();if(!i)throw Error("sdk.app.openRoute: route must include a path");if(i.startsWith("//"))throw Error("sdk.app.openRoute: route must be a path, not a host");if(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(i))try{let e=new URL(i);i=`${e.pathname}${e.search}`}catch{throw Error("sdk.app.openRoute: route must be a valid URL")}if(!i)throw Error("sdk.app.openRoute: route must include a path");return i.startsWith("/")?i:(i.startsWith("?"),`/${i}`)}(e)}),{handled:!0,result:void 0}}case"viewport.expand":{ed({policyState:a,sdkMethod:"viewport.expand",operationId:r});let e=o.getViewportController?.()??null;if(!e)throw Error("sdk.viewport is not available on this surface");let t=m?.area;if("card"!==t&&"plane"!==t&&"page"!==t)throw Error("sdk.viewport.expand: area must be 'card', 'plane', or 'page'");if(!function(e){if(document.activeElement===e)return!0;try{return e.matches(":hover")}catch{return!1}}(l))throw Error("sdk.viewport.expand requires current user interaction inside the app");return await e.expand(t),{handled:!0,result:{state:e.getState()}}}case"viewport.collapse":{let e=o.getViewportController?.()??null;if(!e)return{handled:!0,result:{state:"inline"}};return await e.collapse(),{handled:!0,result:{state:e.getState()}}}case"viewport.escape":{let e=o.getViewportController?.()??null;return e?.escape(),{handled:!0,result:void 0}}case"openExternal":{let e=(0,ef.parseExternalNavigation)(n);return await ec({config:o,policyState:a,permissionState:s,iframe:l,sdkMethod:"openExternal",url:e.url,operationId:r}),{handled:!0,result:await (0,ef.executeSharedBrowserCapability)({method:i,params:n})}}case"http.get":{let e=H(n,"url","sdk.http.get");return await ec({config:o,policyState:a,permissionState:s,iframe:l,sdkMethod:"http.get",url:e,operationId:r}),{handled:!0,result:await (f||B)("GET",e)}}case"http.post":{let e=H(n,"url","sdk.http.post");await ec({config:o,policyState:a,permissionState:s,iframe:l,sdkMethod:"http.post",url:e,operationId:r});let t=m?.body;return{handled:!0,result:await (f||B)("POST",e,t)}}case"http.getBlob":{let e=H(n,"url","sdk.http.getBlob");return await ec({config:o,policyState:a,permissionState:s,iframe:l,sdkMethod:"http.getBlob",url:e,operationId:r}),{handled:!0,result:await V(e)}}case"ui.toast":{let e=H(n,"message","sdk.ui.toast"),t=(0,c.isObjectRecord)(n)?n.variant:void 0,r=Z.find(e=>e===t);return g?.(e,r?{level:r}:void 0),{handled:!0,result:void 0}}case"ui.lightbox.open":{let e=function(e){if(!(0,c.isObjectRecord)(e))throw ep("params must be an object");let t=e.input;if(!(0,c.isObjectRecord)(t))throw ep("requires an options object");let r=t.images;if(!Array.isArray(r)||0===r.length)throw ep("requires a non-empty images array");if(r.length>30)throw ep("supports at most 30 images");let i=r.map(eu);if(i.reduce((e,t)=>e+t.src.length,0)>0x1400000)throw ep("total image data exceeds the maximum of 20971520 characters across all srcs");let n=0;
1if(void 0!==t.startIndex){if("number"!=typeof t.startIndex||!Number.isInteger(t.startIndex)||t.startIndex<0)throw ep("startIndex must be a non-negative integer");n=Math.min(t.startIndex,i.length-1)}let o=!1;if(void 0!==t.showDownload){if("boolean"!=typeof t.showDownload)throw ep("showDownload must be a boolean");o=t.showDownload}let a="dots";if(void 0!==t.indicators){if(!el.includes(t.indicators))throw ep(`indicators must be one of: ${el.join(", ")}`);a=t.indicators}return{images:i,startIndex:n,showDownload:o,indicators:a}}(n);if(!h)throw Error("sdk.ui.lightbox.open is not available in this context");return h(e),{handled:!0,result:void 0}}case"notifications.send":{if(!(0,c.isObjectRecord)(n))throw Error("sdk.notifications.send: params must be an object");let e=function(e){if(!(0,c.isObjectRecord)(e))throw Error("sdk.notifications.send: input must be an object");if("string"!=typeof e.title||"string"!=typeof e.body)throw Error("sdk.notifications.send: title and body must be strings");if(void 0!==e.url&&"string"!=typeof e.url)throw Error("sdk.notifications.send: url must be a string");if(void 0!==e.data&&!(0,c.isObjectRecord)(e.data))throw Error("sdk.notifications.send: data must be an object");return{title:e.title,body:e.body,..."string"==typeof e.url?{url:e.url}:{},...(0,c.isObjectRecord)(e.data)?{data:e.data}:{},...void 0!==e.target?{target:function(e){if(void 0!==e){var t;if(!(0,c.isObjectRecord)(e))throw Error("sdk.notifications.send: target must be an object");if("actor"===e.type||"team"===e.type)return{type:e.type};if("member"===e.type&&"string"==typeof e.userId)return{type:"member",userId:e.userId};if("role"===e.type&&"string"==typeof(t=e.role)&&Q.TEAM_ROLES.some(e=>e===t))return{type:"role",role:e.role};throw Error("sdk.notifications.send: target is invalid")}}(e.target)}:{}}}(n.input);return{handled:!0,result:await F({config:o,appId:p,appName:u,input:e,onToast:g})}}case"email.send":{let e;if(!m)throw Error("sdk.email.send: params must be an object");let t=m.subject;if(void 0!==t&&"string"!=typeof t)throw Error("sdk.email.send: subject must be a string");"string"==typeof t&&(e=t);let r=H(n,"text","sdk.email.send"),i=m.html;if(void 0!==i&&"string"!=typeof i)throw Error("sdk.email.send: html must be a string");let a=m.target;if(void 0!==a&&("object"!=typeof a||null===a||Array.isArray(a)))throw Error("sdk.email.send: target must be an object");let s=await O({config:o,input:"/api/apps/sdk/email",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:p,appName:u,subject:e,text:r,html:i,target:a})}}),c=await k(s);if(!s.ok){if(429===s.status||"RATE_LIMITED"===c.code){let e=c.error||"Rate limit reached. Please try again later.";g?.(e)}throw"CREDITS_EXHAUSTED"===c.code&&g?.(c.error||"Credit limit exceeded."),T(c.error||"Email send failed","string"==typeof c.code?c.code:void 0)}return{handled:!0,result:c.result}}case"services.request":{let e,i=H(n,"provider","services.request"),s=H(n,"method","services.request"),c=H(n,"path","services.request"),d=(e=(t={provider:i,method:s}).method.toUpperCase(),"weatherapi"===t.provider&&"GET"===e?"services.weatherapi.get":"serpapi"===t.provider&&"GET"===e?"services.serpapi.get":"websearch"===t.provider&&"POST"===e?"services.websearch.post":null);d&&ed({policyState:a,sdkMethod:d,operationId:r});let l=m?.params,u=m?.body,f=await O({config:o,input:"/api/apps/sdk/services",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:p,provider:i,method:s,path:c,params:l,body:u})}}),g=await k(f);if(!f.ok)throw T(g.error||"Service request failed","string"==typeof g.code?g.code:void 0);return{handled:!0,result:g.result}}case"services.website.inspect":{let e=function(e){if(!(0,c.isObjectRecord)(e)||"string"!=typeof e.url)throw Error("sdk.services.website.inspect requires an input object with a url");let t=e.formats;if(void 0!==t&&(!Array.isArray(t)||!t.every(e=>"string"==typeof e&&X.some(t=>t===e))))throw Error("sdk.services.website.inspect: formats are invalid");let r=e.screenshot;if(void 0!==r&&!(0,c.isObjectRecord)(r))throw Error("sdk.services.website.inspect: screenshot must be an object");let i=r?.mode;if(void 0!==i&&!("string"==typeof i&&Y.some(e=>e===i)))throw Error("sdk.services.website.inspect: screenshot mode is invali
1d");return{url:e.url,...void 0!==t?{formats:t}:{},...void 0!==r?{screenshot:{...void 0!==i?{mode:i}:{}}}:{}}}((0,c.isObjectRecord)(n)?n.input:void 0);ed({policyState:a,sdkMethod:"services.website.inspect",operationId:r});let t=await O({config:o,input:"/api/apps/sdk/services",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:p,provider:"website",operation:"inspect",input:e})}}),i=await k(t);if(!t.ok)throw T(i.error||"Website inspection failed","string"==typeof i.code?i.code:void 0);return{handled:!0,result:i.result}}case"chat.send":{if(!n||"object"!=typeof n)throw Error("chat.send: params must be an object");let e=H(n,"message","chat.send"),t=H(n,"label","chat.send"),r=await O({config:o,input:"/api/apps/sdk/chat",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:e,label:t,appId:p,appName:u})}}),i=await k(r);if(!r.ok){let e="string"==typeof i.code?i.code:void 0;if(429===r.status||"RATE_LIMITED"===e){let e=i.error||"Rate limit reached. Please try again later.";g?.(e)}throw"CREDITS_EXHAUSTED"===e&&g?.(i.error||"Credit limit exceeded."),T(i.error||"Snow request failed",e)}return{handled:!0,result:i.message??i}}default:return{handled:!1}}}function eh(e,t){let r=new Set(t);return Object.keys(e).every(e=>r.has(e))}function em(e){if(!(0,c.isObjectRecord)(e))return{error:"target must be an object"};if("action"===e.type)return eh(e,["type","actionName","actionInput"])?"string"==typeof e.actionName&&e.actionName.trim()?{target:{type:"action",actionName:e.actionName.trim(),...Object.hasOwn(e,"actionInput")?{actionInput:e.actionInput}:{}}}:{error:"Action target requires actionName"}:{error:"Action target contains unsupported fields"};if("snow"===e.type){var t;if(!eh(e,["type","prompt"]))return{error:"Snow target contains unsupported fields"};if("string"!=typeof e.prompt)return{error:"Snow target requires prompt"};let r=(t=e.prompt,new TextEncoder().encode(t).length);return r<1||r>32768?{error:"Snow target prompt must be between 1 and 32768 UTF-8 bytes"}:{target:{type:"snow",prompt:e.prompt}}}return{error:'target.type must be "action" or "snow"'}}let ey=new Set(["provisioning","ready","needs_attention","requires_redeploy","failed","deleting"]);function ew(e){return null===e||"string"==typeof e}function eb(e){return(0,c.isObjectRecord)(e)&&"string"==typeof e.id&&"string"==typeof e.name&&"string"==typeof e.app&&(void 0===e.bindingKey||ew(e.bindingKey))&&ew(e.connection)&&"string"==typeof e.triggerKey&&void 0!==em(e.target).target&&"string"==typeof e.state&&ey.has(e.state)&&"boolean"==typeof e.isActive&&"string"==typeof e.createdAt&&"string"==typeof e.updatedAt&&(void 0===e.lastEventAt||ew(e.lastEventAt))&&"lastError"in e}function ev(e){return(0,c.isObjectRecord)(e)&&"string"==typeof e.app&&"string"==typeof e.triggerKey&&"string"==typeof e.name&&"string"==typeof e.description&&"configSchema"in e}function eI(e){return(0,c.isObjectRecord)(e)?{..."string"==typeof e.error?{error:e.error}:{},..."string"==typeof e.code?{code:e.code}:{},...(0,c.isObjectRecord)(e.details)?{details:e.details}:{}}:{}}function eE(e){if(!((0,c.isObjectRecord)(e)&&(0,c.isObjectRecord)(e.config)&&eb(e)))throw Error("Trigger request returned invalid data");return e}async function eT(e){return eE((await eD({config:e.config,appId:e.appId,method:"POST",body:{name:e.input.name,providerSlug:e.input.app,connectionTarget:"binding"in e.input?{type:"binding",bindingKey:e.input.binding}:{type:"connection",connectionId:e.input.connection},triggerKey:e.input.triggerKey,config:e.input.config,target:e.input.target,...void 0!==e.input.isActive?{isActive:e.input.isActive}:{},appId:e.appId},onToast:e.onToast})).trigger)}async function eR(e){let t=new URLSearchParams;for(let r of(t.set("appId",e.appId),e.apps??[]))t.append("apps",r);let r=await O({config:e.config,input:`/api/apps/sdk/triggers?${t.toString()}`,init:{method:"GET"}}),i=await r.json().catch(()=>null),n=(0,c.isObjectRecord)(i)?i:null,o=eI(i),a=n?.triggers;if(!r.ok||!Array.isArray(a)||!a.every(eb)){let t=o.error||"Failed to load triggers";throw(429===r.status||"RATE_LIMITED"===o.code)&&e.onToast?.(t),T(t,o.code,o.details)}return a}
1async function eO(e){return eE((await eD({config:e.config,appId:e.appId,method:"GET",path:encodeURIComponent(e.id),onToast:e.onToast})).trigger)}async function ek(e){return eE((await eD({config:e.config,appId:e.appId,method:"PATCH",path:encodeURIComponent(e.id),body:e.input,onToast:e.onToast})).trigger)}async function eS(e){if(!0!==(await eD({config:e.config,appId:e.appId,method:"DELETE",path:encodeURIComponent(e.id),onToast:e.onToast})).success)throw Error("Trigger request returned invalid data")}async function eA(e){let t=new URLSearchParams;for(let r of e.apps??[])t.append("apps",r);let r=await eP({config:e.config,appId:e.appId,query:t,onToast:e.onToast});if(!Array.isArray(r.definitions)||!r.definitions.every(ev))throw Error("Trigger request returned invalid data");return r.definitions}async function eN(e){var t=(await eP({config:e.config,appId:e.appId,path:`${encodeURIComponent(e.input.app)}/${encodeURIComponent(e.input.triggerKey)}`,onToast:e.onToast})).definition;if(!ev(t))throw Error("Trigger request returned invalid data");return t}async function eD(e){let t=e.path?`/api/apps/sdk/triggers/${e.path}`:"/api/apps/sdk/triggers",r=`${t}?appId=${encodeURIComponent(e.appId)}`,i=await O({config:e.config,input:r,init:{method:e.method,headers:e.body?{"Content-Type":"application/json"}:void 0,body:e.body?JSON.stringify(e.body):void 0}}),n=await i.json().catch(()=>null),o=(0,c.isObjectRecord)(n)?n:null,a=eI(n);if(!i.ok){let t=a.error||"Trigger request failed";throw(429===i.status||"RATE_LIMITED"===a.code)&&e.onToast?.(t),T(t,a.code,a.details)}if(!o)throw Error("Trigger request returned invalid data");return o}async function eP(e){let t=e.path?`/api/apps/sdk/triggers/definitions/${e.path}`:"/api/apps/sdk/triggers/definitions",r=e.query??new URLSearchParams;r.set("appId",e.appId);let i=await O({config:e.config,input:`${t}?${r.toString()}`,init:{method:e.method??"GET",headers:e.body?{"Content-Type":"application/json"}:void 0,body:e.body?JSON.stringify(e.body):void 0}}),n=await i.json().catch(()=>null),o=(0,c.isObjectRecord)(n)?n:null,a=eI(n);if(!i.ok){let t=a.error||"Trigger request failed";throw(429===i.status||"RATE_LIMITED"===a.code)&&e.onToast?.(t),T(t,a.code,a.details)}if(!o)throw Error("Trigger request returned invalid data");return o}function eC(e){if(!(0,c.isObjectRecord)(e))throw Error("SDK schedule input requires a schedule object");if("cron"===e.type&&"string"==typeof e.cron&&(void 0===e.timezone||"string"==typeof e.timezone))return{type:"cron",cron:e.cron,..."string"==typeof e.timezone?{timezone:e.timezone}:{}};if("once"===e.type&&"string"==typeof e.runAt)return{type:"once",runAt:e.runAt};throw Error("SDK schedule input has an invalid schedule")}function e_(e){if(!(0,c.isObjectRecord)(e)||void 0!==e.retries&&"number"!=typeof e.retries||void 0!==e.retryDelay&&"string"!=typeof e.retryDelay||void 0!==e.timeout&&"number"!=typeof e.timeout)throw Error("SDK schedule input has invalid delivery options");return{..."number"==typeof e.retries?{retries:e.retries}:{},..."string"==typeof e.retryDelay?{retryDelay:e.retryDelay}:{},..."number"==typeof e.timeout?{timeout:e.timeout}:{}}}function ej(e,t,r){let i=Object.keys(t).filter(e=>!r.includes(e));if(i.length>0)throw Error(`${e}: unknown field ${i.sort()[0]}`)}function eM(e,t){if(!(0,c.isObjectRecord)(e)||!(t in e))throw Error("Schedule request returned invalid data");return e[t]}function ex(e,t){if(void 0!==e){if(!(0,c.isObjectRecord)(e))throw Error(`${t}: params must be an object`);if(void 0!==e.apps){if(!Array.isArray(e.apps)||!e.apps.every(e=>"string"==typeof e))throw Error(`${t}: apps must be an array of strings`);return e.apps}}}let eL={INTEGRATION_CONNECTION_RECONNECT_REQUIRED:"reconnect-account",INTEGRATION_NOT_CONNECTED:"connect-account",INTEGRATION_CONNECTION_NOT_FOUND:"connect-account"},eU=new Set(["INTEGRATION_NOT_CONNECTED","INTEGRATION_CONNECTION_NOT_FOUND","INTEGRATION_CONNECTION_RECONNECT_REQUIRED"]),eq=["INTEGRATION_NOT_DECLARED","INTEGRATION_TARGET_UNSPECIFIED","INTEGRATION_NOT_CONNECTED","INTEGRATION_BINDING_REQUIRED","INTEGRATION_CONNECTION_NOT_FOUND","INTEGRATION_CONNECTION_RECONNECT_REQUIRED","INTEGRATION_CONNECT_DISMISSED","INTEGRATION_SELECTION_GRANT_INVALID","INTEGRATION_SELECTION_GRANT_UNAVAILABLE","INTEGRATION_PROXY_FAILED","INTEGRATION_NOT_CONNECTED_NON_INTERACTIVE","INTEGRATION_BINDING_REQUIRED_NON_INTERACTIVE","INTEGRATION_CONNECTION_NOT_FOUND_NON_INTERACTIVE","INTEGRATION_CONNECTION_RECONNECT_REQUIRED_NON_INTERACTIVE"],eF=["not_declared","target_unspecified","not_connected","binding_required","connection_not_found","reconnect_required","proxy_failed"];function eK(e){return null==e||"string"==typeof e}function e$(e){var t;return(0,c.isObjectRecord)(e)&&"string"==typeof(t=e.code)&&eq.some(e=>e===t)?e.code:void 0}function ez(e){return(0,c.isObjectRecord)(e)&&function(e){if(!(0,c.isObjectRecord)(e)||!(0,c.isObjectRecord)(e.provider))return!1;let t=e.provider;return"string"==typeof t.slug&&"string"==typeof t.name&&!!eK(t.iconUrl)&&!!eF.some(t=>t===e.reason)&&!!eK(e.bindingKey)&&!!eK(e.requestedConnectionId)&&(void 0===e.availableConnections||!!Array.isArray(e.availableConnections)&&!!e.availableConnections.every(e=>(0,c.isObjectRecord)(e)&&"string"==typeof e.id&&"string"==typeof e.label))&&(void 0===e.connectionRequirement||!!function(e){if(!(0,c.isObjectRecord)(e))return!1;let{workspace:t,owner:r}=e;if(!(0,c.isObjectRecord)(t)||!(0,c.isObjectRecord)(r))return!1;
1let i="personal"===t.kind||"team"===t.kind&&"string"==typeof t.teamId,n="user"===r.kind||"team"===r.kind&&"string"==typeof r.teamId;return i&&n}(e.connectionRequirement))&&(void 0===e.cta||!!(0,c.isObjectRecord)(e.cta)&&("connect"===e.cta.kind||"reconnect"===e.cta.kind)&&"string"==typeof e.cta.href&&"string"==typeof e.cta.label)&&!0}(e.details)?e.details:void 0}function eG(e){return"binding"in e&&"string"==typeof e.binding}async function eB(e){return await $({config:e.config,appId:e.config.appId,providerSlug:e.input.app,bindingKey:e.input.binding,tool:e.input.tool,connectionId:e.connectionId})}async function eV(e){await G({appId:e.appId,providerSlug:e.providerSlug,bindingKey:e.bindingKey,connectionId:e.connectionId})}async function eH(e){let t;if(!e.config.onIntegrationPrompt||!e.details?.connectionRequirement)return null;try{var r;let i;t=(i=(r=await z({config:e.config,appId:e.config.appId,providerSlug:e.providerSlug,onToast:e.config.onToast})).filter(e=>"connected"===e.status)).length>0?i:r}catch{return null}if(0===t.length)return null;let i=await e.config.onIntegrationPrompt({kind:"select-connection",appId:e.config.appId,appName:e.config.appName,appImage:e.config.appImage,source:e.config.source??"apps-page",operationId:(0,v.generateUUID)(),provider:e.details?.provider??{slug:e.providerSlug,name:e.providerSlug,iconUrl:null},connectionRequirement:e.details.connectionRequirement,bindingKey:e.bindingKey,connections:t,rememberByDefault:!0,...e.rememberRequired?{rememberRequired:!0}:{}});return"selected"!==i.decision?null:{connectionId:i.connectionId,rememberSelection:i.rememberSelection}}async function eW(e){if(!e.config.onIntegrationPrompt)return null;let t=e$(e.error),r=ez(e.error);if(!t||!r?.provider)return null;let i=eL[t];if(!i||!r.cta?.label||!r.connectionRequirement)return null;let n=await e.config.onIntegrationPrompt({kind:i,appId:e.config.appId,appName:e.config.appName,appImage:e.config.appImage,source:e.config.source??"apps-page",operationId:(0,v.generateUUID)(),provider:r.provider,connectionRequirement:r.connectionRequirement,ctaLabel:r.cta.label,requestedConnectionId:r.requestedConnectionId??void 0});if("dismissed"===n.decision){var o;let t,n=((t=Object.assign(Error("reconnect-account"===(o={details:r,promptKind:i}).promptKind?`Reconnect ${o.details.provider.name} before retrying.`:`Connect ${o.details.provider.name} before retrying.`),{code:"INTEGRATION_CONNECT_DISMISSED",details:o.details}
1)).name="IntegrationConnectDismissedError",t);throw e.config.onToast?.(n.message,{level:"warning"}),n}return"connected"!==n.decision?null:{connectionId:n.connectionId,promptKind:i,details:r}}async function eJ(e){var t,r;if(!("binding"in(t=e.input)&&"string"==typeof t.binding))return null;let i=await eH({config:e.config,providerSlug:e.input.app,bindingKey:e.input.binding,details:ez(e.error)});if(!i)return null;if(i.rememberSelection)return await G({config:e.config,appId:e.config.appId,providerSlug:e.input.app,bindingKey:e.input.binding,connectionId:i.connectionId}),await K({config:e.config,appId:e.config.appId,input:e.input,onToast:e.config.onToast});let n=await eB({config:e.config,input:e.input,connectionId:i.connectionId});return await K({config:e.config,appId:e.config.appId,input:{...(r={input:e.input,selectionGrant:n}).input,selectionGrant:r.selectionGrant},onToast:e.config.onToast})}async function eQ(e){if(!eG(e.input))return null;let t=await eH({config:e.config,providerSlug:e.input.app,bindingKey:e.input.binding,details:ez(e.error),rememberRequired:!0});return t?(await eV({appId:e.config.appId,bindingKey:e.input.binding,connectionId:t.connectionId,providerSlug:e.input.app}),await eT({appId:e.config.appId,input:e.input,onToast:e.config.onToast})):null}async function eX(e){let t=await eW({config:e.config,error:e.error});return t?(await G({config:e.config,appId:e.config.appId,providerSlug:e.input.app,bindingKey:e.input.binding,connectionId:t.connectionId}),await K({config:e.config,appId:e.config.appId,input:e.input,onToast:e.config.onToast})):null}async function eY(e){var t;let r=await eW({config:e.config,error:e.error});return r?eG(e.input)?(await eV({appId:e.config.appId,bindingKey:e.input.binding,connectionId:r.connectionId,providerSlug:e.input.app}),await eT({appId:e.config.appId,input:e.input,onToast:e.config.onToast})):await eT({appId:e.config.appId,input:{name:(t={input:e.input,connectionId:r.connectionId}).input.name,app:t.input.app,triggerKey:t.input.triggerKey,config:t.input.config,target:t.input.target,...void 0!==t.input.isActive?{isActive:t.input.isActive}:{},connection:t.connectionId},onToast:e.config.onToast}):null}async function eZ(e){try{return await e.attempt()}catch(r){let t=e$(r);if("INTEGRATION_BINDING_REQUIRED"===t){let t=await e.handleBindingRequired(r);if(t)return t}if(void 0!==t&&eU.has(t)){let t=await e.handleConnectPrompt(r);if(t)return t}throw r}}async function e0(e){return eZ({attempt:()=>K({config:e.config,appId:e.config.appId,input:e.input,onToast:e.config.onToast}),handleBindingRequired:t=>eJ({config:e.config,error:t,input:e.input}),handleConnectPrompt:t=>eX({config:e.config,error:t,input:e.input})})}async function e1(e){return eZ({attempt:()=>eT({appId:e.config.appId,input:e.input,onToast:e.config.onToast}),handleBindingRequired:t=>eQ({config:e.config,error:t,input:e.input}),handleConnectPrompt:t=>eY({config:e.config,error:t,input:e.input})})}function e4(e){return(0,c.isObjectRecord)(e)&&"input"in e?e.input:e}function e2(e){if(!(0,c.isObjectRecord)(e))return;let t=e.scopeKey;if("string"!=typeof t)return;let r=t.trim();return r.length>0?r:void 0}async function e9(e,t){if(!e.onOwnerFilePick)throw Error("sdk.files.pick is unavailable on this surface");let r=(0,c.isObjectRecord)(t)?t:{};if(Object.keys(r).some(e=>!["name","type"].includes(e)))throw Error("sdk.files.pick options contain an unknown field");if(void 0!==r.name&&"string"!=typeof r.name)throw Error("sdk.files.pick name must be a string");if(void 0!==r.type&&"string"!=typeof r.type)throw Error("sdk.files.pick type must be a string");let i="string"==typeof r.name?r.name.trim():"",n="string"==typeof r.type?r.type.trim():null,o=async t=>(function(e){if(!(0,c.isObjectRecord)(e)||!Array.isArray(e.files)||null!==e.nextCursor&&"string"!=typeof e.nextCursor)throw Error("sdk.files.pick received an invalid catalog response");return Object.freeze({files:Object.freeze(e.files.map(e=>{if(!(0,c.isObjectRecord)(e)||"string"!=typeof e.id||"string"!=typeof e.name||"string"!=typeof e.type||"number"!=typeof e.size||"number"!=typeof e.revision||"string"!=typeof e.createdAt||"string"!=typeof e.updatedAt)throw Error("sdk.files.pick received an invali
1d catalog item");return Object.freeze({id:e.id,revision:e.revision,name:e.name,type:e.type,size:e.size,createdAt:e.createdAt,updatedAt:e.updatedAt})})),nextCursor:e.nextCursor})})(await j({config:e,method:"listPickable",input:{...t.search?{name:t.search}:{},...n?{type:n}:{},...t.cursor?{cursor:t.cursor}:{},limit:50}})),a=await e.onOwnerFilePick({initialSearch:i,loadPage:o});if(null===a)return null;let s=await j({config:e,method:"issuePickGrant",input:{fileId:a}});if(!(0,c.isObjectRecord)(s)||"string"!=typeof s.pickGrantId)throw Error("sdk.files.pick received an invalid selection grant");return j({config:e,method:"pick",input:{fileId:a,pickGrantId:s.pickGrantId}})}async function e8(e){let{requestId:t=crypto.randomUUID(),method:r,callParams:i,config:n}=e,{appId:o,onToast:a}=n,s=(0,c.isObjectRecord)(i)?i:null;if(r.startsWith("data.")){let e=r.slice(5),t=s?.alias;if("atomic"!==e&&"string"!=typeof t)throw Error(`sdk.${r}: alias must be a string`);return{handled:!0,result:await _({config:n,appId:o,method:e,..."string"==typeof t?{alias:t}:{},input:s?.input})}}switch(r){case"files.find":return{handled:!0,result:await j({config:n,method:"find",input:(0,c.isObjectRecord)(i)?i:{}})};case"files.pick":return{handled:!0,result:await e9(n,i)};case"files.rename":{let e=H(i,"id","sdk.files.rename"),t=H(i,"name","sdk.files.rename");if("number"!=typeof s?.expectedRevision)throw Error("sdk.files.rename requires expectedRevision");return{handled:!0,result:await j({config:n,method:"rename",input:{fileId:e,name:t,expectedRevision:s.expectedRevision}})}}case"files.replace":{let e=H(i,"id","sdk.files.replace"),r=s?.blob;if(!(r instanceof Blob)||"number"!=typeof s?.expectedRevision)throw Error("sdk.files.replace requires a Blob and expectedRevision");if(Object.keys(s).some(e=>!["id","blob","expectedRevision"].includes(e)))throw Error("sdk.files.replace params contain an unknown field");return{handled:!0,result:await x({config:n,blob:r,options:{},idempotencyKey:`${n.sessionToken}:${t}`,replace:{fileId:e,expectedRevision:s.expectedRevision}})}}case"context.update":case"appContext.update":if(!(0,c.isObjectRecord)(i))throw Error("sdk.appContext.update: params must be an object");return{handled:!0,result:await L(o,i,a,n)};case"context.clear":case"appContext.clear":var d,l;return{handled:!0,result:await L(o,(d=e2(i),l={clear:!0},d?{...l,scopeKey:d}:l),a,n)};case"schedules.create":{let e=function(e){if(!(0,c.isObjectRecord)(e)||"string"!=typeof e.name||void 0!==e.description&&null!==e.description&&"string"!=typeof e.description||void 0!==e.maxRuns&&null!==e.maxRuns&&"number"!=typeof e.maxRuns||void 0!==e.isActive&&"boolean"!=typeof e.isActive)throw Error("sdk.schedules.create: input is invalid");let t=em(e.target);if(!t.target)throw Error(`sdk.schedules.create: ${t.error}`);return{name:e.name,target:t.target,schedule:eC(e.schedule),..."string"==typeof e.description||null===e.description?{description:e.description}:{},..."number"==typeof e.maxRuns||null===e.maxRuns?{maxRuns:e.maxRuns}:{},..."boolean"==typeof e.isActive?{isActive:e.isActive}:{},...void 0!==e.delivery?{delivery:e_(e.delivery)}:{}}}(s?.input);return{handled:!0,result:eM(await U({config:n,appId:o,method:"POST",body:{...e,appId:o},onRateLimited:a}),"schedule")}}case"schedules.update":{let e=H(i,"id","sdk.schedules.update"),t=function(e){if(!(0,c.isObjectRecord)(e)||void 0!==e.name&&"string"!=typeof e.name||void 0!==e.description&&null!==e.description&&"string"!=typeof e.description||void 0!==e.maxRuns&&null!==e.maxRuns&&"number"!=typeof e.maxRuns||void 0!==e.isActive&&"boolean"!=typeof e.isActive)throw Error("sdk.schedules.update: input is invalid");ej("sdk.schedules.update",e,["name","description","target","schedule","maxRuns","isActive","delivery"]);let t=void 0===e.target?null:em(e.target);if(t&&!t.target)throw Error(`sdk.schedules.update: ${t.error}`);return{..."string"==typeof e.name?{name:e.name}:{},..."string"==typeof e.description||null===e.description?{description:e.description}:{},...t?.target?{target:t.target}:{},...void 0!==e.schedule?{schedule:eC(e.schedule)}:{},..."number"==typeof e.maxRuns||null===e.maxRuns?{maxRuns:e.maxRuns}:{},..."boolean"==typeof e.isActive?{isActive:e.isActive}:{},...void 0!==e.delivery?{delivery:null===e.delivery?null:e_(e.delivery)}:{}}}(s?.input);return{handled:!0,result:eM(await U({config:n,appId:o,method:"PATCH",path:e,body:t,onRateLimited:a}
1),"schedule")}}case"schedules.delete":{let e=H(i,"id","sdk.schedules.delete");return await U({config:n,appId:o,method:"DELETE",path:e,onRateLimited:a}),{handled:!0,result:void 0}}case"schedules.get":{let e=H(i,"id","sdk.schedules.get");return{handled:!0,result:eM(await U({config:n,appId:o,method:"GET",path:e,onRateLimited:a}),"schedule")}}case"schedules.list":return{handled:!0,result:eM(await U({config:n,appId:o,method:"GET",onRateLimited:a}),"schedules")};case"actions.call":{if(!s)throw Error("sdk.actions.call: params must be an object");let e=H(i,"actionName","actions.call"),t=s.input;if(void 0!==t&&!(0,c.isObjectRecord)(t))throw Error("sdk.actions.call: input must be an object");return{handled:!0,result:await q({config:n,appId:o,actionName:e,input:t,onToast:a})}}case"files.upload":{let e=e2(i),r=s?.blob,o=s?.options;if(!(r instanceof Blob))throw Error("sdk.files.upload requires a Blob");if(void 0!==o&&!(0,c.isObjectRecord)(o))throw Error("sdk.files.upload: options must be an object");if(null!==s&&Object.keys(s).some(e=>!["blob","options","scopeKey"].includes(e)))throw Error("sdk.files.upload: params contain an unknown field");if(!((0,c.isObjectRecord)(o)&&void 0!==o.access)&&!await M(n))throw Error("sdk.files.upload is not declared by this app");if(void 0!==e)throw Error("sdk.files.scope is unavailable for owner files");return{handled:!0,result:await x({config:n,blob:r,options:(0,c.isObjectRecord)(o)?o:{},idempotencyKey:`${n.sessionToken}:${t}`})}}case"files.get":{let e=e2(i),t=H(i,"id","sdk.files.get");if(await M(n)){if(void 0!==e)throw Error("sdk.files.scope is unavailable for owner files");return{handled:!0,result:await j({config:n,method:"get",input:{fileId:t}})}}throw Error("sdk.files.get is not declared by this app")}case"files.delete":{let e=e2(i),t=H(i,"id","sdk.files.delete");if(s?.expectedRevision!==void 0||await M(n)){if(void 0!==e)throw Error("sdk.files.scope is unavailable for owner files");if("number"!=typeof s?.expectedRevision)throw Error("sdk.files.delete requires expectedRevision");return{handled:!0,result:await j({config:n,method:"delete",input:{fileId:t,expectedRevision:s.expectedRevision}})}}throw Error("sdk.files.delete is not declared by this app")}case"integrations.execute":{let e=e4(i);if(!(0,c.isObjectRecord)(e))throw Error("sdk.integrations.execute: params must be an object");let t=H(e,"app","sdk.integrations.execute"),r=H(e,"tool","sdk.integrations.execute"),o=H(e,"binding","sdk.integrations.execute"),a=e.arguments;if(void 0!==a&&!(0,c.isObjectRecord)(a))throw Error("sdk.integrations.execute: arguments must be an object");let s={app:t,tool:r,binding:o,...void 0!==a?{arguments:a}:{}};return{handled:!0,result:await e0({config:n,input:s})}}case"integrations.listConnections":{let e=H(e4(i),"app","sdk.integrations.listConnections");return{handled:!0,result:await z({config:n,appId:o,providerSlug:e,onToast:a})}}case"triggers.create":{let e=function(e){if(!(0,c.isObjectRecord)(e))throw Error("sdk.triggers.create: params must be an object");if("string"!=typeof e.name||"string"!=typeof e.app||"string"!=typeof e.triggerKey||!(0,c.isObjectRecord)(e.config)||void 0!==e.isActive&&"boolean"!=typeof e.isActive)throw Error("sdk.triggers.create: input is invalid");let t=em(e.target);if(!t.target)throw Error(`sdk.triggers.create: ${t.error}`);let r={name:e.name,app:e.app,triggerKey:e.triggerKey,config:e.config,target:t.target,..."boolean"==typeof e.isActive?{isActive:e.isActive}:{}};if("string"==typeof e.binding&&void 0===e.connection)return{...r,binding:e.binding};if("string"==typeof e.connection&&void 0===e.binding)return{...r,connection:e.connection};throw Error("sdk.triggers.create: input requires one binding or connection")}(e4(i));return{handled:!0,result:await e1({config:n,input:e})}}case"triggers.list":{let e=e4(i);return{handled:!0,result:await eR({config:n,appId:o,apps:ex(e,"sdk.triggers.list"),onToast:a})}}case"triggers.get":{let e=H(i,"id","sdk.triggers.get");return{handled:!0,result:await eO({config:n,appId:o,id:e,onToast:a})}}case"triggers.listDefinitions":{let e=e4(i);return{handled:!0,result:await eA({config:n,appId:o,apps:ex(e,"sdk.triggers.listDefinitions"),onToast:a})}}case"triggers.getDefinition":{let e=e4(i);return{handled:!0,result:await eN({config:n,appId:o,input:function(e){if(!(0,c.isObjectRecord)(e)||"string"!=typeof e.app||"string"!=typeof e.triggerKey)throw Error("sdk.triggers.getDefinition: params are invalid");return{app:e.app,triggerKey:e.triggerKey}}(e),onToast:a})}}case"triggers.update":{let e=H(i,"id","sdk.triggers.update"),t=function(e){if(!(0,c.isObjectRecord)(e)||void 0!==e.name&&"string"!=typeof e.name||void 0!==e.binding&&"string"!=typeof e.binding||void 0!==e.connection&&"string"!=typeof e.connection||void 0!==e.config&&!(0,c.isObjectRecord)(e.config)||void 0!==e.isActive&&"boolean"!=typeof e.isActive)throw Error("sdk.triggers.update: input is invali
1d");if(void 0!==e.binding&&void 0!==e.connection)throw Error("sdk.triggers.update: use either binding or connection, not both");ej("sdk.triggers.update",e,["name","binding","connection","config","target","isActive"]);let t=void 0===e.target?null:em(e.target);if(t&&!t.target)throw Error(`sdk.triggers.update: ${t.error}`);return{..."string"==typeof e.name?{name:e.name}:{},..."string"==typeof e.binding?{binding:e.binding}:{},..."string"==typeof e.connection?{connection:e.connection}:{},...(0,c.isObjectRecord)(e.config)?{config:e.config}:{},...t?.target?{target:t.target}:{},..."boolean"==typeof e.isActive?{isActive:e.isActive}:{}}}(s?.input);return{handled:!0,result:await ek({config:n,appId:o,id:e,input:t,onToast:a})}}case"triggers.delete":{let e=H(i,"id","sdk.triggers.delete");return await eS({config:n,appId:o,id:e,onToast:a}),{handled:!0,result:void 0}}default:return{handled:!1}}}var e3=e.i(352255),e6=e.i(254581);let e5=new Set,e7=null,te=!1,tt=!1;function tr(){return"u">typeof navigator&&"wakeLock"in navigator&&"function"==typeof navigator.wakeLock?.request}async function ti(){if(!e7&&!te&&0!==e5.size&&tr()&&("u"<typeof document||"visible"===document.visibilityState)){te=!0;try{let e=await navigator.wakeLock.request("screen");if(0===e5.size)return void e.release().catch(()=>{});(e7=e).addEventListener("release",()=>{e7=null})}catch{e7=null}finally{te=!1}}}async function tn(){if(!e7)return;let e=e7;e7=null;try{await e.release()}catch{}}async function to(e){return!!tr()&&(!tt&&"u">typeof document&&(tt=!0,document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&e5.size>0&&ti()})),e5.add(e),await ti(),!0)}async function ta(e){e5.delete(e)&&0===e5.size&&await tn()}async function ts(e){let{id:t,method:r,params:i,config:n,policyState:o}=e,{appId:a,onToast:s}=n,d=(0,c.isObjectRecord)(i)?i:null;if((0,ef.isSharedBrowserSdkMethod)(r)&&"openExternal"!==r)return ed({policyState:o,sdkMethod:r,operationId:t}),{handled:!0,result:await (0,ef.executeSharedBrowserCapability)({method:r,params:i})};switch(r){case"device.push.requestPermission":{if(ed({policyState:o,sdkMethod:r,operationId:t}),!(0,e3.isPushSupported)()||"function"!=typeof Notification.requestPermission)throw Error("Notifications are not supported in this browser");let e=await Notification.requestPermission();if("granted"===e){let e=await (0,e3.getExistingSubscription)({appId:a})!==null,t=await (0,e3.subscribeToPush)({appId:a});if(!(await I("/api/notifications/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,appId:a})})).ok)throw e||await (0,e3.unsubscribeFromPush)({appId:a}).catch(()=>{}),Error("Failed to save notification subscription")}return{handled:!0,result:e}}case"device.push.getStatus":return ed({policyState:o,sdkMethod:r,operationId:t}),{handled:!0,result:await (0,e6.getPushStatus)(a)};case"device.location.get":ed({policyState:o,sdkMethod:r,operationId:t});try{let e=await navigator.permissions.query({name:"geolocation"});if("denied"===e.state)throw s?.("Location access denied. Enable in browser settings to use this feature."),Error("PERMISSION_DENIED");let t=await new Promise((e,t)=>{navigator.geolocation.getCurrentPosition(e,t,{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})});return{handled:!0,result:{latitude:t.coords.latitude,longitude:t.coords.longitude,accuracy:t.coords.accuracy}}}catch(e){if(e instanceof GeolocationPositionError)switch(e.code){case e.PERMISSION_DENIED:throw s?.("Location access denied. Enable in browser settings to use this feature."),Error("PERMISSION_DENIED");case e.POSITION_UNAVAILABLE:throw Error("POSITION_UNAVAILABLE");case e.TIMEOUT:throw Error("TIMEOUT")}if(e instanceof Error&&["PERMISSION_DENIED","POSITION_UNAVAILABLE","TIMEOUT"].includes(e.message))throw e;throw Error("POSITION_UNAVAILABLE")}case"device.location.getPermissionState":ed({policyState:o,sdkMethod:r,operationId:t});try{let e=await navigator.permissions.query({name:"geolocation"});return{handled:!0,result:e.state}}catch{return{handled:!0,result:"prompt"}}case"device.screen.keepAwake":if(ed({policyState:o,sdkMethod:r,operationId:t}
1),d?.on===!0)return{handled:!0,result:{supported:await to(n.sessionToken)}};return await ta(n.sessionToken),{handled:!0,result:{supported:tr()}};default:return{handled:!1}}}let tc=["user","environment"],td="sdk-media-frame-ack";function tl(e){return Error(`sdk.device: ${e}`)}function tp(e){if(null==e)return{};if(!(0,c.isObjectRecord)(e))throw tl("params must be an object");return e}function tu(e){let t=tp(e);if("string"!=typeof t.sessionId||0===t.sessionId.length)throw tl("sessionId must be a non-empty string");return{sessionId:t.sessionId}}class tf extends Error{code;constructor(e,t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="MediaCaptureError",this.code=e}}function tg(e,t){if(e instanceof tf)return e;let r=e instanceof DOMException?e.name:"";return"NotAllowedError"===r||"SecurityError"===r?new tf("PERMISSION_DENIED",`${"camera"===t?"Camera":"Microphone"} access denied`):"NotFoundError"===r||"OverconstrainedError"===r?new tf("DEVICE_NOT_FOUND",`No ${t} available on this device`):new tf("DEVICE_UNAVAILABLE",`The ${t} could not be started`)}function th(){if("u"<typeof navigator||!navigator.mediaDevices||"function"!=typeof navigator.mediaDevices.getUserMedia)throw new tf("MEDIA_UNSUPPORTED","Media capture is not supported in this browser");return navigator.mediaDevices}async function tm(e,t){let r=th(),i={width:{ideal:3840},height:{ideal:2160}};t?i.deviceId={exact:t}:i.facingMode=e;try{return await r.getUserMedia({video:i,audio:!1})}catch(e){throw tg(e,"camera")}}async function ty(e){if("u">typeof navigator&&navigator.mediaDevices&&"function"==typeof navigator.mediaDevices.enumerateDevices)try{let t=(await navigator.mediaDevices.enumerateDevices()).filter(e=>"videoinput"===e.kind&&e.deviceId);if(t.length<2)return;let r=(t.findIndex(t=>t.deviceId===e)+1)%t.length;return t[r]?.deviceId}catch{return}}async function tw(){if("u"<typeof navigator||!navigator.mediaDevices||"function"!=typeof navigator.mediaDevices.enumerateDevices)return!1;try{return(await navigator.mediaDevices.enumerateDevices()).filter(e=>"videoinput"===e.kind).length>1}catch{return!1}}async function tb(){let e=th();try{return await e.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1})}catch(e){throw tg(e,"microphone")}}async function tv(e,t){let r=document.createElement("video");
1r.srcObject=e,r.muted=!0,r.playsInline=!0,r.style.cssText="position:fixed;width:1px;height:1px;visibility:hidden;pointer-events:none;",t.appendChild(r);try{await r.play(),r.readyState<HTMLMediaElement.HAVE_CURRENT_DATA&&await new Promise(e=>{r.addEventListener("loadeddata",()=>e(),{once:!0})})}catch(e){throw r.remove(),tg(e,"camera")}return r}function tI(e){let t=Math.max(1,e.videoWidth),r=Math.max(1,e.videoHeight),i=Math.max(t,r);if(i<=b.SDK_MEDIA_LIMITS.PREVIEW_MAX_DIMENSION)return{width:t,height:r};let n=b.SDK_MEDIA_LIMITS.PREVIEW_MAX_DIMENSION/i;return{width:Math.max(1,Math.round(t*n)),height:Math.max(1,Math.round(r*n))}}let tE=null;async function tT(e){let{width:t,height:r}=tI(e);if(!1!==tE)try{let i=await createImageBitmap(e,{resizeWidth:t,resizeHeight:r,resizeQuality:"medium"});return tE=!0,i}catch{tE=!1}return createImageBitmap(e)}async function tR(e){let t=Math.max(1,e.videoWidth),r=Math.max(1,e.videoHeight),i=Math.max(t,r),n=i>b.SDK_MEDIA_LIMITS.PHOTO_MAX_DIMENSION?b.SDK_MEDIA_LIMITS.PHOTO_MAX_DIMENSION/i:1,o=Math.max(1,Math.round(t*n)),a=Math.max(1,Math.round(r*n)),s=document.createElement("canvas");s.width=o,s.height=a;let c=s.getContext("2d");if(!c)throw new tf("MEDIA_UNSUPPORTED","Could not initialize photo capture canvas");c.drawImage(e,0,0,o,a);let d=await new Promise(e=>{s.toBlob(e,"image/jpeg",b.SDK_MEDIA_LIMITS.PHOTO_JPEG_QUALITY)});if(!d)throw new tf("MEDIA_UNSUPPORTED","Photo capture produced no image data");return{blob:d,width:o,height:a,mimeType:"image/jpeg"}}let tO=["video/mp4","video/webm;codecs=vp9","video/webm"],tk=["audio/mp4","audio/webm;codecs=opus","audio/webm"];function tS(e,t){if("u"<typeof MediaRecorder)throw new tf("MEDIA_UNSUPPORTED","Recording is not supported in this browser");let r=function(e){if("u"<typeof MediaRecorder||"function"!=typeof MediaRecorder.isTypeSupported)return null;for(let t of e)if(MediaRecorder.isTypeSupported(t))return t;return null}("video"===t?tO:tk),i=r?new MediaRecorder(e,{mimeType:r}):new MediaRecorder(e),n=[],o=Date.now(),a=!1;i.addEventListener("dataavailable",e=>{!a&&e.data.size>0&&n.push(e.data)});let s=new Promise((e,s)=>{i.addEventListener("stop",()=>{if(a)return void s(new tf("DEVICE_UNAVAILABLE","Recording cancelled"));let c=i.mimeType||r||("video"===t?"video/webm":"audio/webm");e({blob:new Blob(n,{type:c}),mimeType:c,durationMs:Date.now()-o})}),i.addEventListener("error",()=>{s(new tf("DEVICE_UNAVAILABLE","Recording failed"))})});return i.start(1e3),{stop:()=>("inactive"!==i.state&&i.stop(),s),cancel:()=>{a=!0,n.length=0,"inactive"!==i.state&&i.stop(),s.catch(()=>void 0)}}}function tA(e){e&&e.getTracks().forEach(e=>e.stop())}var tN=e.i(14467);class tD extends Error{code;constructor(e,t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="MediaSessionError",this.code=e}}let tP=new Map,tC=!1,t_=null;function tj(){tC||(tC=!0,window.addEventListener("pagehide",()=>{for(let e of Array.from(tP.values()))tU(e,null)}))}function tM(e,t,r){let i=e.iframe.contentWindow;if(!i)return;let n={type:"sdk-media-event",sessionId:e.sessionId,...t};r&&r.length>0?i.postMessage(n,e.targetOrigin,r):i.postMessage(n,e.targetOrigin)}function tx(e,t){let r=()=>{let e=tP.get(t);e&&tU(e,"iframe-navigated")};return e.addEventListener("load",r),()=>{e.removeEventListener("load",r)}}function tL(e){e.recordingTimer&&(clearTimeout(e.recordingTimer),e.recordingTimer=null),e.recorder=null,"camera"===e.kind&&e.micStream&&(tA(e.micStream),e.micStream=null)}function tU(e,t){!e.stopped&&(e.stopped=!0,e.recorder&&e.recorder.cancel(),tL(e),e.pendingRecording=null,e.detachIframeLoad(),"camera"===e.kind?(null!==e.rafHandle&&(cancelAnimationFrame(e.rafHandle),e.rafHandle=null),e.video.pause(),e.video.srcObject=null,e.video.remove()):e.levelMeter.stop(),tA(e.stream),tP.delete(e.sessionId),t&&tM(e,{event:"state",state:"session-stopped",reason:t}))}function tq(e,t){let r=tP.get(t);if(!r||r.ownerToken!==e||r.stopped)throw new tD("SESSION_NOT_FOUND","Media session not found or no longer active");return r}function tF(e,t){let r=tq(e,t);if("camera"!==r.kind)throw new tD("SESSION_NOT_FOUND","Media session not found or no longer active");return r}function tK(e,t){let r=tq(e,t);if("audio"!==r.kind)throw new tD("SESSION_NOT_FOUND","Media session not found or no longer active");return r}function t$(e,t){for(let r of tP.values())if(r.ownerToken===e&&r.kind===t)return r;return null}function tz(e){if(e.stopped)return;let t=()=>{tG(e)},r=e.video;"function"==typeof r.requestVideoFrameCallback?r.requestVideoFrameCallback(t):e.rafHandle=requestAnimationFrame(t)}async function tG(e){if(e.stopped)return;if(!e.iframe.contentWindow)return void tU(e,null);let t=Date.now();if(null!==e.awaitingAckFrameId)return t-e.lastFrameSentAt>b.SDK_MEDIA_LIMITS.FRAME_ACK_TIMEOUT_MS?void tU(e,"unresponsive"):void tz(e);let r=1e3/b.SDK_MEDIA_LIMITS.PREVIEW_MAX_FPS;if(t-e.lastFrameSentAt<r)return void tz(e);try{let t=await tT(e.video);if(e.stopped)return void t.close();if(!e.iframe.contentWindow){t.close(),tU(e,null);return}let r=e.nextFrameId++;e.awaitingAckFrameId=r,e.lastFrameSentAt=Date.now(),tM(e,{event:"frame",frameId:r,frame:t},[t])}catch(t){(0,tN.captureException)(t instanceof Error?t:Error(String(t)),{tags:{component:"apps-media-host",operation:"preview-frame"}}),tU(e,"preview-failed");return}tz(e)}function tB(e){e.recordingTimer=setTimeout(()=>{tV(e)},b.SDK_MEDIA_LIMITS.MAX_RECORDING_MS)}async function tV(e){let t=e.recorder;if(t&&!e.stopped){e.recorder=null;try{let r=await t.stop();if(e.stopped)return;e.pendingRecording=r}catch{e.pendingRecording=null}tL(e),"audio"===e.kind&&(e.levelMeter.stop(),tA(e.stream)),tM(e,{event:"state",state:"recording-stopped",reason:"max-duration"})}}async function tH(e,t){let r,i,n;tj();let o=t$(e.ownerToken,"camera");
1o?.kind!=="camera"||o.facingReported||o.requestedFacing===t||(r=await ty(o.deviceId)),o&&tU(o,"replaced");let a=await tm(t,r),s=await tv(a,function(){if(t_&&t_.isConnected)return t_;let e=document.createElement("div");return e.setAttribute("aria-hidden","true"),e.style.cssText="position:fixed;width:0;height:0;overflow:hidden;",document.body.appendChild(e),t_=e,e}()).catch(e=>{throw tA(a),e}),c=(i=a.getVideoTracks()[0]?.getSettings(),n=i?.facingMode==="user"||i?.facingMode==="environment",{facing:i?.facingMode==="environment"?"environment":"user",facingReported:n,deviceId:i?.deviceId||void 0}),d=(0,v.generateUUID)(),l={...e,kind:"camera",sessionId:d,requestedFacing:t,facingReported:c.facingReported,deviceId:c.deviceId,stream:a,video:s,micStream:null,stopped:!1,recorder:null,recordingTimer:null,pendingRecording:null,nextFrameId:1,awaitingAckFrameId:null,lastFrameSentAt:0,rafHandle:null,detachIframeLoad:tx(e.iframe,d)};tP.set(d,l),tz(l);let{width:p,height:u}=tI(s),f=await tw();return{sessionId:d,width:p,height:u,facing:c.facing,hasMultipleCameras:f}}async function tW(e,t){return tR(tF(e,t).video)}async function tJ(e,t,r){let i=tF(e,t);if(i.recorder)throw new tD("RECORDING_IN_PROGRESS","A recording is already in progress for this camera session");i.pendingRecording=null;let n=i.stream;if(r){let e=await tb();if(i.stopped)throw tA(e),new tD("SESSION_NOT_FOUND","Media session not found or no longer active");i.micStream=e,n=new MediaStream([...i.stream.getVideoTracks(),...e.getAudioTracks()])}try{i.recorder=tS(n,"video")}catch(e){throw tL(i),e}tB(i)}async function tQ(e,t){let r=tF(e,t);if(r.recorder){let e=r.recorder;r.recorder=null,r.recordingTimer&&(clearTimeout(r.recordingTimer),r.recordingTimer=null);try{return await e.stop()}finally{tL(r)}}if(r.pendingRecording){let e=r.pendingRecording;return r.pendingRecording=null,e}throw new tD("NO_ACTIVE_RECORDING","No recording is in progress for this camera session")}async function tX(e){let t;if(tj(),t$(e.ownerToken,"audio"))throw new tD("AUDIO_SESSION_ACTIVE","An audio recording is already active; stop or cancel it first");let r=await tb(),i=(0,v.generateUUID)();try{let n=tS(r,"audio");t={...e,kind:"audio",sessionId:i,stream:r,stopped:!1,recorder:n,recordingTimer:null,pendingRecording:null,levelMeter:function(e,t){if("u"<typeof AudioContext)return{stop:()=>void 0};let r=new AudioContext,i=r.createMediaStreamSource(e),n=r.createAnalyser();n.fftSize=256,i.connect(n);let o=new Uint8Array(n.fftSize),a=setInterval(()=>{n.getByteTimeDomainData(o);let e=0;for(let t of o){let r=(t-128)/128;e+=r*r}t(Math.min(1,Math.sqrt(e/o.length)))},b.SDK_MEDIA_LIMITS.LEVEL_EVENT_INTERVAL_MS);return{stop:()=>{clearInterval(a),i.disconnect(),"closed"!==r.state&&r.close().catch(()=>void 0)}}}(r,e=>{let t=tP.get(i);t&&!t.stopped&&tM(t,{event:"level",level:e})}),detachIframeLoad:tx(e.iframe,i)}}catch(e){throw tA(r),e}return tP.set(i,t),tB(t),{sessionId:i}}async function tY(e,t){let r=tK(e,t);if(r.recorder){let e=r.recorder;r.recorder=null;try{return await e.stop()}finally{tU(r,null)}}if(r.pendingRecording){let e=r.pendingRecording;return r.pendingRecording=null,tU(r,null),e}throw tU(r,null),new tD("NO_ACTIVE_RECORDING","No recording is in progress for this audio session")}async function tZ(e){try{let t=await navigator.permissions.query({name:e});if("granted"===t.state||"denied"===t.state||"prompt"===t.state)return t.state;return"prompt"}catch{return"prompt"}}let t0={camera:"Camera access denied. Enable it in browser settings to use this feature.",microphone:"Microphone access denied. Enable it in browser settings to use this feature."};async function t1(e,t,r){try{return await r()}catch(r){throw r instanceof tf&&"PERMISSION_DENIED"===r.code&&e.onToast?.(t0[t]),r}}async function t4(e){let{id:t,method:r,params:i,config:n,policyState:o,iframe:a,targetOrigin:s}=e;if(!r.startsWith("device.camera.")&&!r.startsWith("device.microphone."))return{handled:!1};let c={ownerToken:n.sessionToken,iframe:a,targetOrigin:s};switch(r){case"device.camera.start":{ed({policyState:o,sdkMethod:"device.camera.start",operationId:t});let{facing:e}=function(e){let t=tp(e),r="user";if(void 0!==t.facing){if(!tc.includes(t.facing))throw tl(`facing must be one of: ${tc.join(", ")}`);r=t.facing}return{facing:r}}(i);return{handled:!0,result:await t1(n,"camera",()=>tH(c,e))}}case"device.camera.capturePhoto":{ed({policyState:o,sdkMethod:"device.camera.capturePhoto",operationId:t});let{sessionId:e}=tu(i);return{handled:!0,result:await tW(n.sessionToken,e)}}case"device.camera.startRecording":{ed({policyState:o,sdkMethod:"device.camera.startRecording",operationId:t});let{sessionId:e,audio:r}=function(e){let{sessionId:t}=tu(e),r=tp(e),i=!1;if(void 0!==r.audio){if("boolean"!=typeof r.audio)throw tl("audio must be a boolean");i=r.audio}return{sessionId:t,audio:i}}(i);return r&&ed({policyState:o,sdkMethod:"device.microphone.start",operationId:t}),await t1(n,"microphone",()=>tJ(n.sessionToken,e,r)),{handled:!0,result:void 0}}case"device.camera.stopRecording":{ed({policyState:o,sdkMethod:"device.camera.stopRecording",operationId:t});let{sessionId:e}=tu(i);return{handled:!0,result:await tQ(n.sessionToken,e)}}case"device.camera.stop":{ed({policyState:o,sdkMethod:"device.camera.stop",operationId:t});let{sessionId:e}=tu(i);return tU(tF(n.sessionToken,e),null),{handled:!0,result:void 0}}case"device.camera.getPermissionState":return ed({policyState:o,sdkMethod:"device.camera.getPermissionState",operationId:t}),{handled:!0,result:await tZ("camera")};case"device.microphone.start":return ed({policyState:o,sdkMethod:"device.microphone.start",operationId:t}),{handled:!0,result:await t1(n,"microphone",()=>tX(c))};case"device.microphone.stop":{ed({policyState:o,sdkMethod:"device.microphone.stop",o
1perationId:t});let{sessionId:e}=tu(i);return{handled:!0,result:await tY(n.sessionToken,e)}}case"device.microphone.cancel":{ed({policyState:o,sdkMethod:"device.microphone.cancel",operationId:t});let{sessionId:e}=tu(i);return tU(tK(n.sessionToken,e),null),{handled:!0,result:void 0}}case"device.microphone.getPermissionState":return ed({policyState:o,sdkMethod:"device.microphone.getPermissionState",operationId:t}),{handled:!0,result:await tZ("microphone")};default:return{handled:!1}}}async function t2({call:e,config:t,policyState:r,permissionState:i,iframe:n,targetOrigin:a}){let{id:s,method:d,params:l}=e,{appId:p}=t;try{if("sdk.ready"===d)return{type:"sdk-response",id:s,result:void 0};let e={id:s,method:d,params:l,config:t,policyState:r,permissionState:i,iframe:n,targetOrigin:a},o=await e8({requestId:s,method:d,callParams:l,config:t});if(o.handled)return{type:"sdk-response",id:s,result:o.result};let c=await eg(e);if(c.handled)return{type:"sdk-response",id:s,result:c.result};let p=await ts(e);if(p.handled)return{type:"sdk-response",id:s,result:p.result};let u=await t4(e);if(u.handled)return{type:"sdk-response",id:s,result:u.result};let f=await J(e);if(f.handled)return{type:"sdk-response",id:s,result:f.result};throw Error(`Unknown SDK method: ${d}`)}catch(n){let e=n instanceof Error?n.message:"Unknown error",t=(0,c.isObjectRecord)(n)&&"string"==typeof n.code?n.code:void 0,r=function(e){if((0,c.isObjectRecord)(e))return(0,c.isObjectRecord)(e.details)?e.details:void 0}(n),i=(0,c.isObjectRecord)(n)&&"boolean"==typeof n.retryable?n.retryable:void 0;if(d.startsWith("http.")){let t=(0,c.isObjectRecord)(l)?l.url:void 0,r="string"==typeof t?`${e} (${(0,W.getDomainFromUrl)(t)})`:e;(0,o.addAppLog)(p,"error",[r],Date.now())}return{type:"sdk-response",id:s,error:t?{message:e,code:t,...r?{details:r}:{},...void 0===i?{}:{retryable:i}}:e}}}let t9=null,t8=new Set,t3=!1;function t6(e){if(!e)return;let t=e.contentWindow;t&&"function"==typeof t.postMessage&&t.postMessage({type:"dismiss-iframe-overlays"},"*")}function t5(){t6(t9)}let t7="app-capture-shortcut",re="snow:app-iframe-capture-shortcut";function rt(e){window.dispatchEvent(new CustomEvent(re,{detail:{appId:e}}))}e.s(["APP_IFRAME_CAPTURE_SHORTCUT_EVENT",0,re,"APP_IFRAME_CAPTURE_SHORTCUT_MESSAGE_TYPE",0,t7,"dispatchAppIframeCaptureShortcut",0,rt,"getAppIframeCaptureShortcutDetail",0,function(e){var t;return e instanceof CustomEvent?"object"==typeof(t=e.detail)&&null!==t&&"appId"in t&&"string"==typeof t.appId?e.detail:null:null}],845029);var rr=e.i(669187);let ri="sdk-data-subscribe",rn="sdk-data-unsubscribe",ro="sdk-data-subscription";function ra(e,t=[],r){for(let i of((0,tN.captureException)(Error("SDK data Realtime transport failed"),{tags:{component:"sdk-data-realtime",operation:e},...void 0===r?{}:{extra:{topic:r}}}),new Set(t)))try{i(e)}catch{}}class rs{config;loadClient;tokenProviders=new Map;failureCallbacks=new Map;topics=new Map;clientPromise=null;rebuildPromise=null;stopped=!1;constructor(e){this.config=e.config,this.loadClient=e.loadClient}matches(e){return this.config.endpoint===e.endpoint&&this.config.publishableKey===e.publishableKey}addOwner(e,t,r){this.tokenProviders.set(e,t),r&&this.failureCallbacks.set(e,r)}removeOwner(e){this.tokenProviders.delete(e),this.failureCallbacks.delete(e)}hasOwners(){return this.tokenProviders.size>0}async acquireChannel(e,t){if(this.stopped)return null;let r=this.topics.get(e);if(!r){if(this.topics.size>=80)return null;r={topic:e,listeners:new Set,channel:null,startPromise:Promise.resolve(!1),joined:!1,hasSubscribed:!1,disruptionReported:!1,rejoinAttempts:0,rejoinTimer:null},this.topics.set(e,r),r.startPromise=this.startTopic(r,!1)}if(r.listeners.add(t),!await r.startPromise)return r.listeners.delete(t),0===r.listeners.size&&this.topics.get(e)===r&&this.topics.delete(e),null;let i=!1;return Object.freeze({joined:r.joined,release:()=>{i||(i=!0,this.releaseListener(r,t))}})}stop(e=[]){if(this.stopped)return;this.stopped=!0;let t=[...this.topics.values()].some(e=>null!==e.channel);for(let e of this.topics.values())this.clearRejoinTimer(e);this.topics.clear(),this.tokenProviders.clear();let r=new Set([...this.failureCallbacks.values(),...e]);this.failureCallbacks.clear();let i=t?this.clientPromise:null;i&&i.then(async e=>{if(e)try{await e.removeAllChannels()}catch{ra("document-cleanup",r)}})}async getAccessToken(){let e;for(let t of this.tokenProviders.values())try{let e=await t({skipCache:!1});if(e&&function(e){try{let t=e.split(".")[1];if(!t)return 0;let r=JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")));if(!(0,c.isObjectRecord)(r)||"number"!=typeof r.exp)return 0;return Math.max(0,1e3*r.exp-Date.now())}catch{return 0}}(e)>=35e3)return e;let r=await t({skipCache:!0});if(r)return r}catch(t){e??=t}if(void 0!==e)throw e;return null}ensureClient(){return this.clientPromise??=this.loadClient().then(async e=>{if(this.stopped)return null;if(!e)return this.captureFailure("initialize"),null;let t=new e(this.config.endpoint,{accessToken:()=>this.getAccessToken(),params:{apikey:this.config.publishableKey},worker:!0});return(await t.setAuth(),this.stopped)?null:t}).catch(()=>(this.captureFailure("initialize"),null)),this.clientPromise}async startTopic(e,t){let r=await this.ensureClient();if(!r||this.stopped||this.topics.get(e.topic)!==e)return!1;if(t){try{await r.setAuth()}catch{}if(this.stopped||this.topics.get(e.topic)!==e)return!1}let i=null;try{let t=r.channel(e.topic,{config:{private:!0}}).on("broadcast",{event:"changed"},t=>{let r=function(e){if(!(0,c.isObjectRecord)(e)||Object.keys(e).some(e=>!["type","event","payload","meta"].includes(e))||"broadcast"!==e.type||"changed"!==e.event||!(0,c.isObjectRecord)(e.meta)||Object.keys(e.meta).some(e=>!["id","replayed"].includes(e))||"string"!=typeof e.meta.id||!(0,v.isValidUUID)(e.meta.id)||void 0!==e.meta.replayed&&"boolean"!=typeof e.meta.replayed||!(0,c.isObjectRecord)(e.payload)||e.payload.id!==e.meta.id)return null;var t=e.payload;let r=function(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return null}}(t);if(null===r||r>8192||!(0,c.isObjectRecord)(t)||Object.keys(t).some(e=>!["storeIds","routingChanged","id"].includes(e))||!Array.isArray(t.storeIds)||0===t.storeIds.length||t.storeIds.length>100||"string"!=typeof t.id||!(0,v.isValidUUID)(t.id)||void 0!==t.routingChanged&&!0!==t.routingChanged)return null;let i=new Set;for(let e of t.storeIds){if("string"!=typeof e||!(0,v.isValidUUID)(e))return null;i.add(e)}return i.size!==t.storeIds.length?null:Object.freeze({storeIds:i,routingChanged:!0===t.routingChanged})}(t);if(!r)return void this.captureFailure("malformed-invalidation");for(let t of[...e.listeners])t.onInvalidation(r)});return i=t,e.channel=t,t.subscribe(r=>{if(this.topics.get(e.topic)===e&&e.channel===t){if("SUBSCRIBED"===r){let t=e.hasSubscribed;for(let r of(e.joined=!0,e.hasSubscribed=!0,e.disruptionReported=!1,e.rejoinAttempts=0,[...e.listeners]))r.onSubscribed(t);return}if(e.joined=!1,"TIMED_OUT"===r||"CHANNEL_ERROR"===r)return void this.reportDisruption(e,"channel-error");"CLOSED"===r&&(this.reportDisruption(e,"channel-closed"),e.channel=null,t.teardown(),this.scheduleRejoin(e))}}),!0}catch{return i&&this.removeChannel(i),this.captureFailure("channel-start"),!1}}reportDisruption(e,t){if(!e.disruptionReported)for(let r of(e.disruptionReported=!0,this.captureFailure(t,e.topic),[...e.listeners]))r.onDisrupted()}scheduleRejoin(e){this.clearRejoinTimer(e);let t=Math.min(1e3*2**e.rejoinAttempts,6e4);e.rejoinAttempts+=1,e.rejoinTimer=setTimeout(()=>{e.rejoinTimer=null,this.stopped||this.topics.get(e.topic)!==e||(e.startPromise=this.startTopic(e,!0))},t)}clearRejoinTimer(e){e.rejoinTimer&&(clearTimeout(e.rejoinTimer),e.rejoinTimer=null)}releaseListener(e,t){e.listeners.delete(t),!(e.listeners.size>0)&&this.topics.get(e.topic)===e&&(this.topics.delete(e.topic),this.clearRejoinTimer(e),e.channel&&this.removeChannel(e.channel))}removeChannel(e){let t=this.clientPromise;t?t.then(async t=>{if(!t)return void e.teardown();try{let r=await t.removeChannel(e);"ok"!==r&&(this.captureFailure("channel-removal"),await this.rebuildClient(t))}catch{this.captureFailure("channel-removal"),await this.rebuildClient(t)}}):e.teardown()}rebuildClient(e){if(this.rebuildPromise)return this.rebuildPromise;for(let e of this.topics.values())this.clearRejoinTimer(e),e.channel=null,e.joined=!1;return this.rebuildPromise=(async()=>{try{await e.removeAllChannels()}catch{this.captureFailure("channel-cleanup")}if(!this.stopped)for(let e of(this.clientPromise=null,this.topics.values())
1)e.startPromise=this.startTopic(e,!1)})().finally(()=>{this.rebuildPromise=null}),this.rebuildPromise}captureFailure(e,t){ra(e,this.failureCallbacks.values(),t)}}let rc=null,rd=0,rl=0,rp=new Set(["CONNECTION_REQUIRED","SCHEMA_VERSION_UNSUPPORTED"]),ru=Object.freeze({message:"Live updates are unavailable because this app surface reached its subscription limit.",code:"QUOTA_EXCEEDED",retryable:!1}),rf=new Set,rg=!1;function rh(){if("visible"===document.visibilityState)for(let e of[...rf])e()}function rm(e,t){(0,tN.captureException)(Error("SDK data Realtime host failed"),{tags:{component:"sdk-data-realtime",operation:t}});try{e.onRealtimeFailure?.(t)}catch{}}function ry(e){return(0,c.isObjectRecord)(e)&&"string"==typeof e.code?Object.freeze({message:e instanceof Error||"string"==typeof e.message?e.message:"The operation could not be completed.",code:e.code,...(0,c.isObjectRecord)(e.details)?{details:e.details}:{},retryable:!0===e.retryable}):Object.freeze({message:"The operation could not be completed.",code:"INTERNAL_ERROR",retryable:!0})}class rw{options;subscriptions=new Map;currentPreparation=null;preparationPromise;repreparePromise=null;realtimeConfigPromise=null;configurationFailureCaptured=!1;documentOwner=null;retainedQueryBytes=0;stopped=!1;generation=0;cleanupVisibilityListener;constructor(e){this.options=e,this.preparationPromise=e.initialPreparation.then(e=>(this.stopped||(this.currentPreparation=e),e)),this.cleanupVisibilityListener=function(e){return"u"<typeof document?()=>void 0:(rf.add(e),rg||(rg=!0,document.addEventListener("visibilitychange",rh)),()=>{rf.delete(e),0===rf.size&&rg&&(rg=!1,document.removeEventListener("visibilitychange",rh))})}(()=>{for(let e of this.subscriptions.values())this.requestRead(e,!0)})}subscribe(e){if(this.stopped||this.subscriptions.has(e.subscriptionId))return;let t=function(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return null}}(e.query);if(null===t)return;if(this.subscriptions.size>=100||this.retainedQueryBytes+t>4194304||!(Number.isSafeInteger(t)&&!(t<=0)&&!(t>1048576)&&!(rd>=500)&&!(rl+t>0x1000000)&&(rd+=1,rl+=t,1)))return void this.runOneShotRead(e);let r={id:e.subscriptionId,alias:e.alias,query:e.query,stopped:!1,queryBytes:t,inFlight:!1,dirty:!1,scheduled:!1,routingGeneration:0,staleRecoveryAttempted:!1,retryTimer:null,retryNotBefore:0,automaticRetryAttempts:0,channelLeases:new Map,waitingForFirstJoin:new Set};this.subscriptions.set(r.id,r),this.retainedQueryBytes+=t,this.runRead(r),this.attachChannels(r)}unsubscribe(e){let t=this.subscriptions.get(e);t&&this.stopSubscription(t)}cleanup(){if(!this.stopped){for(let e of(this.stopped=!0,this.generation+=1,this.cleanupVisibilityListener(),[...this.subscriptions.values()]))this.stopSubscription(e);this.releaseDocumentOwner()}}async getPreparation(){return this.currentPreparation??await this.preparationPromise}routeFor(e,t){return e.realtime.routes.find(e=>e.alias===t)??null}isStale(e,t){return this.stopped||e.stopped||t!==e.routingGeneration}captureConfigurationFailure(e){this.configurationFailureCaptured||(this.configurationFailureCaptured=!0,rm(this.options.config,e))}resolveRealtimeConfig(){if(this.realtimeConfigPromise)return this.realtimeConfigPromise;if(void 0===this.options.config.resolveRealtimeConfig&&void 0===this.options.config.realtimeConfig)return this.realtimeConfigPromise=Promise.resolve(null),this.realtimeConfigPromise;let e=Promise.resolve().then(()=>this.options.config.resolveRealtimeConfig?this.options.config.resolveRealtimeConfig():this.options.config.realtimeConfig??null).then(e=>(null===e&&this.captureConfigurationFailure("configuration-unavailable"),e)).catch(()=>(this.captureConfigurationFailure("configuration-resolution"),null));return this.realtimeConfigPromise=e,e.then(t=>{null===t&&this.realtimeConfigPromise===e&&(this.realtimeConfigPromise=null)}),e}ensureDocumentOwner(e){return this.documentOwner||(this.documentOwner=function(e){let t=function(e){if(!e)return null;let t=e.publishableKey.trim();if(0===t.length||t.length>4096)return null;try{if(e.supabaseUrl.length>2048)return null;let r=new URL(e.supabaseUrl);if("https:"!==r.protocol||""!==r.username||""!==r.password||""!==r.search||""!==r.hash||""!==r.pathname&&"/"!==r.pathname)return null;return r.protocol="wss:",r.pathname="/realtime/v1",Object.freeze({endpoint:r.toString(),publishableKey:t})}catch{return null}}(e.config.realtimeConfig),r=e.config.onRealtimeFailure;if(!t)return ra("configuration-invalid",r?[r]:[]),null;if(!e.config.loadRealtimeClient||!e.config.getRealtimeAccessToken)return ra("configuration-incomplete",r?[r]:[]),null;if(rc){if(!rc.matches(t))return ra("configuration-mismatch",r?[r]:[]),null}else rc=new rs({config:t,loadClient:e.config.loadRealtimeClient});let i=rc;i.addOwner(e.ownerId,e.config.getRealtimeAccessToken,r);let n=!1;return Object.freeze({acquireChannel:(e,t)=>
1i.acquireChannel(e,t),release:()=>{!n&&(n=!0,i.removeOwner(e.ownerId),i.hasOwners()||rc!==i||(rc=null,i.stop(r?[r]:[])))}})}({ownerId:this.options.config.sessionToken,config:{...this.options.config,realtimeConfig:e}})),this.documentOwner}async attachChannels(e){let t,r=this.generation,i=e.routingGeneration,n=()=>r!==this.generation||this.isStale(e,i);try{t=await this.getPreparation()}catch{return}if(n()||!t.realtime.enabled)return;let o=this.routeFor(t,e.alias);if(!o||0===o.topics.length)return;let a=await this.resolveRealtimeConfig();if(!a||n())return;let s=this.ensureDocumentOwner(a);if(!s)return;e.waitingForFirstJoin=new Set(o.topics);let c=t=>{e.waitingForFirstJoin.delete(t)&&0===e.waitingForFirstJoin.size&&this.requestRead(e,!0)};for(let t of o.topics){let r=await s.acquireChannel(t,{onInvalidation:t=>{!n()&&t.storeIds.has(o.storeId)&&(t.routingChanged?this.reprepareAndRefetch("routing-changed"):this.requestRead(e,!0))},onSubscribed:r=>{n()||(r?this.requestRead(e,!0):c(t))},onDisrupted:()=>{n()||this.requestRead(e,!0)}});if(n())return void r?.release();if(!r){c(t);continue}e.channelLeases.set(t,r),r.joined&&c(t)}}releaseSubscriptionChannels(e){for(let t of(e.routingGeneration+=1,e.waitingForFirstJoin.clear(),e.channelLeases.values()))t.release();e.channelLeases.clear()}releaseDocumentOwner(){this.documentOwner?.release(),this.documentOwner=null}requestRead(e,t){if(e.stopped||this.stopped)return;if(t&&(e.automaticRetryAttempts=0),e.inFlight){e.dirty=!0;return}let r=e.retryNotBefore-Date.now();if(r>0){e.dirty=!0,e.retryTimer||(e.retryTimer=setTimeout(()=>{e.retryTimer=null,e.retryNotBefore=0,this.requestRead(e,!1)},r));return}e.scheduled||(e.scheduled=!0,queueMicrotask(()=>{e.scheduled=!1,e.stopped||this.stopped||this.runRead(e)}))}async runRead(e){if(e.stopped||this.stopped)return;if(e.inFlight){e.dirty=!0;return}e.inFlight=!0,e.dirty=!1;let t=this.generation,r=e.routingGeneration;try{let i=await this.getPreparation(),n=await this.options.executeQuery(e.alias,e.query,i);if(t!==this.generation||this.isStale(e,r))return;e.staleRecoveryAttempted=!1,this.postData(e.id,n)}catch(r){if(this.stopped||e.stopped)return;let t=ry(r);if(rp.has(t.code)&&!e.staleRecoveryAttempted&&(e.staleRecoveryAttempted=!0,await this.reprepareAndRefetch("stale-routing")))return;if(this.postError(e.id,t),!t.retryable)return void this.stopSubscription(e);e.automaticRetryAttempts<1&&(e.automaticRetryAttempts+=1,e.retryNotBefore=Date.now()+Math.max(0,Math.min(t.details?.kind==="limit"&&"number"==typeof t.details.retryAfterMs&&Number.isSafeInteger(t.details.retryAfterMs)?t.details.retryAfterMs:1e3,6e4)),e.dirty=!0)}finally{e.inFlight=!1,e.dirty&&!e.stopped&&this.requestRead(e,!1)}}async runOneShotRead(e){let t=this.generation;try{let r=await this.getPreparation(),i=await this.options.executeQuery(e.alias,e.query,r);this.stopped||t!==this.generation||(this.postData(e.subscriptionId,i),this.postError(e.subscriptionId,ru))}catch(r){if(!this.stopped&&t===this.generation){let t=ry(r);this.postError(e.subscriptionId,{...t,retryable:!1})}}}reprepareAndRefetch(e){return this.stopped||0===this.subscriptions.size?Promise.resolve(!1):(this.repreparePromise??=this.options.prepareFresh().then(e=>{if(this.stopped)return!1;for(let t of(this.currentPreparation=e,this.preparationPromise=Promise.resolve(e),this.options.replacePreparation(e),[...this.subscriptions.values()]))this.releaseSubscriptionChannels(t),this.attachChannels(t),this.requestRead(t,!0);return!0}).catch(()=>{for(let t of(rm(this.options.config,e),this.subscriptions.values()))this.requestRead(t,!0);return!1}).finally(()=>{this.repreparePromise=null}),this.repreparePromise)}stopSubscription(e){if(!e.stopped){var t;e.stopped=!0,e.retryTimer&&clearTimeout(e.retryTimer),this.releaseSubscriptionChannels(e),this.subscriptions.delete(e.id),this.retainedQueryBytes=Math.max(0,this.retainedQueryBytes-e.queryBytes),t=e.queryBytes,rd=Math.max(0,rd-1),rl=Math.max(0,rl-t),0===this.subscriptions.size&&this.releaseDocumentOwner()}}postData(e,t){this.options.postMessage({type:ro,subscriptionId:e,sessionToken:this.options.config.sessionToken,event:"data",result:t})}postError(e,t){this.options.postMessage({type:ro,subscriptionId:e,sessionToken:this.options.config.sessionToken,event:"error",error:t})}}let rb=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,rv=/^odr1:[0-9a-f]{64}$/;function rI(e,t){return Object.keys(e).every(e=>t.includes(e))}
1function rE(e){if(!(0,c.isObjectRecord)(e)||!rI(e,["alias","storeId","topics"])||"string"!=typeof e.alias||!rb.test(e.alias)||"string"!=typeof e.storeId||!(0,v.isValidUUID)(e.storeId)||!Array.isArray(e.topics)||e.topics.length>3)throw Error("The data connection returned invalid Realtime routing.");let t=[],r=null;for(let i of e.topics){if("string"!=typeof i||!rv.test(i)||69!==new TextEncoder().encode(i).byteLength||null!==r&&i<=r)throw Error("The data connection returned invalid Realtime routing.");t.push(i),r=i}return Object.freeze({alias:e.alias,storeId:e.storeId,topics:Object.freeze(t)})}async function rT(e){if(void 0===e.ownerDataAliases)throw Error("Owner data is not declared by this app.");let t=await O({config:e,input:"/api/apps/sdk/data/prepare",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e.appId,aliases:e.ownerDataAliases,runtimeSessionKey:e.sessionToken})}}),r=await t.json().catch(()=>null);if(!t.ok)throw Error((0,c.isObjectRecord)(r)&&"string"==typeof r.message?r.message:"The data connection could not be prepared.");if(!(0,c.isObjectRecord)(r)||!rI(r,["descriptor","realtime"])||"string"!=typeof r.descriptor||0===r.descriptor.length||new TextEncoder().encode(r.descriptor).byteLength>0x1000000||!(0,c.isObjectRecord)(r.realtime)||!rI(r.realtime,["enabled","routes"])||"boolean"!=typeof r.realtime.enabled||!Array.isArray(r.realtime.routes)||r.realtime.routes.length>100||!r.realtime.enabled&&0!==r.realtime.routes.length)throw Error("The data connection could not be prepared.");let i=r.realtime.routes.map(rE),n=new Set;for(let e of i){if(n.has(e.alias))throw Error("The data connection returned duplicate Realtime routing.");n.add(e.alias)}return Object.freeze({descriptor:r.descriptor,realtime:Object.freeze({enabled:r.realtime.enabled,routes:Object.freeze(i)})})}e.s(["prepareSdkDataRuntime",0,rT],491421);let rR=/^[A-Za-z0-9_-]+$/,rO=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,rk=new Set(["get","find","exists","count","aggregate"]);function rS(e,t,r=[]){let i=Object.keys(e);return t.every(e=>i.includes(e))&&i.every(e=>t.includes(e)||r.includes(e))}function rA(e){return"string"==typeof e&&e.length>0&&e.length<=128&&rR.test(e)}function rN(e){if(!(0,c.isObjectRecord)(e))return!1;try{return new TextEncoder().encode(JSON.stringify(e)).byteLength<=1048576}catch{return!1}}function rD(e){for(let t of e.ports)t.close()}let rP=new Set(["sdk-call","reload-app","fix-with-ai",td,ri,rn]);function rC(e,t){let{onError:r,onReady:i,onReload:n,onFixWithAI:d}=t,l=e.sandbox.contains("allow-same-origin"),p=l?window.location.origin:"null",u=l?window.location.origin:"*",f=!1,g=!0===t.iframeDocumentAlreadyLoaded,h=(0,s.registerReplayFrame)(e,t.sessionToken,t.iframeDocumentAlreadyLoaded),m=null,y=(e,r)=>{m?.postMessage({type:ro,subscriptionId:e,sessionToken:t.sessionToken,event:"error",error:r})};(0,o.registerAppFrameMount)(t.appId)&&(0,o.setAppNotReady)(t.appId);let w=(t8.add(e),t3||"u">typeof document&&(document.addEventListener("pointerdown",t5,!0),t3=!0),()=>{t8.delete(e),t9===e&&(t9=null),"u"<typeof document||t8.size>0||t3&&(document.removeEventListener("pointerdown",t5,!0),t3=!1)}),b={effectivePolicy:t.effectivePolicy},v={promptedOperationIds:new Set,deniedPermissions:new Set},I=t.workspace,E=I?{...t,workspaceRequest:(e,t)=>(0,a.workspaceFetchFor)(I,e,{credentials:"same-origin",...t})}:t,T=t.sdkDataRuntimePreparation?new rw({config:E,initialPreparation:t.sdkDataRuntimePreparation,executeQuery:(e,r,i)=>{let n={...E,sdkDataRuntimePreparation:Promise.resolve(i)},o=()=>_({config:n,appId:t.appId,method:r.method,alias:e,input:r.input});return I?(0,a.runWorkspaceMutation)(o,I):o()},prepareFresh:()=>{let e=()=>rT(E);return I?(0,a.runWorkspaceMutation)(e,I):e()},replacePreparation:e=>{t.sdkDataRuntimePreparation=Promise.resolve(e),E.sdkDataRuntimePreparation=Promise.resolve(e)},postMessage:e=>{f||m?.postMessage(e)}}):null,R=async s=>{if(f||s.source!==e.contentWindow)return;let l=s.data;if(null===l||"object"!=typeof l||"string"!=typeof l.type||s.origin!==p||rP.has(l.type)&&l.sessionToken!==t.sessionToken||l.type!==ri&&s.ports.length>0)return void rD(s);switch(l.type){case"sdk-call":{let r;"sdk.ready"===l.method&&((0,o.setAppReady)(t.appId),i?.());try{if(t.workspace&&"sdk.ready"!==l.method){let i=t.workspace;
1(0,a.requireWorkspaceMutationAdmission)(i);let n=t.teamContext?.isTeamApp?t.getTeamRuntimeToken?.():void 0,o={...t,workspaceRequest:(e,t)=>(0,a.workspaceFetchFor)(i,e,{credentials:"same-origin",...t}),...n?{getTeamRuntimeToken:()=>n}:{}};r=await (0,a.runWorkspaceMutation)(()=>t2({call:l,config:o,policyState:b,permissionState:v,iframe:e,targetOrigin:u}),i)}else r=await t2({call:l,config:t,policyState:b,permissionState:v,iframe:e,targetOrigin:u})}catch(t){let e;e=t instanceof a.WorkspaceTransitionInProgressError,r={type:"sdk-response",id:l.id,error:{message:t instanceof Error?t.message:"App operation failed",code:e?t.code:"WORKSPACE_OPERATION_FAILED"}}}if(f)return;e.contentWindow?.postMessage(r,u);break}case ri:{if(m){if(0!==s.ports.length){rD(s);break}}else{let e=s.ports[0];if(1!==s.ports.length||!e){rD(s);break}m=e,e.start()}let e=function(e){if(!(0,c.isObjectRecord)(e)||!rS(e,["type","subscriptionId","alias","query","sessionToken"])||e.type!==ri||!rA(e.subscriptionId)||"string"!=typeof e.alias||!rO.test(e.alias)||"string"!=typeof e.sessionToken)return null;let t=function(e){if(!rN(e)||!rS(e,["method"],["input"])||"string"!=typeof e.method||!rk.has(e.method))return null;switch(e.method){case"get":if(!rN(e.input)||!rS(e.input,["id"],["options"])||"string"!=typeof e.input.id||0===e.input.id.length)break;return e;case"exists":case"aggregate":return rN(e.input)?e:null;case"find":case"count":return void 0===e.input||rN(e.input)?e:null}return null}(e.query);return t?Object.freeze({type:ri,subscriptionId:e.subscriptionId,alias:e.alias,query:t,sessionToken:e.sessionToken}):null}(l);if(!e){"string"==typeof l.subscriptionId&&l.subscriptionId.length<=128&&y(l.subscriptionId,{message:"This subscription request is not valid.",code:"INVALID_INPUT",retryable:!1});break}if(!T){y(e.subscriptionId,{message:"This app does not have declared data access.",code:"NOT_AUTHORIZED",retryable:!1});break}T.subscribe(e);break}case rn:{let e=(0,c.isObjectRecord)(l)&&rS(l,["type","subscriptionId","sessionToken"])&&l.type===rn&&rA(l.subscriptionId)&&"string"==typeof l.sessionToken?Object.freeze({type:rn,subscriptionId:l.subscriptionId,sessionToken:l.sessionToken}):null;e&&e.sessionToken===t.sessionToken&&T?.unsubscribe(e.subscriptionId);break}case"sdk-error":{let e=(0,o.formatRuntimeErrorForLog)(l.error);(0,o.addAppLog)(t.appId,"error",[e],Date.now()),r?.(l.error);break}case"app-ready":(0,o.setAppReady)(t.appId),i?.();break;case"reload-app":n?.();break;case"fix-with-ai":{let e=l.error;d&&e&&d(e);break}case"console":{if(!(0,c.isObjectRecord)(l))break;let e=l.level,i="log"===e||"warn"===e||"error"===e||"info"===e?e:"log",n=l.args,a=Array.isArray(n)?n.map(String):[],s=l.timestamp,d="number"==typeof s&&Number.isFinite(s)?s:Date.now();if("error"===i&&a.some(e=>
1e.includes("IntegrationConnectDismissedError")))break;(0,o.addAppLog)(t.appId,i,a,d),"error"===i&&r&&r({message:a.join(" ")||"App reported an error"});break}case"dismiss-host-overlays":if("u">typeof document)try{let e={key:"Escape",code:"Escape",bubbles:!0,cancelable:!0};document.dispatchEvent(new KeyboardEvent("keydown",e)),document.dispatchEvent(new KeyboardEvent("keyup",e))}catch{}t9!==e&&t6(t9),t9=e;break;case t7:rt(t.appId);break;case td:!function(e,t,r){if("string"!=typeof t||"number"!=typeof r)return;let i=tP.get(t);i&&"camera"===i.kind&&i.ownerToken===e&&i.awaitingAckFrameId===r&&(i.awaitingAckFrameId=null)}(t.sessionToken,l.sessionId,l.frameId)}},O=()=>void 0,k=()=>{if(!f){f=!0,h(),window.removeEventListener("message",R),O(),m?.close(),m=null,T?.cleanup(),w(),(0,rr.closeSdkLightboxForOwner)(t.sessionToken);var e=t.sessionToken;for(let t of Array.from(tP.values()))t.ownerToken===e&&tU(t,null);ta(t.sessionToken),(0,o.unregisterAppFrameMount)(t.appId)&&((0,o.setAppNotReady)(t.appId),(0,o.clearAppReadyState)(t.appId),(0,o.clearAppLogs)(t.appId))}},S=()=>{if(!g){g=!0;return}k(),n?.()};return window.addEventListener("message",R),e.addEventListener("load",S),O=()=>{e.removeEventListener("load",S)},k}async function r_(){return(await e.A(980207)).RealtimeClient}function rj(){let e="https://qnoxnxvqaicpfzvsafcy.supabase.co".trim(),t="sb_publishable_yVyjyqhrTcrw_USXuKurDA_0KjQL68y".trim();return e&&t?Object.freeze({supabaseUrl:e,publishableKey:t}):null}async function rM(e,t,r){return(0,a.runWorkspaceMutation)(async()=>{var i;let n=await (0,a.workspaceFetch)(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:t,...r?.builderPreview?{builderPreview:r.builderPreview}:{},...r?.previousRuntimeToken?{previousRuntimeToken:r.previousRuntimeToken}:{}})}),o=(i=await n.json().catch(()=>null),(0,c.isObjectRecord)(i)&&(void 0===i.runtimeToken||"string"==typeof i.runtimeToken)&&(void 0===i.error||"string"==typeof i.error)&&(void 0===i.code||"string"==typeof i.code)?{..."string"==typeof i.runtimeToken?{runtimeToken:i.runtimeToken}:{},..."string"==typeof i.error?{error:i.error}:{},..."string"==typeof i.code?{code:i.code}:{}}:null);if(!n.ok||"string"!=typeof o?.runtimeToken){let e;throw e=Error(o?.error||"Failed to create a team runtime session."),"string"==typeof o?.code&&(e.code=o.code),e}return o.runtimeToken})}async function rx(e,t){return rM("/api/apps/runtime-sessions",e,{builderPreview:t})}async function rL(e,t,r){return rM("/api/apps/runtime-sessions/refresh",e,{builderPreview:t,previousRuntimeToken:r})}function rU(e,t="Unknown app error"){return"string"==typeof e?{message:e}:(0,c.isObjectRecord)(e)?{message:"string"==typeof e.message?e.message:t,stack:"string"==typeof e.stack?e.stack:void 0}:{message:t}}e.s(["createIframeHost",0,rC],454862),e.s(["getNextRealtimeConfig",0,rj,"loadNextRealtimeClient",0,r_],935792),e.s(["mintTeamRuntimeToken",0,rx,"requestRefreshedTeamRuntimeToken",0,rL],689454),e.s(["formatAppIframeError",0,function(e){if(!e.stack)return e.message;let t=e.stack.trim();return t?t.includes(e.message)?t:`${e.message} 2${t}`:e.message},"normalizeAppIframeError",0,rU,"useAppIframeHandler",0,function(e,i={}){let{getToken:s}=(0,r.useAuth)(),c=(0,t.useRef)(null),d=(0,t.useRef)(null),l=(0,t.useRef)(0),p=(0,t.useRef)(e.effectivePolicy),[u,f]=(0,t.useState)("idle"),[g,h]=(0,t.useState)(null),[m,y]=(0,t.useState)(0),w=(0,t.useRef)(i);(0,t.useEffect)(()=>{w.current=i},[i]),(0,t.useEffect)(()=>{p.current=e.effectivePolicy},[e.effectivePolicy]);let b=(0,t.useCallback)(()=>{c.current&&(clearTimeout(c.current),c.current=null),d.current&&(clearTimeout(d.current),d.current=null)},[]),v=(0,t.useCallback)((e,t)=>{h({message:e,stack:t}),f("error"),b(),w.current.onError?.({message:e,stack:t})},[b]),I=(0,t.useCallback)(()=>{(0,o.clearAppLogs)(e.appId),y(e=>e+1)},[e.appId]),E=(0,t.useCallback)((t,r)=>{let i,o=++l.current,u=null,g=async()=>{if(!e.teamContext?.isTeamApp)return null;u??=rx(e.appId,e.builderPreview);try{return await u}catch(e){throw u=null,e}},m=async()=>{if(!e.teamContext?.isTeamApp)return null;let t=await u?.catch(()=>null);u=rL(e.appId,e.builderPreview,t);try{return await u}catch(e){throw u=null,e}};b(),h(null),f("loading");let y=e.hostRequest?{workspaceRequest:e.hostRequest}:{workspace:i=(0,a.getActiveWorkspaceRef)(),workspaceRequest:(e,t)=>
2(0,a.workspaceFetchFor)(i,e,{credentials:"same-origin",...t})},E=e.hostRequest?void 0:rj(),T={appId:e.appId,appName:e.appName,appImage:e.appImage,userId:e.userId,userName:e.userName,teamContext:e.teamContext,...y,getTeamRuntimeToken:g,refreshTeamRuntimeToken:m,effectivePolicy:p.current,source:e.source,sessionToken:r.sessionToken,ownerDataAliases:e.ownerDataAliases,...void 0===E?{}:{realtimeConfig:E},...E?{getRealtimeAccessToken:e=>s(e),loadRealtimeClient:r_}:{},onOwnerFilePick:e.onOwnerFilePick,getViewportController:e.getViewportController,onError:e=>{if(l.current!==o)return;let t=rU(e);v(t.message,t.stack)},onReady:()=>{l.current===o&&(b(),d.current=setTimeout(()=>{l.current===o&&(f("ready"),w.current.onReady?.())},100))},onToast:n,onLightbox:t=>{(0,rr.openSdkLightbox)({...t,ownerToken:r.sessionToken,appName:e.appName})},onReload:()=>{l.current===o&&(w.current.onReloadRequest?.(),I())},onFixWithAI:e=>{l.current===o&&w.current.onFixWithAI?.(e)},onPermissionPrompt:async t=>{let r=e.teamContext?.isTeamApp?await g().catch(()=>null):null;return await w.current.onPermissionPrompt?.({...t,...r?{runtimeToken:r}:{},...e.builderPreview?{runtimePurpose:"builder_preview"}:{}})??{decision:"dismissed"}},onIntegrationPrompt:async e=>await w.current.onIntegrationPrompt?.(e)??{decision:"dismissed"}};if(void 0!==e.ownerDataAliases){let e=rT(T);e.catch(()=>void 0),T.sdkDataRuntimePreparation=e}let R=rC(t,T);return e.teamContext?.isTeamApp&&g().catch(()=>null),c.current=setTimeout(()=>{l.current===o&&v("App loading timed out. This might be due to network issues or a problem with the app.")},3e4),()=>{R(),b()}},[e.appId,e.appName,e.appImage,e.userId,e.userName,e.teamContext,e.builderPreview,e.source,e.ownerDataAliases,e.onOwnerFilePick,e.hostRequest,e.getViewportController,s,b,v,I]);return(0,t.useEffect)(()=>()=>{b()},[b]),{status:u,error:g,reloadApp:I,clearLoadingTimeout:b,setError:v,setStatus:f,iframeKey:m,startHandler:E}}],381674)}]); 3 4//# chunkId=01a0804f-843d-7812-a01e-d64631953452
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.