1import{v as e}from"./2210eadb.DF0gIp_2.js";const t={production:"https://frontend-event-collector.shopifysvc.com/produce",development:"https://frontend-event-collector-staging.shopifysvc.com/produce",origin:"/.well-known/shopify/fec/produce"};function s(e){const t=e.client?.message;return null==t?"Client message undefined":[`CreatedAt: ${t.createdAt}`,`SentAt: ${t.sentAt}`,`LowId: ${t.id?.lowid}`,`HighId: ${t.id?.highid}`].join(" / ").replace(/ \/ $/,"").trim()}class r{producer;logOptions;static TAG="ProducerMiddleware";constructor(e,t){this.producer=e,this.logOptions=t}do(e,t){return this.logOptions.logger({tags:[r.TAG],message:`Producing ${e.length} events`,metadata:this.logOptions.verbose?{messages:e.map(s)}:void 0}),this.producer.produce(e)}flush(){this.logOptions.logger({tags:[r.TAG],message:"Flushing producer"}),this.producer.flush()}}class o extends Error{cause;constructor(e,t){super(e),this.cause=t,this.name="ProtoError",t instanceof Error?this.stack=t.stack:this.stack=t?new Error(t).stack:(new Error).stack}}class n extends o{cause;constructor(e,t){super(e,t),this.cause=t,this.name="ProtoRequestError"}}class i extends n{phase;details;constructor(e,t,s,r){super(t,r),this.name="ProtoTransportError",this.phase=e,this.details=s}}class a extends o{constructor(e,t,s){super(`[${e}] ${t??"Error message not provided"} (CODE: ${s??-1})`)}}class u extends a{constructor(e,t){super(`Event Result ${e}`,t.error_msg,t.error_code),this.name="ProtoEventResultError"}}class c extends a{status;requestId;constructor(e){super("Batch Result",e.batch_result.error_msg,e.batch_result.error_code),this.name="ProtoResponseError",this.status=e.status,this.requestId=e.requestId;const t=[`Status: ${e.status} ${e.statusText}`,`X-Request-ID: ${e.requestId}`];for(const[s,r]of Object.entries(e.event_results))if("ERROR"===r.state){const e=new u(Number(s),r);t.push(e.message)}this.stack=t.join("\n")}}function d(e){const t=e.client;if(!t)return e;const s=t.message;return s?{...e,client:{...t,message:{...s,sentAt:(new Date).toISOString()}}}:e}function l(e,t){if(!e)throw new Error(t);return e}class h{endpoint;logOptions;options;static TAG="HttpProducer";constructor(e,t,s){this.endpoint=e,this.logOptions=t,this.options=s}async produce(e){if(0===e.length)throw new n("No envelopes to produce");let t,r;try{r=function(e){return e.map(d)}(e),t=function(e){return e.forEach(e=>{const t=l(e.client,"ClientContext is not set"),s=l(t.message,"ClientContext.Message is not set");l(s.sentAt,"ClientContext.Message.sentAt is not set")}),JSON.stringify({events:e})}(r)}catch(y){throw this.transportError("serialize","HttpProducer serialize step failed",{endpoint:this.endpoint},y)}const o="function"==typeof Blob?new Blob([t],{type:"application/json"}):void 0,i=o&&"number"==typeof o.size?o.size:function(e){return"function"==typeof TextEncoder?(new TextEncoder).encode(e).length:e.length}(t);this.logOptions.logger({tags:[h.TAG],message:`Producing ${r.length} envelope(s)`,metadata:this.logOptions.verbose?{envelopes:r}:{messages:r.map(s)}});let a=!1,u=!1,g={};try{if(g=this.options?.headers?.()||{},!(Object.keys(g).length>0)&&o&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon)try{const e=navigator.sendBeacon.bind(navigator);if(a=!0,u=e(this.endpoint,o),u)return this.logOptions.logger({tags:[h.TAG],message:"Successfully produced via sendBeacon"}),{batch_result:{state:"ENQUEUED"},event_results:{},status:200,statusText:"OK",requestId:""}}catch{u="threw"}g["Content-Type"]="application/json"}catch(y){throw this.transportError("serialize","HttpProducer header setup failed",{endpoint:this.endpoint,payloadBytes:i,usedSendBeacon:a,beaconResult:u},y)}const f=i<6e4;let m,v,w;try{m=await fetch(this.endpoint,{method:"POST",headers:g,body:t,keepalive:f,...this.options?.timeout?{signal:AbortSignal.timeout(this.options.timeout)}:{}})}catch(y){if(y instanceof n||y instanceof c)throw y;const e=y,t=function(e,t,s){return function(e){return"AbortError"===e.name||"TimeoutError"===e.name}(e)?"fetch_abort":t?"threw"===s?"beacon_throw_fetch_failed":"beacon_false_fetch_failed":"fetch_throw"}(e,a,u);throw this.transportError(t,"HttpProducer produce call failed",{endpoint:this.endpoint,payloadBytes:i,usedSendBeacon:a,beaconResult:u,keepalive:f},e)}try{v=await m.text()}catch(E){throw this.transportError("response_parse","Failed to read response body",{endpoint:this.endpoint,payloadBytes:i,usedSendBeacon:a,beaconResult:u,keepalive:f,responseStatus:m.status,responseStatusText:m.statusText},E)}try{if(w={...JSON.parse(v),status:m.status,statusText:m.statusText,requestId:m.headers.get("x-request-id")||""},m.ok)return this.logOptions.logger({tags:[h.TAG],message:"Successfully produced via fetch"}),w}catch(E){throw this.transportError("response_parse",`Failed to parse response body: ${v}`,{endpoint:this.endpoint,payloadBytes:i,usedSendBeacon:a,beaconResult:u,keepalive:f,responseStatus:m.status,responseStatusText:m.statusText},E)}if(!function(e){return p(e.batch_result)&&p(e.event_results)}(w))throw this.transportError("response_parse","Failed to parse response body: invali
1d ProtoResponse error body",{endpoint:this.endpoint,payloadBytes:i,usedSendBeacon:a,beaconResult:u,keepalive:f,responseStatus:m.status,responseStatusText:m.statusText},new Error("Invalid ProtoResponse error body"));throw new c(w)}flush(){}transportError(e,t,s,r){const o={...s,causeName:r.name,causeMessage:r.message};return this.logOptions.logger({tags:[h.TAG],message:`Produce failed: ${e} (${r.name}: ${r.message})`,metadata:{phase:e,...o},error:r}),new i(e,t,o,r)}}function p(e){return"object"==typeof e&&null!==e}class g{logOptions;static TAG="LogProducer";constructor(e){this.logOptions=e}async produce(e){return this.logOptions.logger({tags:[g.TAG],message:`Producing ${e.length} envelope(s)`,metadata:this.logOptions.verbose?{envelopes:e}:{messages:e.map(s)}}),function(e=[]){return{batch_result:{state:"ENQUEUED",error_code:0,error_msg:void 0},event_results:Object.fromEntries(e.map((e,t)=>[t.toString(),{state:"ENQUEUED",error_code:0,error_msg:void 0}])),status:200,statusText:"OK",requestId:""}}(e)}flush(){}}class f{middleware;logOptions;static identityFn;static TAG="ProtoProducer";static createLogProducer({middleware:e,logOptions:t}){return new f(new g(t),e||[],t)}static createHttpProducer({endpoint:e,middleware:s,httpOptions:r,logOptions:o}){return new f(new h(t[e],o,r),s||[],o)}static buildMiddlewareChain(e,t=0){return t===e.length?f.identityFn:s=>e[t].do(s,this.buildMiddlewareChain(e,t+1))}static buildMiddlewareFlushChainFn(e,t=0){return t===e.length?()=>{}:()=>{e[t].flush(),this.buildMiddlewareFlushChainFn(e,t+1)()}}executeChain;executeFlushChain;constructor(e,t,s){this.middleware=t,this.logOptions=s;const o=new r(e,s);this.executeChain=f.buildMiddlewareChain(this.middleware.concat(o)),this.executeFlushChain=f.buildMiddlewareFlushChainFn(this.middleware.concat(o))}produce(e){return this.logOptions.logger({tags:[f.TAG],message:"Producing events",metadata:{eventCount:e.length,messages:e.map(s)}}),this.executeChain(e)}flush(){this.logOptions.logger({tags:[f.TAG],message:"Flushing producer"}),this.executeFlushChain()}}class m{protoProducer;constructor({endpoint:e="development",producer:t="http",logOptions:s={verbose:!1,logger:()=>{}},middleware:r=[],httpOptions:o={timeout:void 0,headers:void 0}}={}){const n={endpoint:e,producer:t,logOptions:{verbose:s?.verbose??!1,logger:({tags:e,message:t,metadata:r,error:o})=>{s?.logger({tags:["proto-ts",...e],message:t,metadata:r,error:o})}},middleware:r,httpOptions:o};if("http"===n.producer)this.protoProducer=f.createHttpProducer({endpoint:n.endpoint,middleware:n.middleware,httpOptions:n.httpOptions,logOptions:n.logOptions});else{if("log"!==n.producer)throw new Error(`Invalid producer: ${n.producer}`);this.protoProducer=f.createLogProducer({middleware:n.middleware,logOptions:n.logOptions})}}get producer(){return this.protoProducer}async produceEvents(e){return this.protoProducer.produce(e)}async produceEvent(e){return this.produceEvents([e])}flush(){this.protoProducer.flush()}}class v extends Error{constructor(e){super(e),this.name="BatchEventQueueError"}}class w{queue;_promise;_resolve;_reject;_nextMiddleware;flushed=!1;constructor(e){this.queue=[],this._nextMiddleware=e,this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}add(e){if(this.flushed)throw new v("Queue already flushed");this.queue.push(...e)}flush(){this.flushed||(this._nextMiddleware(this.queue).then(this._resolve).catch(this._reject),this.flushed=!0)}get promise(){return this._promise}get length(){return this.queue.length}}class y{static TAG="BatchMiddleware";state={type:"initial"};scheduleFlush;maxQueueSize;logger;shouldSkipBatching;constructor(e){const t=e?.debounceCoolOffMs??500,s=e?.maxWaitTimeMs??2e3;this.maxQueueSize=e?.maxQueueSize??20,this.logger=e?.logger??(()=>{}),this.shouldSkipBatching=e?.shouldSkipBatching,this.scheduleFlush=function(e,t,s){const r=s?.leading??!1,o=s?.trailing??!0,n=s?.maxWait,i=void 0!==n,a=i?Math.max(n,t):0;let u,c,d,l,h=0;function p(t){const s=d;return d=void 0,h=t,l=e.apply(s?.context,s?.args),l}function g(e,t){u=setTimeout(e,t)}function f(){void 0!==u&&(clearTimeout(u),u=void 0)}function m(e){const s=void 0===c?void 0:e-c;return void 0===s||s>=t||s<0||i&&e-h>=a}function v(e){return u=void 0,o&&void 0!==d?p(e):(d=void 0,l)}function w(){const e=Date.now();m(e)?v(e):g(w,function(e){const s=e-h,r=t-(e-(c??0));return i?Math.min(r,a-s):r}(e))}function y(...e){const s=Date.now(),o=m(s);if(d={args:e,context:this},c=s,o){if(void 0===u)return function(e){return h=e,g(w,t),r?p(e):l}(s);if(i)return f(),g(w,t),p(s)}return void 0===u&&g(w,t),l}
1return y.cancel=function(){f(),h=0,d=void 0,c=void 0},y.flush=function(){return void 0===u?l:v(Date.now())},y.pending=function(){return void 0!==u},y}(()=>{"open"===this.state.type&&this.flushCurrentQueue()},t,{maxWait:s})}do(e,t){if(this.shouldSkipBatchingForAny(e))return this.logger({tags:[y.TAG],message:"Skipping batch queue",metadata:{eventCount:e.length}}),t(e);const s=this.getOrCreateQueue(t);return this.logger({tags:[y.TAG],message:"Adding events to queue",metadata:{state:this.state.type,queueSize:s.length,eventCount:e.length}}),s.add(e),s.length>=this.maxQueueSize?(this.scheduleFlush.cancel(),this.flushCurrentQueue()):this.scheduleFlush(),s.promise}flush(){this.logger({tags:[y.TAG],message:"Flushing queue",metadata:{state:this.state.type,queueSize:"open"===this.state.type?this.state.queue.length:void 0}}),"open"===this.state.type&&(this.scheduleFlush.cancel(),this.flushCurrentQueue())}shouldSkipBatchingForAny(e){return e.some(e=>!0===this.shouldSkipBatching?.(e))}getOrCreateQueue(e){if("initial"===this.state.type)return this.createQueue(e);const t=this.state.queue;return t.flushed?this.createQueue(e):t}createQueue(e){const t=new w(e);return this.state={type:"open",queue:t},t}flushCurrentQueue(){if("open"===this.state.type){const e=this.state.queue;this.logger({tags:[y.TAG],message:"Flushing current queue",metadata:{queueSize:e.length}}),e.flush(),this.state={type:"initial"}}}}var E,b;(b=E||(E={})).EventTypeIdentifier="@type",b.createEnvelope=function(e,t){const s={...t};return delete s[b.EventTypeIdentifier],{...e,timestamp:void 0,payload:{...s,[b.EventTypeIdentifier]:`type.googleapis.com/${t[b.EventTypeIdentifier]}`}}};const O={v4:()=>e(),parse:e=>{const t=e.replace(/-/g,"");return Array.from({length:16},(e,s)=>parseInt(t.slice(2*s,2*s+2),16))}},x=new class{uuidProvider;constructor(e){this.uuidProvider=e}createGlobalId(e){if("number"==typeof e&&this.isUint64(e.toString()))return{lowid:e.toString(),highid:void 0};if("string"==typeof e){if(this.isUint64(e))return{lowid:e,highid:void 0};if(this.isUuid(e))return this.convertUuidToGlobalId(e)}}isUint64(e){if(!/^\d+$/.test(e))return!1;const t=BigInt(0),s=BigInt("18446744073709551615"),r=BigInt(e);return r>=t&&r<=s}isUuid(e){return/^(?:[a-f0-9]{32}|[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/i.test(e.trim())}convertUuidToGlobalId(e){const t=e?.trim();if(!t)return;const s=this.uuidProvider.parse(t),r=new Uint8Array(s);let o=BigInt(0);for(let i=0;i<8;i++)o=o<<BigInt(8)|BigInt(r[i]);let n=BigInt(0);for(let i=8;i<16;i++)n=n<<BigInt(8)|BigInt(r[i]);return{lowid:n.toString(),highid:o.toString()}}}(O);class T extends Error{constructor(){super(...arguments),this.name="MessageIdMintError"}}function S(){const e=x.createGlobalId(O.v4());if(!e)throw new T("ProtoGlobalIdProvider failed to mint a message id");return e}class _{#e=[];async get(){return this.#e}async set(e){this.#e=e}async clear(){this.#e=[]}}function P(){const e=new m({endpoint:"origin",middleware:[new y({storage:new _,logger:({tags:e,message:t})=>{}})]});return{proto:E,client:e,createMessageId:S,flush(){e.flush()}}}export{P as createProtoHub};
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.