@blotout/qinto-cli 0.1.13 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14822,6 +14822,7 @@ var endpointContextSchema = external_exports.object({
14822
14822
  mode: external_exports.enum(["webhook", "api"]),
14823
14823
  version: external_exports.string().min(1).max(32),
14824
14824
  site: external_exports.object({ origin: external_exports.string().min(1).max(255) }).strict(),
14825
+ geo: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
14825
14826
  installs: external_exports.array(installSchema3).min(1).max(15)
14826
14827
  }).strict().refine((context) => {
14827
14828
  return context.mode === "webhook" || context.installs.length === 1;
@@ -15518,6 +15519,24 @@ var brokerFactsRead = async (env, userId, input = {}) => {
15518
15519
  });
15519
15520
  return { items: answer.items ?? [], nextCursor: answer.nextCursor ?? null };
15520
15521
  };
15522
+ var brokerIdentityRead = async (env, identifier, options = {}) => {
15523
+ const answer = await askBroker(env, "apps.identity resolve", {
15524
+ v: ENVELOPE_VERSION,
15525
+ kind: "identityRead",
15526
+ slug: callerSlug(env),
15527
+ key: env.QINTO_INTERNAL_KEY,
15528
+ identifier,
15529
+ ...options.cursor === void 0 ? {} : { cursor: options.cursor }
15530
+ });
15531
+ return { globalId: answer.globalId ?? null, anonIds: answer.anonIds ?? [], nextCursor: answer.nextCursor ?? null };
15532
+ };
15533
+ var buildIdentity = (env) => {
15534
+ return {
15535
+ resolve: (identifier, options) => {
15536
+ return brokerIdentityRead(env, identifier, options);
15537
+ }
15538
+ };
15539
+ };
15521
15540
  var brokerActive = async (env, input) => {
15522
15541
  let response;
15523
15542
  try {
@@ -16043,6 +16062,7 @@ var buildWorkflowContext = (env, stamp) => {
16043
16062
  appSecrets,
16044
16063
  userId: stamp.anonId,
16045
16064
  observability: buildObservability(stamp.ord),
16065
+ identity: buildIdentity(env),
16046
16066
  context: asyncContext(env, (what) => {
16047
16067
  return requireSubject(stamp.anonId, what);
16048
16068
  }),
@@ -16175,6 +16195,7 @@ var buildContext = ({
16175
16195
  }
16176
16196
  },
16177
16197
  observability: buildObservability(install.ord),
16198
+ identity: buildIdentity(env),
16178
16199
  apps: buildAppsClient(env, envelope)
16179
16200
  };
16180
16201
  };
@@ -16293,6 +16314,7 @@ var dispatchSchedule = async (envelope, bundle, env) => {
16293
16314
  appVariables: appScope.appVariables,
16294
16315
  appSecrets: appScope.appSecrets,
16295
16316
  observability: buildObservability(install.ord),
16317
+ identity: buildIdentity(env),
16296
16318
  apps: buildAppsClient(env, { depth: 0 }),
16297
16319
  query: buildQuery({ env, ticket: install.queryTicket, installId: install.id }),
16298
16320
  push: async (userId, message) => {
@@ -16413,6 +16435,7 @@ var buildContext2 = (envelope, env) => {
16413
16435
  appVariables: appScope.appVariables,
16414
16436
  appSecrets: appScope.appSecrets,
16415
16437
  observability: buildObservability(install.ord),
16438
+ identity: buildIdentity(env),
16416
16439
  apps: buildAppsClient(env, { depth: 0 }),
16417
16440
  query: buildQuery({ env, ticket: envelope.tool.queryTicket, installId: install.id }),
16418
16441
  fail: (message) => {
@@ -16634,11 +16657,21 @@ var handlerRequest = (request, context, body) => {
16634
16657
  body: body.byteLength === 0 ? void 0 : body
16635
16658
  });
16636
16659
  };
16637
- var buildContext3 = ({ env, maps, kinds, appScope, install, site, params }) => {
16660
+ var buildContext3 = ({
16661
+ env,
16662
+ maps,
16663
+ kinds,
16664
+ appScope,
16665
+ install,
16666
+ site,
16667
+ geo,
16668
+ params
16669
+ }) => {
16638
16670
  const { variables, secrets } = projectInstallValues(maps, kinds, install.ord);
16639
16671
  return {
16640
16672
  env,
16641
16673
  site,
16674
+ geo,
16642
16675
  params,
16643
16676
  install: { id: install.id, label: install.label },
16644
16677
  // An endpoint has no visitor, so a workflow it starts cannot push. `push` below is the
@@ -16650,6 +16683,7 @@ var buildContext3 = ({ env, maps, kinds, appScope, install, site, params }) => {
16650
16683
  appVariables: appScope.appVariables,
16651
16684
  appSecrets: appScope.appSecrets,
16652
16685
  observability: buildObservability(install.ord),
16686
+ identity: buildIdentity(env),
16653
16687
  apps: buildAppsClient(env, { depth: 0 }),
16654
16688
  push: async (userId, message) => {
16655
16689
  await brokerPush(env, {
@@ -16726,7 +16760,7 @@ var dispatchEndpoint = async ({ request, env, versions }) => {
16726
16760
  return installSpan(install, () => {
16727
16761
  return handler(
16728
16762
  handlerRequest(request, context, body),
16729
- buildContext3({ env, maps, kinds: variableKinds, appScope, install, site: context.site, params: context.params })
16763
+ buildContext3({ env, maps, kinds: variableKinds, appScope, install, site: context.site, geo: context.geo, params: context.params })
16730
16764
  );
16731
16765
  });
16732
16766
  };
@@ -16785,6 +16819,53 @@ var runAppInvocation = async (input, handle) => {
16785
16819
  }
16786
16820
  };
16787
16821
 
16822
+ // src/pipeline-retry.ts
16823
+ var ATTEMPTS = 3;
16824
+ var BASE_BACKOFF_MS = 100;
16825
+ var TRANSIENT_MESSAGES = [
16826
+ "storage caused object to be reset",
16827
+ "Network connection lost",
16828
+ "transient issue on remote node",
16829
+ "reset because its code was updated"
16830
+ ];
16831
+ var isTransient = (error51) => {
16832
+ if (!(error51 instanceof Error)) {
16833
+ return false;
16834
+ }
16835
+ const { retryable, overloaded } = error51;
16836
+ if (overloaded === true) {
16837
+ return false;
16838
+ }
16839
+ return retryable === true || TRANSIENT_MESSAGES.some((fragment) => error51.message.includes(fragment));
16840
+ };
16841
+ var sendWithRetry = async (binding, pipeline, records) => {
16842
+ for (let attempt = 1; ; attempt += 1) {
16843
+ try {
16844
+ return await pipeline.send(records);
16845
+ } catch (error51) {
16846
+ if (attempt === ATTEMPTS || !isTransient(error51)) {
16847
+ throw error51;
16848
+ }
16849
+ addSpanEvent("pipeline send retried", { level: "warn", attrs: { binding, attempt, "exception.message": error51.message } });
16850
+ await new Promise((resolve) => {
16851
+ setTimeout(resolve, Math.random() * BASE_BACKOFF_MS * 2 ** attempt);
16852
+ });
16853
+ }
16854
+ }
16855
+ };
16856
+ var withPipelineRetry = (env, bindings) => {
16857
+ const wrapped = { ...env };
16858
+ for (const name of bindings) {
16859
+ const pipeline = env[name];
16860
+ wrapped[name] = {
16861
+ send: (records) => {
16862
+ return sendWithRetry(name, pipeline, records);
16863
+ }
16864
+ };
16865
+ }
16866
+ return wrapped;
16867
+ };
16868
+
16788
16869
  // src/traced-fetch.ts
16789
16870
  var MAX_BODY_CHARS = 65536;
16790
16871
  var TOO_LARGE = `[not recorded: the body is over ${MAX_BODY_CHARS} characters]`;
@@ -16854,9 +16935,13 @@ var bodyAttribute = async (key, body) => {
16854
16935
  const text = await body;
16855
16936
  return text === void 0 ? void 0 : { [key]: text };
16856
16937
  };
16938
+ var INSTALLED = /* @__PURE__ */ Symbol.for("qinto.runtime.tracedFetch");
16857
16939
  var installTracedFetch = () => {
16940
+ if (globalThis.fetch[INSTALLED] === true) {
16941
+ return;
16942
+ }
16858
16943
  const original = globalThis.fetch.bind(globalThis);
16859
- globalThis.fetch = async (input, init) => {
16944
+ const wrapped = async (input, init) => {
16860
16945
  const { method, url: url2 } = requestParts(input, init);
16861
16946
  const sent = requestBody(input, init);
16862
16947
  return traced(`${method} ${new URL(url2).host}`, { attrs: { "http.request.method": method, "url.full": url2 } }, async () => {
@@ -16867,6 +16952,8 @@ var installTracedFetch = () => {
16867
16952
  return response;
16868
16953
  });
16869
16954
  };
16955
+ wrapped[INSTALLED] = true;
16956
+ globalThis.fetch = wrapped;
16870
16957
  };
16871
16958
 
16872
16959
  // src/settings.ts
@@ -16948,6 +17035,7 @@ var dispatchUi = async ({ request, env, versions }) => {
16948
17035
  appSecrets,
16949
17036
  viewer: context.viewer,
16950
17037
  observability: buildObservability(context.install.ord),
17038
+ identity: buildIdentity(env),
16951
17039
  apps: buildAppsClient(env, { depth: 0 })
16952
17040
  };
16953
17041
  let response;
@@ -17234,10 +17322,11 @@ var serve = async (input, request, env) => {
17234
17322
  };
17235
17323
  var createRuntime = (input) => {
17236
17324
  return {
17237
- fetch: async (request, env) => {
17238
- if (request.headers.get("x-qinto-app-key") !== env.QINTO_INTERNAL_KEY) {
17325
+ fetch: async (request, bindings) => {
17326
+ if (request.headers.get("x-qinto-app-key") !== bindings.QINTO_INTERNAL_KEY) {
17239
17327
  return jsonError(403, "forbidden");
17240
17328
  }
17329
+ const env = withPipelineRetry(bindings, input.pipelines);
17241
17330
  return runAppInvocation(
17242
17331
  {
17243
17332
  request,
@@ -0,0 +1 @@
1
+ (function(){var e=class extends Error{constructor(e){super(e),this.name=`QintoError`}},t=class extends e{constructor(e){super(e),this.name=`QintoTimeoutError`}},n=(e=Date.now())=>`evt_${globalThis.crypto.randomUUID()}_${e}`,r=(e,t)=>{if(e!==void 0)return e;let r=t?.orderId;return typeof r==`string`&&r!==``?r:n()},i=[`necessary`,`functional`,`analytics`,`marketing`,`salesOfData`],a=(e,t,n)=>n===void 0||!i.some(e=>e===n)?!1:n===`necessary`||e!==null&&e.categories[n]===!0&&e.apps[t]!==!1,o=()=>{},s=100,c=1024,l=32*1024,u=(e,t,n)=>e.target.config?.consentConfiguration?.enabled!==!0||a(n,t,e.target.config?.apps?.[t]?.category),d=e=>Object.values(e.config?.apps??{}).some(e=>e.category!==`necessary`||e.capture!==void 0),f=(e,t)=>{let{app:n,install:r,topic:i,to:a}=e;return typeof n!=`string`||typeof i!=`string`||r!==void 0&&typeof r!=`string`||t&&!(Array.isArray(a)&&a.every(e=>typeof e==`string`))},p=(e,t,n,r)=>r===null?e.slug===t&&(n===void 0||n===e.installId):r.has(e.slug),m=(e,t)=>{console.error(`[Qinto] A handler of app "${e.slug}" (install "${e.installId}") failed.`,t)},h=(e,t,n)=>{for(let r of t)try{let t=r(n);t instanceof Promise&&t.catch(t=>{m(e,t)})}catch(t){m(e,t)}},g=(e,t,n,r)=>{e.activated.add(r.id);let i={slug:t,installId:r.id,eventHandlers:[],consentHandlers:[],pushHandlers:[],sharedContextHandlers:[]};e.instances.push(i);let a={variables:r.variables,install:{id:r.id,label:r.label},getSession:async()=>{let n=await e.client.getSession();return e.target.config?.apps?.[t]?.geo===!0?n:{...n,ip:null,geo:null}},track:(t,n)=>{e.client.track(t,n).catch(o)},onEvent:e=>{i.eventHandlers.push(e)},onConsent:e=>{i.consentHandlers.push(e)},onPush:e=>{i.pushHandlers.push(e)},onSharedContext:n=>{if(e.target.config?.apps?.[t]?.sharedContext!==!0){console.error(`[Qinto] App "${t}" reads shared context without declaring the sharedContext capability.`);return}i.sharedContextHandlers.push(n),e.sharedContext!==null&&ee(e,t)&&h(i,[n],e.sharedContext)}};try{n(a)}catch(e){console.error(`[Qinto] App "${t}" failed to activate install "${r.id}".`,e)}},_=(e,t,n)=>{if(!u(e,t,e.consent))return;let r=((`_appInstalls`in e.target?e.target._appInstalls:void 0)?.[t]??[]).filter(t=>!e.activated.has(t.id));if(r.length===0)return;let i=n.factory;if(i===void 0){try{i=n.loader()}catch(e){i=null,console.error(`[Qinto] App "${t}" failed to load.`,e)}e.apps.set(t,{...n,factory:i})}if(i!==null)for(let n of r)g(e,t,i,n)},ee=(e,t)=>u(e,t,e.consent)?e.sharedContextConsent===void 0||u(e,t,e.sharedContextConsent):!1,te=e=>{let{categories:t,apps:n}=e;if(!(typeof t!=`object`||!t||typeof n!=`object`||!n))return{categories:t,apps:n}},ne=(e,t)=>{let n=e;n.consent=t,n.sharedContextConsent=void 0;for(let n of e.instances)h(n,n.consentHandlers,t);e.onConsentSettled?.(t);for(let[t,n]of e.apps)_(e,t,n)},v=async e=>{try{ne(e,await e.client.getConsent())}catch(e){console.error(`[Qinto] The apps consent read failed.`,e)}},y=e=>{let t;try{t=JSON.stringify(e)}catch{return}if(!(t===void 0||new TextEncoder().encode(t).length>c))return JSON.parse(t)},b=e=>{let t={};for(let n of e){if(n.settled!==n.total||n.values.length!==1)continue;let e=y(n.values[0]);if(e===void 0)continue;let r={...t[n.instance.slug]??{},[n.instance.installId]:e},i={...t,[n.instance.slug]:r};new TextEncoder().encode(JSON.stringify(i)).length<=l&&(t[n.instance.slug]=r)}return Object.keys(t).length===0?void 0:t},x=async(e,t)=>{e.onPageEvent?.(e.consent);let n=[],r=[];for(let i of e.instances){if(!u(e,i.slug,e.consent))continue;if(e.target.config?.apps?.[i.slug]?.eventResults?.includes(t.type)!==!0){h(i,i.eventHandlers,t);continue}let a={instance:i,total:i.eventHandlers.length,settled:0,values:[]};n.push(a);for(let e of i.eventHandlers){let n;try{n=e(t)}catch(e){a.settled+=1,m(i,e);continue}r.push(Promise.resolve(n).then(e=>{a.settled+=1,e!==void 0&&a.values.push(e)},e=>{a.settled+=1,m(i,e)}))}}if(r.length>0){let e=o,t=new Promise(t=>{e=t}),n=setTimeout(e,s);await Promise.race([Promise.all(r),t]),clearTimeout(n)}return b(n)},re=e=>{let{client:t}=e;return{track:async(n,i,a)=>{let o=r(a?.eventId,i),s=t.actionContext(),c=await x(e,{type:`track`,event:n,eventId:o,properties:i??{}});return await t.submitTrack({event:n,eventId:o,properties:i,context:s,appResults:c}),{eventId:o}},identify:async(n,r)=>{let i=t.actionContext(),a=await x(e,{type:`identify`,event:`identify`,properties:n??{}});return t.submitIdentify({traits:n,id:r,context:i,appResults:a})},alias:t.alias,consent:async n=>{if(await t.submitConsent(n,t.actionContext()),e.onConsentMutation?.(),d(e.target)){let t=e;t.consent=null,await v(e)}},getAnonId:t.getAnonId,getConsent:t.getConsent,getSession:t.getSession,close:t.close}},ie=(e,t)=>{let n=new Map,r=null,i=null,a=e=>{let[t,i]=e;if(n.has(t))return;let a={loader:i};n.set(t,a),r?.(t,a)},o=e,s=`_apps`in o?o._apps:void 0,c=Array.isArray(s)?s:[];c.push=(...e)=>{for(let t of e)a(t);return 0},o._apps=c;for(let e of c.splice(0))a(e);return{sharedContext:e=>{let{context:t}=e;if(typeof t!=`object`||!t||Array.isArray(t)){console.error(`[Qinto] The server sent a malformed shared context.`,e);return}let n=i;if(n===null)return;n.sharedContext=t;let r=te(e),a=r??n.consent;n.sharedContextConsent=r;for(let e of n.instances)u(n,e.slug,a)&&h(e,e.sharedContextHandlers,n.sharedContext)},push:e=>{let{app:t,install:n,topic:r,scope:a,to:o}=e,s=a===`site`;if(f(e,s)){console.error(`[Qinto] The server sent a malformed app push.`,e);return}let c=i;if(c===null)return;let l=s?new Set(o):null,d={topic:r,data:e.data,from:t};for(let e of c.instances)p(e,t,n,l)&&u(c,e.slug,c.consent)&&h(e,e.pushHandlers,d)},connect:async a=>{let o={target:e,client:a,apps:n,instances:[],activated:new Set,consent:null,sharedContext:i?.sharedContext??null,sharedContextConsent:i?.sharedContextConsent,onConsentSettled:t?.onConsentSettled,onConsentMutation:t?.onConsentMutation,onPageEvent:t?.onPageEvent};i=o,r=(e,t)=>{_(o,e,t),o.consent===null&&o.target.config?.consentConfiguration?.enabled===!0&&o.target.config?.apps?.[e]?.category!==`necessary`&&v(o)};for(let[e,t]of n)_(o,e,t);return e.config?.consentConfiguration?.enabled===!0&&d(e)?await v(o):o.onConsentSettled?.(o.consent),re(o)}}},ae=`PageView`,S=()=>{},oe=e=>{e.config?.autoCapture?.pageLoad===!0&&e.q.push([`track`,[ae],S,S])},C=512,w=1440*60*1e3,T=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Object.fromEntries(Object.entries(t).map(([e,t])=>[e,t.value]))])),E=(e,t)=>`qinto:cap:${encodeURIComponent(e)}:${encodeURIComponent(t)}`,D=e=>{try{let t=window.sessionStorage.getItem(e);if(t===null)return null;let n=JSON.parse(t);return typeof n.at!=`number`||typeof n.anonId!=`string`||typeof n.apps!=`object`||n.apps===null||Date.now()-n.at>w?null:{at:n.at,anonId:n.anonId,apps:n.apps}}catch{return null}},O=(e,t)=>{try{window.sessionStorage.setItem(e,JSON.stringify(t))}catch{}},k=e=>{try{window.sessionStorage.removeItem(e)}catch{}},A=e=>{try{return decodeURIComponent(e)}catch{return e}},j=()=>{let e={};for(let t of document.cookie.split(`;`)){let n=t.indexOf(`=`);n>0&&(e[t.slice(0,n).trim()]=A(t.slice(n+1)))}return e},M=(e,t)=>{let n={};for(let r of e.queryParams){let e=t.params.get(r);e!==null&&e.length<=C&&(n[r]={value:e,source:`query`})}for(let r of e.cookies){let e=t.cookies[r];e!==void 0&&e.length<=C&&(n[r]={value:e,source:`cookie`})}return n},N=(e,t)=>{let n={params:new URLSearchParams(window.location.search),cookies:j()},r={};for(let[i,o]of Object.entries(e.config?.apps??{})){if(o.capture===void 0||!a(t,i,o.category))continue;let e=M(o.capture,n);Object.keys(e).length>0&&(r[i]=e)}return r},P=(e,t)=>{let n={};for(let[r,i]of Object.entries(e)){let e=t[r]??{},a={};for(let[t,n]of Object.entries(i))(e[t]?.value!==n.value||e[t]?.source!==n.source)&&(a[t]=n);Object.keys(a).length>0&&(n[r]=a)}return n},F=(e,t,n,r)=>{let i=E(r,n),a=D(i),o=a?.apps??{},s=a?.anonId??null,c=a===null,l={},u=0,d=(e,t)=>{s!==null&&s!==e.anonId&&(o={}),s=e.anonId;let n=new Set(Object.entries(e.accepted).flatMap(([e,t])=>t.map(t=>`${e}\u0000${t}`)));for(let[e,r]of Object.entries(t))for(let[t,i]of Object.entries(r))n.has(`${e}\u0000${t}`)&&(o[e]={...o[e],[t]:i});O(i,{at:Date.now(),anonId:s,apps:o})},f=null,p=()=>{u+=1,o={},l={},k(i)},m=n=>{if(f=n,!c)return;let r=P(N(e,n),{...o,...l});if(Object.keys(r).length===0)return;let i=u;l={...l,...r},t(T(r)).then(e=>{i===u&&d(e,r)}).catch(()=>{}).finally(()=>{l={}})};return{settled:e=>{m(e)},needsAnon:()=>!c,observedAnon:e=>{(e===null||s!==null&&s!==e)&&p(),s=e,c=!0,m(f)},clear:p}},I=Symbol.for(`qinto.connectGate`),L=()=>{},R=e=>{let t=globalThis,n=(t[I]??Promise.resolve()).then(e);return t[I]=n.then(L,L),n},z=class extends e{constructor(e){super(e),this.name=`QintoProtocolError`}},B=e=>{if(typeof e!=`string`)return null;let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let n=t;return n.t===`ack`||n.t===`error`||n.t===`consentState`||n.t===`session`||n.t===`captureAck`||n.t===`appPush`||n.t===`sharedContext`?t:null},V=e=>{if(e.t===`consentState`)return{categories:e.categories,apps:e.apps};if(e.t===`session`)return{anonId:e.anonId,globalId:e.globalId,ip:e.ip,geo:e.geo};if(e.t===`captureAck`)return{anonId:e.anonId,accepted:e.accepted}},H=e=>{let n=new Map,r=e=>{let t=n.get(e);if(t!==void 0)return clearTimeout(t.timer),n.delete(e),t};return{submit:r=>new Promise((i,a)=>{let o={frame:r,sent:e.send(r),resolve:i,reject:a,timer:setTimeout(()=>{n.delete(r.ref),a(new t(`The Qinto request timed out.`))},e.requestTimeoutMs)};n.set(r.ref,o)}),flush:()=>{for(let t of n.values())t.sent||=e.send(t.frame)},deliver:e=>{let t=e.ref===void 0?void 0:r(e.ref);if(t!==void 0){if(e.t===`error`){t.reject(new z(e.message));return}t.resolve(V(e))}},rejectAll:e=>{let t=[...n.values()];n.clear();for(let n of t)clearTimeout(n.timer),n.reject(e)}}},U=e=>new WebSocket(e),se=500,W=3e4,G=`session not initialized`,K=(e,t)=>{let n=Math.min(se*2**e,W);return Math.round(n/2+n/2*t)},ce=(e,t)=>e.t===`appPush`?(t.onAppPush?.(e),!0):e.t===`sharedContext`?(t.onSharedContext?.(e),!0):!1,le=e=>{let t=`${e.destination.replace(/\/+$/,``)}/open`,n=null,r=null,i=0,a=null,o=H({send:e=>n===null||n.readyState!==1?!1:(n.send(JSON.stringify(e)),!0),requestTimeoutMs:e.requestTimeoutMs}),s=t=>{e.onError?.(t)},c=()=>{if(r!==null&&(clearTimeout(r),r=null),n!==null){let e=n;n=null,e.close()}o.rejectAll(new z(`connection closed`))},l=()=>{let u=U(t);n=u,u.onopen=()=>{i=0;let e=a;a=null,o.flush(),e?.resolve()},u.onmessage=t=>{let n=B(t.data);if(n===null){s(new z(`invalid message`));return}ce(n,e)||(`anonId`in n&&typeof n.anonId==`string`&&e.onAnonId?.(n.anonId),o.deliver(n),n.t===`error`&&n.message===G&&u.close())},u.onerror=()=>{s(new z(`connection closed`))},u.onclose=()=>{if(n!==u)return;n=null;let e=a;if(e!==null){a=null,c(),e.reject(new z(`connection closed`));return}o.rejectAll(new z(`connection closed`)),r=setTimeout(()=>{r=null,l()},K(i,Math.random())),i+=1}};return{connect:()=>new Promise((e,t)=>{a={resolve:e,reject:t},l()}),submit:e=>o.submit(e),close:()=>{c()}}},ue=1e4,de=()=>{let e=0;return()=>(e+=1,`q${e}`)},fe=(e,t)=>{let n=`qinto:visit:${e.replace(/\/+$/,``)}:${t}`,r,i=!1;try{let e=sessionStorage.getItem(n),t=e===null?null:JSON.parse(e);t===null||typeof t.id!=`string`||!/^vis_[0-9a-f-]{36}$/.test(t.id)||!Number.isSafeInteger(t.startedAt)||t.startedAt<0?(r={id:`vis_${crypto.randomUUID()}`,startedAt:Date.now()},sessionStorage.setItem(n,JSON.stringify(r)),i=!0):r={id:t.id,startedAt:t.startedAt}}catch{r={id:`vis_${crypto.randomUUID()}`,startedAt:Date.now()},i=!0}return()=>{let e={...r,isNew:i};return i=!1,e}},pe=(e,t,n,i)=>{let a=null,o=fe(n,i),s=()=>{let e=document.referrer;return{occurredAt:Date.now(),page:{url:window.location.href,...e===``?{}:{referrer:e}},session:o()}},c=async()=>{let n=await e.submit({t:`getSession`,ref:t()});return a=n.anonId,n};return{actionContext:s,submitIdentify:async({traits:n,id:r,context:i,appResults:a})=>{await e.submit({t:`identify`,ref:t(),traits:n,id:r,context:i,appResults:a})},submitTrack:async({event:n,eventId:r,properties:i,context:a,appResults:o})=>{await e.submit({t:`track`,ref:t(),event:n,eventId:r,properties:i,context:a,appResults:o})},submitConsent:async(n,r)=>{await e.submit({t:`consent`,ref:t(),categories:n.categories,apps:n.apps,context:r})},track:async(n,i,a)=>{let o=r(a?.eventId,i);return await e.submit({t:`track`,ref:t(),event:n,eventId:o,properties:i,context:s()}),{eventId:o}},alias:async n=>{await e.submit({t:`alias`,ref:t(),alias:n})},getConsent:async()=>await e.submit({t:`getConsent`,ref:t()}),getSession:c,getAnonId:async()=>(a===null&&await c(),a),close:()=>{e.close()}}},me=async e=>{let t=le({destination:e.destination,requestTimeoutMs:e.requestTimeoutMs??ue,onError:e.onError,onAppPush:e.onAppPush,onSharedContext:e.onSharedContext,onAnonId:e.onAnonId});await R(()=>t.connect());let n=de();return{client:pe(t,n,e.destination,e.globalName??`qinto`),submitCapture:async e=>await t.submit({t:`capture`,ref:n(),apps:e})}},he=[`then`,`ready`,`config`],q=()=>{},ge=(e,t)=>(...n)=>{let r=new Promise((r,i)=>{e.q.push([t,n,r,i])});return r.catch(q),r},J=e=>{let t=e;return t._q=1,t.q=[],new Proxy(t,{get:(e,n)=>typeof n!=`string`||he.includes(n)||n in t?Reflect.get(t,n):(t[n]=ge(t,n),t[n])})},_e=()=>{let e=document.currentScript?.dataset.qintoGlobal;return typeof e==`string`&&e!==``?e:`qinto`},ve=e=>typeof e==`object`&&!!e&&e._q===1,ye=(e=`qinto`)=>{let t=globalThis;if(e in t){let n=t[e];if(!ve(n))return null;let r=Array.isArray(n.q)?n:J(n);return r!==n&&Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0}),r}let n=J({});return Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0}),n},be=(t,n)=>async(r,i)=>{let a=Reflect.get(t,r);if(typeof a!=`function`)throw new e(`[Qinto] ${n}.${r} is not a method of this tag.`);return a.apply(t,Array.from(i))},Y=e=>()=>Promise.reject(e),X=(e,t)=>{let[n,r,i,a]=t;e(n,r).then(i,a)},xe=e=>{let t=[];return t.push=(...t)=>{for(let n of t)X(e,n);return 0},t},Se=(e,t,n=`window.qinto`)=>{let r=e.ready;if(r!==void 0)return r;let i=e,a=e=>{let t=i.q;i.q=xe(e);for(let n of t)X(e,n)},o=t().then(e=>{a(be(e,n))},e=>{throw a(Y(e)),e});return o.catch(q),i.ready=o,o},Z=_e(),Q=ye(Z),$=`window.${Z}`;if(Q!==null&&Q.ready===void 0){let e=null,t=ie(Q,{onConsentSettled:t=>{e?.settled(t)},onConsentMutation:()=>{e?.clear()},onPageEvent:t=>{e?.settled(t)}});oe(Q),Se(Q,async()=>{let n=Q.config?.destination;if(typeof n!=`string`||n===``)throw Error(`[Qinto] ${$}.config.destination is missing.`);let r=await me({destination:n,globalName:Z,onAppPush:t.push,onSharedContext:t.sharedContext,onAnonId:t=>{e?.observedAnon(t)}});e=F(Q,r.submitCapture,n,Z);let i=await t.connect(r.client);return e.needsAnon()&&e.observedAnon((await r.client.getSession()).anonId),i},$)}})();