@spiffcommerce/core 44.8.1-alpha.0 → 44.9.0
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.
- package/dist/{index-CGmMgNeJ.cjs → index-CPGnAXAs.cjs} +3 -3
- package/dist/{index-CGmMgNeJ.cjs.map → index-CPGnAXAs.cjs.map} +1 -1
- package/dist/{index-Bh9-t6cC.js → index-DUDcj0N-.js} +4 -4
- package/dist/{index-Bh9-t6cC.js.map → index-DUDcj0N-.js.map} +1 -1
- package/dist/{index.browser-DpspqM1v.cjs → index.browser-C2H4mjal.cjs} +2 -2
- package/dist/{index.browser-DpspqM1v.cjs.map → index.browser-C2H4mjal.cjs.map} +1 -1
- package/dist/{index.browser-BN--zW20.js → index.browser-CYEmJE69.js} +2 -2
- package/dist/{index.browser-BN--zW20.js.map → index.browser-CYEmJE69.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
|
@@ -3105,7 +3105,7 @@ Minimum version required to store current data is: `+U+`.
|
|
|
3105
3105
|
`;class ZV{constructor(e,t=Le.getShadowGraphqlClient.bind(Le)){this.options=e,this.client=t}query(e){const t=this.options?.onQuery?this.options?.onQuery(e):{};return this.client().query({...t,...e,context:{...t.context??{},...e.context??{}}})}mutate(e){const t=this.options?.onMutate?this.options?.onMutate(e):{};return this.client().mutate({...t,...e,context:{...t.context??{},...e.context??{}}})}}function e$(r,e,t){return r.$source||(r.$source={}),r.$source[e]=t,r}const t$=r=>r?.body instanceof ReadableStream,ml=(r,e)=>{const t=[];if(r&&t.push(r),e)for(const n of e)t.push(n);return t},no=(r,e)=>`${r||"anonymous"}${e&&e.length>0?` (a.k.a. ${e.join(",")})`:""}`,kg=()=>{let r=[],e=[],t=!1;const n=new Set,i=f=>f.sort((d,h)=>GE[h.step]-GE[d.step]||jE[h.priority||"normal"]-jE[d.priority||"normal"]),a=f=>{let d=!1;const h=g=>{const y=ml(g.name,g.aliases);if(y.includes(f)){d=!0;for(const v of y)n.delete(v);return!1}return!0};return r=r.filter(h),e=e.filter(h),d},s=f=>{let d=!1;const h=g=>{if(g.middleware===f){d=!0;for(const y of ml(g.name,g.aliases))n.delete(y);return!1}return!0};return r=r.filter(h),e=e.filter(h),d},o=f=>(r.forEach(d=>{f.add(d.middleware,{...d})}),e.forEach(d=>{f.addRelativeTo(d.middleware,{...d})}),f.identifyOnResolve?.(c.identifyOnResolve()),f),l=f=>{const d=[];return f.before.forEach(h=>{h.before.length===0&&h.after.length===0?d.push(h):d.push(...l(h))}),d.push(f),f.after.reverse().forEach(h=>{h.before.length===0&&h.after.length===0?d.push(h):d.push(...l(h))}),d},u=(f=!1)=>{const d=[],h=[],g={};return r.forEach(v=>{const A={...v,before:[],after:[]};for(const x of ml(A.name,A.aliases))g[x]=A;d.push(A)}),e.forEach(v=>{const A={...v,before:[],after:[]};for(const x of ml(A.name,A.aliases))g[x]=A;h.push(A)}),h.forEach(v=>{if(v.toMiddleware){const A=g[v.toMiddleware];if(A===void 0){if(f)return;throw new Error(`${v.toMiddleware} is not found when adding ${no(v.name,v.aliases)} middleware ${v.relation} ${v.toMiddleware}`)}v.relation==="after"&&A.after.push(v),v.relation==="before"&&A.before.push(v)}}),i(d).map(l).reduce((v,A)=>(v.push(...A),v),[])},c={add:(f,d={})=>{const{name:h,override:g,aliases:y}=d,v={step:"initialize",priority:"normal",middleware:f,...d},A=ml(h,y);if(A.length>0){if(A.some(x=>n.has(x))){if(!g)throw new Error(`Duplicate middleware name '${no(h,y)}'`);for(const x of A){const S=r.findIndex(E=>E.name===x||E.aliases?.some(R=>R===x));if(S===-1)continue;const F=r[S];if(F.step!==v.step||v.priority!==F.priority)throw new Error(`"${no(F.name,F.aliases)}" middleware with ${F.priority} priority in ${F.step} step cannot be overridden by "${no(h,y)}" middleware with ${v.priority} priority in ${v.step} step.`);r.splice(S,1)}}for(const x of A)n.add(x)}r.push(v)},addRelativeTo:(f,d)=>{const{name:h,override:g,aliases:y}=d,v={middleware:f,...d},A=ml(h,y);if(A.length>0){if(A.some(x=>n.has(x))){if(!g)throw new Error(`Duplicate middleware name '${no(h,y)}'`);for(const x of A){const S=e.findIndex(E=>E.name===x||E.aliases?.some(R=>R===x));if(S===-1)continue;const F=e[S];if(F.toMiddleware!==v.toMiddleware||F.relation!==v.relation)throw new Error(`"${no(F.name,F.aliases)}" middleware ${F.relation} "${F.toMiddleware}" middleware cannot be overridden by "${no(h,y)}" middleware ${v.relation} "${v.toMiddleware}" middleware.`);e.splice(S,1)}}for(const x of A)n.add(x)}e.push(v)},clone:()=>o(kg()),use:f=>{f.applyToStack(c)},remove:f=>typeof f=="string"?a(f):s(f),removeByTag:f=>{let d=!1;const h=g=>{const{tags:y,name:v,aliases:A}=g;if(y&&y.includes(f)){const x=ml(v,A);for(const S of x)n.delete(S);return d=!0,!1}return!0};return r=r.filter(h),e=e.filter(h),d},concat:f=>{const d=o(kg());return d.use(f),d.identifyOnResolve(t||d.identifyOnResolve()||(f.identifyOnResolve?.()??!1)),d},applyToStack:o,identify:()=>u(!0).map(f=>{const d=f.step??f.relation+" "+f.toMiddleware;return no(f.name,f.aliases)+" - "+d}),identifyOnResolve(f){return typeof f=="boolean"&&(t=f),t},resolve:(f,d)=>{for(const h of u().map(g=>g.middleware).reverse())f=h(f,d);return t&&console.log(c.identify()),f}};return c},GE={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},jE={high:3,normal:2,low:1};var Tf;(function(r){r.HTTP="http",r.HTTPS="https"})(Tf||(Tf={}));var Ff;(function(r){r.MD5="md5",r.CRC32="crc32",r.CRC32C="crc32c",r.SHA1="sha1",r.SHA256="sha256"})(Ff||(Ff={}));const kA="__smithy_context",Ac=r=>r[kA]||(r[kA]={});class aa{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(e){this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?e.protocol.slice(-1)!==":"?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?e.path.charAt(0)!=="/"?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){const t=new aa({...e,headers:{...e.headers}});return t.query&&(t.query=r$(t.query)),t}static isInstance(e){if(!e)return!1;const t=e;return"method"in t&&"protocol"in t&&"hostname"in t&&"path"in t&&typeof t.query=="object"&&typeof t.headers=="object"}clone(){return aa.clone(this)}}function r$(r){return Object.keys(r).reduce((e,t)=>{const n=r[t];return{...e,[t]:Array.isArray(n)?[...n]:n}},{})}class oc{statusCode;reason;headers;body;constructor(e){this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){if(!e)return!1;const t=e;return typeof t.statusCode=="number"&&typeof t.headers=="object"}}const n$=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),nm=(r,e=!1)=>{if(!e)return n$.test(r);const t=r.split(".");for(const n of t)if(!nm(n))return!1;return!0},_s=r=>{if(typeof r=="function")return r;const e=Promise.resolve(r);return()=>e};function i$(r){const e={};if(r=r.replace(/^\?/,""),r)for(const t of r.split("&")){let[n,i=null]=t.split("=");n=decodeURIComponent(n),i&&(i=decodeURIComponent(i)),n in e?Array.isArray(e[n])?e[n].push(i):e[n]=[e[n],i]:e[n]=i}return e}const Tg=r=>{if(typeof r=="string")return Tg(new URL(r));const{hostname:e,pathname:t,port:n,protocol:i,search:a}=r;let s;return a&&(s=i$(a)),{hostname:e,port:n?parseInt(n):void 0,protocol:i,path:t,query:s}},J1=r=>{if(typeof r=="object"){if("url"in r){const e=Tg(r.url);if(r.headers){e.headers={};for(const t in r.headers)e.headers[t.toLowerCase()]=r.headers[t].join(", ")}return e}return r}return Tg(r)},a$=r=>()=>Promise.reject(r);class s${config;middlewareStack=kg();initConfig;handlers;constructor(e){this.config=e;const{protocol:t,protocolSettings:n}=e;n&&typeof t=="function"&&(e.protocol=new t(n))}send(e,t,n){const i=typeof t!="function"?t:void 0,a=typeof t=="function"?t:n,s=i===void 0&&this.config.cacheMiddleware===!0;let o;if(s){this.handlers||(this.handlers=new WeakMap);const l=this.handlers;l.has(e.constructor)?o=l.get(e.constructor):(o=e.resolveMiddleware(this.middlewareStack,this.config,i),l.set(e.constructor,o))}else delete this.handlers,o=e.resolveMiddleware(this.middlewareStack,this.config,i);if(a)o(e).then(l=>a(null,l.output),l=>a(l)).catch(()=>{});else return o(e).then(l=>l.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}const rg=r=>typeof r=="function"?r():r,sP=(r,e,t,n,i)=>({name:e,namespace:r,traits:t,input:n,output:i}),o$=r=>(e,t)=>async n=>{const{response:i}=await e(n),{operationSchema:a}=Ac(t),[,s,o,l,u,c]=a??[];try{const f=await r.protocol.deserializeResponse(sP(s,o,l,u,c),{...r,...t},i);return{response:i,output:f}}catch(f){if(Object.defineProperty(f,"$response",{value:i,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in f)){const d="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{f.message+=`
|
|
3106
3106
|
`+d}catch{!t.logger||t.logger?.constructor?.name==="NoOpLogger"?console.warn(d):t.logger?.warn?.(d)}typeof f.$responseBodyText<"u"&&f.$response&&(f.$response.body=f.$responseBodyText);try{if(oc.isInstance(i)){const{headers:h={},statusCode:g}=i,y=Object.entries(h);f.$metadata={httpStatusCode:g,requestId:Uy(/^x-[\w-]+-request-?id$/,y),extendedRequestId:Uy(/^x-[\w-]+-id-2$/,y),cfId:Uy(/^x-[\w-]+-cf-id$/,y)}}}catch{}}throw f}},Uy=(r,e)=>(e.find(([t])=>t.match(r))||[void 0,void 0])[1],l$=r=>(e,t)=>async n=>{const{operationSchema:i}=Ac(t),[,a,s,o,l,u]=i??[],c=t.endpointV2?async()=>J1(t.endpointV2):r.endpoint,f=await r.protocol.serializeRequest(sP(a,s,o,l,u),n.input,{...r,...t,endpoint:c});return e({...n,request:f})},u$={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},c$={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function d$(r){return{applyToStack:e=>{e.add(l$(r),c$),e.add(o$(r),u$),r.protocol.setSerdeContext(r)}}}const Vy=[];function jd(r){if(typeof r=="object")return r;if(r=r|0,Vy[r])return Vy[r];const e={};let t=0;for(const n of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])(r>>t++&1)===1&&(e[n]=1);return Vy[r]=e}const Fd={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},$y=[],zy={};class yi{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=yi.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(e,t){this.ref=e,this.memberName=t;const n=[];let i=e,a=e;for(this._isMemberSchema=!1;Hy(i);)n.push(i[1]),i=i[0],a=rg(i),this._isMemberSchema=!0;if(n.length>0){this.memberTraits={};for(let s=n.length-1;s>=0;--s){const o=n[s];Object.assign(this.memberTraits,jd(o))}}else this.memberTraits=0;if(a instanceof yi){const s=this.memberTraits;Object.assign(this,a),this.memberTraits=Object.assign({},s,a.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=t??a.memberName;return}if(this.schema=rg(a),f$(this.schema)?(this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3]):(this.name=this.memberName??String(a),this.traits=0),this._isMemberSchema&&!t)throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](e){const t=this.prototype.isPrototypeOf(e);return!t&&typeof e=="object"&&e!==null?e.symbol===this.symbol:t}static of(e){const t=typeof e=="function"||typeof e=="object"&&e!==null;if(typeof e=="number"){if($y[e])return $y[e]}else if(typeof e=="string"){if(zy[e])return zy[e]}else if(t&&e[Fd.ns])return e[Fd.ns];const n=rg(e);if(n instanceof yi)return n;if(Hy(n)){const[a,s]=n;if(a instanceof yi)return Object.assign(a.getMergedTraits(),jd(s)),a;throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(e,null,2)}.`)}const i=new yi(n);return t?e[Fd.ns]=i:typeof n=="string"?zy[n]=i:typeof n=="number"?$y[n]=i:i}getSchema(){const e=this.schema;return Array.isArray(e)&&e[0]===0?e[4]:e}getName(e=!1){const{name:t}=this;return!e&&t&&t.includes("#")?t.split("#")[1]:t||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){const e=this.getSchema();return typeof e=="number"?e>=64&&e<128:e[0]===1}isMapSchema(){const e=this.getSchema();return typeof e=="number"?e>=128&&e<=255:e[0]===2}isStructSchema(){const e=this.getSchema();if(typeof e!="object")return!1;const t=e[0];return t===3||t===-3||t===4}isUnionSchema(){const e=this.getSchema();return typeof e!="object"?!1:e[0]===4}isBlobSchema(){const e=this.getSchema();return e===21||e===42}isTimestampSchema(){const e=this.getSchema();return typeof e=="number"&&e>=4&&e<=7}isUnitSchema(){return this.getSchema()==="unit"}isDocumentSchema(){return this.getSchema()===15}isStringSchema(){return this.getSchema()===0}isBooleanSchema(){return this.getSchema()===2}isNumericSchema(){return this.getSchema()===1}isBigIntegerSchema(){return this.getSchema()===17}isBigDecimalSchema(){return this.getSchema()===19}isStreaming(){const{streaming:e}=this.getMergedTraits();return!!e||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return jd(this.memberTraits)}getOwnTraits(){return jd(this.traits)}getKeySchema(){const[e,t]=[this.isDocumentSchema(),this.isMapSchema()];if(!e&&!t)throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);const n=this.getSchema(),i=e?15:n[4]??0;return Id([i,0],"key")}getValueSchema(){const e=this.getSchema(),[t,n,i]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],a=typeof e=="number"?63&e:e&&typeof e=="object"&&(n||i)?e[3+e[0]]:t?15:void 0;if(a!=null)return Id([a,0],n?"value":"member");throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(e){const t=this.getSchema();if(this.isStructSchema()&&t[4].includes(e)){const n=t[4].indexOf(e),i=t[5][n];return Id(Hy(i)?i:[i,0],e)}if(this.isDocumentSchema())return Id([15,0],e);throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${e}.`)}getMemberSchemas(){const e={};try{for(const[t,n]of this.structIterator())e[t]=n}catch{}return e}getEventStreamMember(){if(this.isStructSchema()){for(const[e,t]of this.structIterator())if(t.isStreaming()&&t.isStructSchema())return e}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw new Error("@smithy/core/schema - cannot iterate non-struct schema.");const e=this.getSchema(),t=e[4].length;let n=e[Fd.it];if(n&&t===n.length){yield*n;return}n=Array(t);for(let i=0;i<t;++i){const a=e[4][i],s=Id([e[5][i],0],a);yield n[i]=[a,s]}e[Fd.it]=n}}function Id(r,e){if(r instanceof yi)return Object.assign(r,{memberName:e,_isMemberSchema:!0});const t=yi;return new t(r,e)}const Hy=r=>Array.isArray(r)&&r.length===2,f$=r=>Array.isArray(r)&&r.length>=5;class ta{namespace;schemas;exceptions;static registries=new Map;constructor(e,t=new Map,n=new Map){this.namespace=e,this.schemas=t,this.exceptions=n}static for(e){return ta.registries.has(e)||ta.registries.set(e,new ta(e)),ta.registries.get(e)}copyFrom(e){const{schemas:t,exceptions:n}=this;for(const[i,a]of e.schemas)t.has(i)||t.set(i,a);for(const[i,a]of e.exceptions)n.has(i)||n.set(i,a)}register(e,t){const n=this.normalizeShapeId(e);for(const i of[this,ta.for(n.split("#")[0])])i.schemas.set(n,t)}getSchema(e){const t=this.normalizeShapeId(e);if(!this.schemas.has(t)){if(!e.includes("#")){const n="#"+e,i=[];for(const[a,s]of this.schemas.entries())a.endsWith(n)&&i.push(s);if(i.length===1)return i[0]}throw new Error(`@smithy/core/schema - schema not found for ${t}`)}return this.schemas.get(t)}registerError(e,t){const n=e,i=n[1];for(const a of[this,ta.for(i)])a.schemas.set(i+"#"+n[2],n),a.exceptions.set(n,t)}getErrorCtor(e){const t=e;return this.exceptions.has(t)?this.exceptions.get(t):ta.for(t[1]).exceptions.get(t)}getBaseException(){for(const e of this.exceptions.keys())if(Array.isArray(e)){const[,t,n]=e,i=t+"#"+n;if(i.startsWith("smithy.ts.sdk.synthetic.")&&i.endsWith("ServiceException"))return e}}find(e){for(const t of this.schemas.values())if(e(t))return t}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(e){return e.includes("#")?e:this.namespace+"#"+e}}const Gy="***SensitiveInformation***";function TA(r,e){if(e==null)return e;const t=yi.of(r);if(t.getMergedTraits().sensitive)return Gy;if(t.isListSchema()){if(!!t.getValueSchema().getMergedTraits().sensitive)return Gy}else if(t.isMapSchema()){if(!!t.getKeySchema().getMergedTraits().sensitive||!!t.getValueSchema().getMergedTraits().sensitive)return Gy}else if(t.isStructSchema()&&typeof e=="object"){const n=e,i={};for(const[a,s]of t.structIterator())n[a]!=null&&(i[a]=TA(s,n[a]));return i}return e}class K1{middlewareStack=kg();schema;static classBuilder(){return new h$}resolveMiddlewareWithContext(e,t,n,{middlewareFn:i,clientName:a,commandName:s,inputFilterSensitiveLog:o,outputFilterSensitiveLog:l,smithyContext:u,additionalContext:c,CommandCtor:f}){for(const A of i.bind(this)(f,e,t,n))this.middlewareStack.use(A);const d=e.concat(this.middlewareStack),{logger:h}=t,g={logger:h,clientName:a,commandName:s,inputFilterSensitiveLog:o,outputFilterSensitiveLog:l,[kA]:{commandInstance:this,...u},...c},{requestHandler:y}=t;let v=n??{};return u.eventStream&&(v={isEventStream:!0,...v}),d.resolve(A=>y.handle(A.request,v),g)}}class h${_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,t,n={}){return this._smithyContext={service:e,operation:t,...n},this}c(e={}){return this._additionalContext=e,this}n(e,t){return this._clientName=e,this._commandName=t,this}f(e=n=>n,t=n=>n){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=t,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}sc(e){return this._operationSchema=e,this._smithyContext.operationSchema=e,this}build(){const e=this;let t;return t=class extends K1{input;static getEndpointParameterInstructions(){return e._ep}constructor(...[n]){super(),this.input=n??{},e._init(this),this.schema=e._operationSchema}resolveMiddleware(n,i,a){const s=e._operationSchema,o=s?.[4]??s?.input,l=s?.[5]??s?.output;return this.resolveMiddlewareWithContext(n,i,a,{CommandCtor:t,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog??(s?TA.bind(null,o):u=>u),outputFilterSensitiveLog:e._outputFilterSensitiveLog??(s?TA.bind(null,l):u=>u),smithyContext:e._smithyContext,additionalContext:e._additionalContext})}serialize=e._serializer;deserialize=e._deserializer}}}class $u extends Error{$fault;$response;$retryable;$metadata;constructor(e){super(e.message),Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}static isInstance(e){if(!e)return!1;const t=e;return $u.prototype.isPrototypeOf(t)||!!t.$fault&&!!t.$metadata&&(t.$fault==="client"||t.$fault==="server")}static[Symbol.hasInstance](e){if(!e)return!1;const t=e;return this===$u?$u.isInstance(e):$u.isInstance(e)?t.name&&this.name?this.prototype.isPrototypeOf(e)||t.name===this.name:this.prototype.isPrototypeOf(e):!1}}const qE=(r,e={})=>{Object.entries(e).filter(([,n])=>n!==void 0).forEach(([n,i])=>{(r[n]==null||r[n]==="")&&(r[n]=i)});const t=r.message||r.Message||"UnknownError";return r.message=t,delete r.Message,r},p$=r=>{switch(r){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}},oP=Object.values(Ff),g$=r=>{const e=[];for(const t in Ff){const n=Ff[t];r[n]!==void 0&&e.push({algorithmId:()=>n,checksumConstructor:()=>r[n]})}for(const[t,n]of Object.entries(r.checksumAlgorithms??{}))e.push({algorithmId:()=>t,checksumConstructor:()=>n});return{addChecksumAlgorithm(t){r.checksumAlgorithms=r.checksumAlgorithms??{};const n=t.algorithmId(),i=t.checksumConstructor();oP.includes(n)?r.checksumAlgorithms[n.toUpperCase()]=i:r.checksumAlgorithms[n]=i,e.push(t)},checksumAlgorithms(){return e}}},m$=r=>{const e={};return r.checksumAlgorithms().forEach(t=>{const n=t.algorithmId();oP.includes(n)&&(e[n]=t.checksumConstructor())}),e},y$=r=>({setRetryStrategy(e){r.retryStrategy=e},retryStrategy(){return r.retryStrategy}}),v$=r=>{const e={};return e.retryStrategy=r.retryStrategy(),e},A$=r=>Object.assign(g$(r),y$(r)),b$=r=>Object.assign(m$(r),v$(r));class lP{trace(){}debug(){}info(){}warn(){}error(){}}const uP="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",WE=Object.entries(uP).reduce((r,[e,t])=>(r[t]=Number(e),r),{}),w$=uP.split(""),Qu=6,rf=8,x$=63,im=r=>{let e=r.length/4*3;r.slice(-2)==="=="?e-=2:r.slice(-1)==="="&&e--;const t=new ArrayBuffer(e),n=new DataView(t);for(let i=0;i<r.length;i+=4){let a=0,s=0;for(let u=i,c=i+3;u<=c;u++)if(r[u]!=="="){if(!(r[u]in WE))throw new TypeError(`Invalid character ${r[u]} in base64 string.`);a|=WE[r[u]]<<(c-u)*Qu,s+=Qu}else a>>=Qu;const o=i/4*3;a>>=s%rf;const l=Math.floor(s/rf);for(let u=0;u<l;u++){const c=(l-u-1)*rf;n.setUint8(o+u,(a&255<<c)>>c)}}return new Uint8Array(t)},Pl=r=>new TextEncoder().encode(r);function Fg(r){let e;typeof r=="string"?e=Pl(r):e=r;const t=typeof e=="object"&&typeof e.length=="number",n=typeof e=="object"&&typeof e.byteOffset=="number"&&typeof e.byteLength=="number";if(!t&&!n)throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let i="";for(let a=0;a<e.length;a+=3){let s=0,o=0;for(let u=a,c=Math.min(a+3,e.length);u<c;u++)s|=e[u]<<(c-u-1)*rf,o+=rf;const l=Math.ceil(o/Qu);s<<=l*Qu-o;for(let u=1;u<=l;u++){const c=(l-u)*Qu;i+=w$[(s&x$<<c)>>c]}i+="==".slice(0,4-l)}return i}function C$(r,e,t,n){return class ng extends Uint8Array{static fromString(a,s="utf-8"){if(typeof a=="string")return s==="base64"?ng.mutate(n(a)):ng.mutate(e(a));throw new Error(`Unsupported conversion from ${typeof a} to Uint8ArrayBlobAdapter.`)}static mutate(a){return Object.setPrototypeOf(a,ng.prototype),a}transformToString(a="utf-8"){return a==="base64"?t(this):r(this)}}}const am=r=>{if(typeof r=="string")return r;if(typeof r!="object"||typeof r.byteOffset!="number"||typeof r.byteLength!="number")throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(r)},Pi=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function S$(r){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?()=>crypto.randomUUID():()=>{const e=new Uint8Array(16);return r(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128,Pi[e[0]]+Pi[e[1]]+Pi[e[2]]+Pi[e[3]]+"-"+Pi[e[4]]+Pi[e[5]]+"-"+Pi[e[6]]+Pi[e[7]]+"-"+Pi[e[8]]+Pi[e[9]]+"-"+Pi[e[10]]+Pi[e[11]]+Pi[e[12]]+Pi[e[13]]+Pi[e[14]]+Pi[e[15]]}}const FA=r=>{if(r!=null){if(typeof r=="string"){const e=parseFloat(r);if(!Number.isNaN(e))return String(e)!==String(r)&&O$.warn(R$(`Expected number but observed string: ${r}`)),e}if(typeof r=="number")return r;throw new TypeError(`Expected number, got ${typeof r}: ${r}`)}},E$=Math.ceil(2**127*(2-2**-23)),QE=r=>{const e=FA(r);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>E$)throw new TypeError(`Expected 32-bit float, got ${r}`);return e},k$=r=>{if(r!=null){if(Number.isInteger(r)&&!Number.isNaN(r))return r;throw new TypeError(`Expected integer, got ${typeof r}: ${r}`)}},YE=r=>cP(r,16),XE=r=>cP(r,8),cP=(r,e)=>{const t=k$(r);if(t!==void 0&&T$(t,e)!==t)throw new TypeError(`Expected ${e}-bit integer, got ${r}`);return t},T$=(r,e)=>{switch(e){case 32:return Int32Array.of(r)[0];case 16:return Int16Array.of(r)[0];case 8:return Int8Array.of(r)[0]}},F$=r=>FA(typeof r=="string"?sm(r):r),I$=r=>QE(typeof r=="string"?sm(r):r),P$=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,sm=r=>{const e=r.match(P$);if(e===null||e[0].length!==r.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(r)},Ig=r=>YE(typeof r=="string"?sm(r):r),D$=r=>XE(typeof r=="string"?sm(r):r),R$=r=>String(new TypeError(r).stack||r).split(`
|
|
3107
3107
|
`).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
|
|
3108
|
-
`),O$={warn:console.warn},B$=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Z1=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function M$(r){const e=r.getUTCFullYear(),t=r.getUTCMonth(),n=r.getUTCDay(),i=r.getUTCDate(),a=r.getUTCHours(),s=r.getUTCMinutes(),o=r.getUTCSeconds(),l=i<10?`0${i}`:`${i}`,u=a<10?`0${a}`:`${a}`,c=s<10?`0${s}`:`${s}`,f=o<10?`0${o}`:`${o}`;return`${B$[n]}, ${l} ${Z1[t]} ${e} ${u}:${c}:${f} GMT`}const _$=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),N$=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");const e=_$.exec(r);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");const[t,n,i,a,s,o,l,u,c]=e,f=Ig(If(n)),d=wo(i,"month",1,12),h=wo(a,"day",1,31),g=ig(f,d,h,{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u});return c.toUpperCase()!="Z"&&g.setTime(g.getTime()-Y$(c)),g},L$=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),U$=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),V$=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),dP=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=L$.exec(r);if(e){const[t,n,i,a,s,o,l,u]=e;return ig(Ig(If(a)),jy(i),wo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u})}if(e=U$.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return G$(ig(z$(a),jy(i),wo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u}))}if(e=V$.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return ig(Ig(If(u)),jy(n),wo(i.trimLeft(),"day",1,31),{hours:a,minutes:s,seconds:o,fractionalMilliseconds:l})}throw new TypeError("Invalid RFC-7231 date-time value")},$$=r=>{if(r==null)return;let e;if(typeof r=="number")e=r;else if(typeof r=="string")e=F$(r);else if(typeof r=="object"&&r.tag===1)e=r.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(e)||e===1/0||e===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(e*1e3))},ig=(r,e,t,n)=>{const i=e-1;return q$(r,i,t),new Date(Date.UTC(r,i,t,wo(n.hours,"hour",0,23),wo(n.minutes,"minute",0,59),wo(n.seconds,"seconds",0,60),Q$(n.fractionalMilliseconds)))},z$=r=>{const e=new Date().getUTCFullYear(),t=Math.floor(e/100)*100+Ig(If(r));return t<e?t+100:t},H$=50*365*24*60*60*1e3,G$=r=>r.getTime()-new Date().getTime()>H$?new Date(Date.UTC(r.getUTCFullYear()-100,r.getUTCMonth(),r.getUTCDate(),r.getUTCHours(),r.getUTCMinutes(),r.getUTCSeconds(),r.getUTCMilliseconds())):r,jy=r=>{const e=Z1.indexOf(r);if(e<0)throw new TypeError(`Invalid month: ${r}`);return e+1},j$=[31,28,31,30,31,30,31,31,30,31,30,31],q$=(r,e,t)=>{let n=j$[e];if(e===1&&W$(r)&&(n=29),t>n)throw new TypeError(`Invalid day for ${Z1[e]} in ${r}: ${t}`)},W$=r=>r%4===0&&(r%100!==0||r%400===0),wo=(r,e,t,n)=>{const i=D$(If(r));if(i<t||i>n)throw new TypeError(`${e} must be between ${t} and ${n}, inclusive`);return i},Q$=r=>r==null?0:I$("0."+r)*1e3,Y$=r=>{const e=r[0];let t=1;if(e=="+")t=1;else if(e=="-")t=-1;else throw new TypeError(`Offset direction, ${e}, must be "+" or "-"`);const n=Number(r.substring(1,3)),i=Number(r.substring(4,6));return t*(n*60+i)*60*1e3},If=r=>{let e=0;for(;e<r.length-1&&r.charAt(e)==="0";)e++;return e===0?r:r.slice(e)},yo=function(e){return Object.assign(new String(e),{deserializeJSON(){return JSON.parse(String(e))},toString(){return String(e)},toJSON(){return String(e)}})};yo.from=r=>r&&typeof r=="object"&&(r instanceof yo||"deserializeJSON"in r)?r:typeof r=="string"||Object.getPrototypeOf(r)===String.prototype?yo(String(r)):yo(JSON.stringify(r));yo.fromObject=yo.from;const JE=/^-?\d*(\.\d+)?$/;class as{string;type;constructor(e,t){if(this.string=e,this.type=t,!JE.test(e))throw new Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](e){if(!e||typeof e!="object")return!1;const t=e;return as.prototype.isPrototypeOf(e)||t.type==="bigDecimal"&&JE.test(t.string)}}const fP={},IA={};for(let r=0;r<256;r++){let e=r.toString(16).toLowerCase();e.length===1&&(e=`0${e}`),fP[r]=e,IA[e]=r}function hP(r){if(r.length%2!==0)throw new Error("Hex encoded strings must have an even number length");const e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2){const n=r.slice(t,t+2).toLowerCase();if(n in IA)e[t/2]=IA[n];else throw new Error(`Cannot decode unrecognized sequence ${n} as hexadecimal`)}return e}function xo(r){let e="";for(let t=0;t<r.byteLength;t++)e+=fP[r[t]];return e}const KE=typeof TextEncoder=="function"?new TextEncoder:null,X$=r=>{if(typeof r=="string"){if(KE)return KE.encode(r).byteLength;let e=r.length;for(let t=e-1;t>=0;t--){const n=r.charCodeAt(t);n>127&&n<=2047?e++:n>2047&&n<=65535&&(e+=2),n>=56320&&n<=57343&&t--}return e}else{if(typeof r.byteLength=="number")return r.byteLength;if(typeof r.size=="number")return r.size}throw new Error(`Body Length computation failed for ${r}`)},Pf=r=>typeof r=="string"?Pl(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(r),J$=r=>typeof ArrayBuffer=="function"&&r instanceof ArrayBuffer||Object.prototype.toString.call(r)==="[object ArrayBuffer]",pP=async r=>{},K$=async r=>{const e=r?.Bucket||"";if(typeof r.Bucket=="string"&&(r.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),nz(e)){if(r.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!rz(e)||e.indexOf(".")!==-1&&!String(r.Endpoint).startsWith("http:")||e.toLowerCase()!==e||e.length<3)&&(r.ForcePathStyle=!0);return r.DisableMultiRegionAccessPoints&&(r.disableMultiRegionAccessPoints=!0,r.DisableMRAP=!0),r},Z$=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,ez=/(\d+\.){3}\d+/,tz=/\.\./,rz=r=>Z$.test(r)&&!ez.test(r)&&!tz.test(r),nz=r=>{const[e,t,n,,,i]=r.split(":"),a=e==="arn"&&r.split(":").length>=6,s=!!(a&&t&&n&&i);if(a&&!s)throw new Error(`Invalid ARN: ${r} was an invalid ARN.`);return s},iz=(r,e,t,n=!1)=>{const i=async()=>{let a;return n?a=t.clientContextParams?.[r]??t[r]??t[e]:a=t[r]??t[e],typeof a=="function"?a():a};return r==="credentialScope"||e==="CredentialScope"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.credentialScope??a?.CredentialScope}:r==="accountId"||e==="AccountId"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.accountId??a?.AccountId}:r==="endpoint"||e==="endpoint"?async()=>{if(t.isCustomEndpoint===!1)return;const a=await i();if(a&&typeof a=="object"){if("url"in a)return a.url.href;if("hostname"in a){const{protocol:s,hostname:o,port:l,path:u}=a;return`${s}//${o}${l?":"+l:""}${u}`}}return a}:i};function az(r){return async(e,t,n,i)=>{if(!n.isCustomEndpoint){let o;n.serviceConfiguredEndpoint?o=await n.serviceConfiguredEndpoint():o=await r(n.serviceId),o&&(n.endpoint=()=>Promise.resolve(J1(o)),n.isCustomEndpoint=!0)}const a=await sz(e,t,n);if(typeof n.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");const s=n.endpointProvider(a,i);if(n.isCustomEndpoint&&n.endpoint){const o=await n.endpoint();if(o?.headers){s.headers??={};for(const[l,u]of Object.entries(o.headers))s.headers[l]=Array.isArray(u)?u:[u]}}return s}}const sz=async(r,e,t)=>{const n={},i=e?.getEndpointParameterInstructions?.()||{};for(const[a,s]of Object.entries(i))switch(s.type){case"staticContextParams":n[a]=s.value;break;case"contextParams":n[a]=r[s.name];break;case"clientContextParams":case"builtInParams":n[a]=await iz(s.name,a,t,s.type!=="builtInParams")();break;case"operationContextParams":n[a]=s.get(r);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(s))}return Object.keys(i).length===0&&Object.assign(n,t),String(t.serviceId).toLowerCase()==="s3"&&await K$(n),n};function oz(r,e,t){r.__smithy_context?r.__smithy_context.features||(r.__smithy_context.features={}):r.__smithy_context={features:{}},r.__smithy_context.features[e]=t}function lz(r){const e=az(r);return({config:t,instructions:n})=>(i,a)=>async s=>{t.isCustomEndpoint&&oz(a,"ENDPOINT_OVERRIDE","N");const o=await e(s.input,{getEndpointParameterInstructions(){return n}},{...t},a);a.endpointV2=o,a.authSchemes=o.properties?.authSchemes;const l=a.authSchemes?.[0];if(l){a.signing_region=l.signingRegion,a.signing_service=l.signingName;const c=Ac(a)?.selectedHttpAuthScheme?.httpAuthOption;c&&(c.signingProperties=Object.assign(c.signingProperties||{},{signing_region:l.signingRegion,signingRegion:l.signingRegion,signing_service:l.signingName,signingName:l.signingName,signingRegionSet:l.signingRegionSet},l.properties))}return i({...s})}}const uz={name:"serializerMiddleware"},cz={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:uz.name};function dz(r){const e=lz(r);return(t,n)=>({applyToStack:i=>{i.addRelativeTo(e({config:t,instructions:n}),cz)}})}function fz(r){return e=>{const t=e.tls??!0,{endpoint:n,useDualstackEndpoint:i,useFipsEndpoint:a}=e,s=n!=null?async()=>J1(await _s(n)()):void 0,l=Object.assign(e,{endpoint:s,tls:t,isCustomEndpoint:!!n,useDualstackEndpoint:_s(i??!1),useFipsEndpoint:_s(a??!1)});let u;return l.serviceConfiguredEndpoint=async()=>(e.serviceId&&!u&&(u=r(e.serviceId)),u),l}}class eb{nodes;root;conditions;results;constructor(e,t,n,i){this.nodes=e,this.root=t,this.conditions=n,this.results=i}static from(e,t,n,i){return new eb(e,t,n,i)}}class hz{capacity;data=new Map;parameters=[];constructor({size:e,params:t}){this.capacity=e??50,t&&(this.parameters=t)}get(e,t){const n=this.hash(e);if(n===!1)return t();if(!this.data.has(n)){if(this.data.size>this.capacity+10){const i=this.data.keys();let a=0;for(;;){const{value:s,done:o}=i.next();if(this.data.delete(s),o||++a>10)break}}this.data.set(n,t())}return this.data.get(n)}size(){return this.data.size}hash(e){let t="";const{parameters:n}=this;if(n.length===0)return!1;for(const i of n){const a=String(e[i]??"");if(a.includes("|;"))return!1;t+=a+"|;"}return t}}class _a extends Error{constructor(e){super(e),this.name="EndpointError"}}const pz="endpoints";function Pg(r){return typeof r!="object"||r==null?r:"ref"in r?`$${Pg(r.ref)}`:"fn"in r?`${r.fn}(${(r.argv||[]).map(Pg).join(", ")})`:JSON.stringify(r,null,2)}const tb={},gz=(r,e)=>r===e;function mz(...r){for(const e of r)if(e!=null)return e}const yz=r=>{const e=r.split("."),t=[];for(const n of e){const i=n.indexOf("[");if(i!==-1){if(n.indexOf("]")!==n.length-1)throw new _a(`Path: '${r}' does not end with ']'`);const a=n.slice(i+1,-1);if(Number.isNaN(parseInt(a)))throw new _a(`Invalid array index: '${a}' in path: '${r}'`);i!==0&&t.push(n.slice(0,i)),t.push(a)}else t.push(n)}return t},gP=(r,e)=>yz(e).reduce((t,n)=>{if(typeof t!="object")throw new _a(`Index '${n}' in '${e}' not found in '${JSON.stringify(r)}'`);if(Array.isArray(t)){const i=parseInt(n);return t[i<0?t.length+i:i]}return t[n]},r),vz=r=>r!=null;function Az(r,e,t){return r?e:t}const bz=r=>!r,wz=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),mP=r=>wz.test(r)||r.startsWith("[")&&r.endsWith("]"),qy={[Tf.HTTP]:80,[Tf.HTTPS]:443},xz=r=>{const e=(()=>{try{if(r instanceof URL)return r;if(typeof r=="object"&&"hostname"in r){const{hostname:d,port:h,protocol:g="",path:y="",query:v={}}=r,A=new URL(`${g}//${d}${h?`:${h}`:""}${y}`);return A.search=Object.entries(v).map(([x,S])=>`${x}=${S}`).join("&"),A}return new URL(r)}catch{return null}})();if(!e)return console.error(`Unable to parse ${JSON.stringify(r)} as a whatwg URL.`),null;const t=e.href,{host:n,hostname:i,pathname:a,protocol:s,search:o}=e;if(o)return null;const l=s.slice(0,-1);if(!Object.values(Tf).includes(l))return null;const u=mP(i),c=t.includes(`${n}:${qy[l]}`)||typeof r=="string"&&r.includes(`${n}:${qy[l]}`),f=`${n}${c?`:${qy[l]}`:""}`;return{scheme:l,authority:f,path:a,normalizedPath:a.endsWith("/")?a:`${a}/`,isIp:u}};function Cz(r,e,t){if(t===1)return[r];if(r==="")return[""];const n=r.split(e);return t===0?n:n.slice(0,t-1).concat(n.slice(1).join(e))}const Sz=(r,e)=>r===e,Ez=(r,e,t,n)=>r==null||e>=t||r.length<t||/[^\u0000-\u007f]/.test(r)?null:n?r.substring(r.length-t,r.length-e):r.substring(e,t),kz=r=>encodeURIComponent(r).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),Tz={booleanEquals:gz,coalesce:mz,getAttr:gP,isSet:vz,isValidHostLabel:nm,ite:Az,not:bz,parseURL:xz,split:Cz,stringEquals:Sz,substring:Ez,uriEncode:kz},yP=(r,e)=>{const t=[],{referenceRecord:n,endpointParams:i}=e;let a=0;for(;a<r.length;){const s=r.indexOf("{",a);if(s===-1){t.push(r.slice(a));break}t.push(r.slice(a,s));const o=r.indexOf("}",s);if(o===-1){t.push(r.slice(s));break}r[s+1]==="{"&&r[o+1]==="}"&&(t.push(r.slice(s+1,o)),a=o+2);const l=r.substring(s+1,o);if(l.includes("#")){const[u,c]=l.split("#");t.push(gP(n[u]??i[u],c))}else t.push(n[l]??i[l]);a=o+1}return t.join("")},Fz=({ref:r},e)=>e.referenceRecord[r]??e.endpointParams[r],om=(r,e,t)=>{if(typeof r=="string")return yP(r,t);if(r.fn)return AP.callFunction(r,t);if(r.ref)return Fz(r,t);throw new _a(`'${e}': ${String(r)} is not a string, function or reference.`)},vP=({fn:r,argv:e},t)=>{const n=Array(e.length);for(let s=0;s<n.length;++s){const o=e[s];typeof o=="boolean"||typeof o=="number"?n[s]=o:n[s]=AP.evaluateExpression(o,"arg",t)}const i=r.indexOf(".");if(i!==-1){const o=tb[r.slice(0,i)]?.[r.slice(i+1)];if(typeof o=="function")return o(...n)}const a=Tz[r];if(typeof a=="function")return a(...n);throw new Error(`function ${r} not loaded in endpointFunctions.`)},AP={evaluateExpression:om,callFunction:vP},Iz=(r,e)=>{const{assign:t}=r;if(t&&t in e.referenceRecord)throw new _a(`'${t}' is already defined in Reference Record.`);const n=vP(r,e);e.logger?.debug?.(`${pz} evaluateCondition: ${Pg(r)} = ${Pg(n)}`);const i=n===""?!0:!!n;return t!=null?{result:i,toAssign:{name:t,value:n}}:{result:i}},Pz=(r,e)=>Object.entries(r??{}).reduce((t,[n,i])=>(t[n]=i.map(a=>{const s=om(a,"Header value entry",e);if(typeof s!="string")throw new _a(`Header '${n}' value '${s}' is not a string`);return s}),t),{}),bP=(r,e)=>Object.entries(r).reduce((t,[n,i])=>(t[n]=xP.getEndpointProperty(i,e),t),{}),wP=(r,e)=>{if(Array.isArray(r))return r.map(t=>wP(t,e));switch(typeof r){case"string":return yP(r,e);case"object":if(r===null)throw new _a(`Unexpected endpoint property: ${r}`);return xP.getEndpointProperties(r,e);case"boolean":return r;default:throw new _a(`Unexpected endpoint property type: ${typeof r}`)}},xP={getEndpointProperty:wP,getEndpointProperties:bP},Dz=(r,e)=>{const t=om(r,"Endpoint URL",e);if(typeof t=="string")try{return new URL(t)}catch(n){throw console.error(`Failed to construct URL with ${t}`,n),n}throw new _a(`Endpoint URL must be a string, got ${typeof t}`)},Wy=1e8,Rz=(r,e)=>{const{nodes:t,root:n,results:i,conditions:a}=r;let s=n;const o={},l={referenceRecord:o,endpointParams:e.endpointParams,logger:e.logger};for(;s!==1&&s!==-1&&s<Wy;){const u=3*(Math.abs(s)-1),[c,f,d]=[t[u],t[u+1],t[u+2]],[h,g,y]=a[c],v=Iz({fn:h,assign:y,argv:g},l);if(v.toAssign){const{name:A,value:x}=v.toAssign;o[A]=x}s=s>=0===v.result?f:d}if(s>=Wy){const u=i[s-Wy];if(u[0]===-1){const[,h]=u;throw new _a(om(h,"Error",l))}const[c,f,d]=u;return{url:Dz(c,l),properties:bP(f,l),headers:Pz(d??{},l)}}throw new _a("No matching endpoint.")},Oz=fz(pP),CP=dz(pP);class Qy extends C$(am,Pl,Fg,im){}const Bz=r=>crypto.getRandomValues(r),SP=S$(Bz),Mz=SP,PA=async(r=new Uint8Array,e)=>{if(r instanceof Uint8Array)return Qy.mutate(r);if(!r)return Qy.mutate(new Uint8Array);const t=e.streamCollector(r);return Qy.mutate(await t)};class _z{serdeContext;setSerdeContext(e){this.serdeContext=e}}class Nz extends _z{options;compositeErrorRegistry;constructor(e){super(),this.options=e,this.compositeErrorRegistry=ta.for(e.defaultNamespace);for(const t of e.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return aa}getResponseType(){return oc}setSerdeContext(e){this.serdeContext=e,this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e),this.getPayloadCodec()&&this.getPayloadCodec().setSerdeContext(e)}updateServiceEndpoint(e,t){if("url"in t){e.protocol=t.url.protocol,e.hostname=t.url.hostname,e.port=t.url.port?Number(t.url.port):void 0,e.path=t.url.pathname,e.fragment=t.url.hash||void 0,e.username=t.url.username||void 0,e.password=t.url.password||void 0,e.query||(e.query={});for(const[n,i]of t.url.searchParams.entries())e.query[n]=i;if(t.headers)for(const n in t.headers)e.headers[n]=t.headers[n].join(", ");return e}else{if(e.protocol=t.protocol,e.hostname=t.hostname,e.port=t.port?Number(t.port):void 0,e.path=t.path,e.query={...t.query},t.headers)for(const n in t.headers)e.headers[n]=t.headers[n];return e}}setHostPrefix(e,t,n){if(this.serdeContext?.disableHostPrefix)return;const i=yi.of(t.input),a=jd(t.traits??{});if(a.endpoint){let s=a.endpoint?.[0];if(typeof s=="string"){for(const[o,l]of i.structIterator()){if(!l.getMergedTraits().hostLabel)continue;const u=n[o];if(typeof u!="string")throw new Error(`@smithy/core/schema - ${o} in input must be a string as hostLabel.`);s=s.replace(`{${o}}`,u)}e.hostname=s+e.hostname}}}deserializeMetadata(e){return{httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:e,requestSchema:t,initialRequest:n}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:e,requestSchema:t,initialRequest:n})}async deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:n}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:n})}async loadEventStreamCapability(){const{EventStreamSerde:e,eventStreamSerdeProvider:t}=await Promise.resolve().then(()=>require("./index.browser-DpspqM1v.cjs")),n=this.resolveEventStreamMarshaller(t);return new e({marshaller:n,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}resolveEventStreamMarshaller(e){const t=this.serdeContext;return t.eventStreamMarshaller?t.eventStreamMarshaller:e(this.serdeContext)}getDefaultContentType(){throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(e,t,n,i,a){return[]}getEventStreamMarshaller(){const e=this.serdeContext;if(!e.eventStreamMarshaller)throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return e.eventStreamMarshaller}}class Lz extends Nz{async serializeRequest(e,t,n){const i=this.serializer,a={},s={},o=await n.endpoint(),l=yi.of(e?.input),u=l.getSchema();let c;const f=t&&typeof t=="object"?t:{},d=new aa({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:a,headers:s,body:void 0});if(o&&(this.updateServiceEndpoint(d,o),this.setHostPrefix(d,e,f)),f){const h=l.getEventStreamMember();if(h){if(f[h]){const g={};for(const[y,v]of l.structIterator())y!==h&&f[y]&&(i.write(v,f[y]),g[y]=i.flush());c=await this.serializeEventStream({eventStream:f[h],requestSchema:l,initialRequest:g})}}else i.write(u,f),c=i.flush()}return d.headers=Object.assign(d.headers,s),d.query=a,d.body=c,d.method="POST",d}async deserializeResponse(e,t,n){const i=this.deserializer,a=yi.of(e.output),s={};if(n.statusCode>=300){const l=await PA(n.body,t);throw l.byteLength>0&&Object.assign(s,await i.read(15,l)),await this.handleError(e,t,n,s,this.deserializeMetadata(n)),new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(const l in n.headers){const u=n.headers[l];delete n.headers[l],n.headers[l.toLowerCase()]=u}const o=a.getEventStreamMember();if(o)s[o]=await this.deserializeEventStream({response:n,responseSchema:a,initialResponseContainer:s});else{const l=await PA(n.body,t);l.byteLength>0&&Object.assign(s,await i.read(a,l))}return s.$metadata=this.deserializeMetadata(n),s}}function EP(r,e){if(e.timestampFormat.useTrait&&r.isTimestampSchema()&&(r.getSchema()===5||r.getSchema()===6||r.getSchema()===7))return r.getSchema();const{httpLabel:t,httpPrefixHeaders:n,httpHeader:i,httpQuery:a}=r.getMergedTraits();return(e.httpBindings?typeof n=="string"||i?6:a||t?5:void 0:void 0)??e.timestampFormat.default}const Uz=r=>({setHttpHandler(e){r.httpHandler=e},httpHandler(){return r.httpHandler},updateHttpClientConfig(e,t){r.httpHandler?.updateHttpClientConfig(e,t)},httpHandlerConfigs(){return r.httpHandler.httpHandlerConfigs()}}),Vz=r=>({httpHandler:r.httpHandler()}),ZE="content-length";function $z(r){return e=>async t=>{const n=t.request;if(aa.isInstance(n)){const{body:i,headers:a}=n;if(i&&Object.keys(a).map(s=>s.toLowerCase()).indexOf(ZE)===-1)try{const s=r(i);n.headers={...n.headers,[ZE]:String(s)}}catch{}}return e({...t,request:n})}}const zz={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},Hz=r=>({applyToStack:e=>{e.add($z(r.bodyLengthChecker),zz)}}),kl=r=>encodeURIComponent(r).replace(/[!'()*]/g,Gz),Gz=r=>`%${r.charCodeAt(0).toString(16).toUpperCase()}`;function jz(r){const e=[];for(let t of Object.keys(r).sort()){const n=r[t];if(t=kl(t),Array.isArray(n))for(let i=0,a=n.length;i<a;i++)e.push(`${t}=${kl(n[i])}`);else{let i=t;(n||typeof n=="string")&&(i+=`=${kl(n)}`),e.push(i)}}return e.join("&")}const qz=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],Wz=["TimeoutError","RequestTimeout","RequestTimeoutException"],Qz=[500,502,503,504],Yz=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],Xz=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],Jz=r=>r?.$retryable!==void 0,Kz=r=>r.$metadata?.clockSkewCorrected,Zz=r=>{const e=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);return r&&r instanceof TypeError?e.has(r.message):!1},kP=r=>r.$metadata?.httpStatusCode===429||qz.includes(r.name)||r.$retryable?.throttling==!0,rb=(r,e=0)=>Jz(r)||Kz(r)||r.name==="InvalidSignatureException"&&r.message?.includes("Signature expired")||Wz.includes(r.name)||Yz.includes(r?.code||"")||Xz.includes(r?.code||"")||Qz.includes(r.$metadata?.httpStatusCode||0)||Zz(r)||tH(r)||r.cause!==void 0&&e<=10&&rb(r.cause,e+1),eH=r=>{if(r.$metadata?.httpStatusCode!==void 0){const e=r.$metadata.httpStatusCode;return 500<=e&&e<=599&&!rb(r)}return!1};function tH(r){return r.code==="ERR_HTTP2_STREAM_ERROR"&&r.message.includes("NGHTTP2_REFUSED_STREAM")}const TP=20*1e3,e2=500,rH=1,nH="amz-sdk-invocation-id",iH="amz-sdk-request";function aH(r,e){if(oc.isInstance(r))for(const t of Object.keys(r.headers)){const n=t.toLowerCase();if(n==="retry-after"){const i=r.headers[t];let a=NaN;if(i.endsWith("GMT"))try{a=(dP(i).getTime()-Date.now())/1e3}catch(s){e?.trace?.("Failed to parse retry-after header"),e?.trace?.(s)}else i.match(/ GMT, ((\d+)|(\d+\.\d+))$/)?a=Number(i.match(/ GMT, ([\d.]+)$/)?.[1]):i.match(/^((\d+)|(\d+\.\d+))$/)?a=Number(i):Date.parse(i)>=Date.now()&&(a=(Date.parse(i)-Date.now())/1e3);return isNaN(a)?void 0:new Date(Date.now()+a*1e3)}else if(n==="x-amz-retry-after"){const i=r.headers[t],a=Number(i);if(isNaN(a)){e?.trace?.(`Failed to parse x-amz-retry-after=${i}`);return}return new Date(Date.now()+a)}}}const sH=r=>r instanceof Error?r:r instanceof Object?Object.assign(new Error,r):typeof r=="string"?new Error(r):new Error(`AWS SDK error wrapper for ${r}`);function oH(r){return e=>(t,n)=>async i=>{let a=await e.retryStrategy();const s=await e.maxAttempts();if(uH(a)){a=a;let o=await a.acquireInitialRetryToken((n.partition_id??"")+(n.__retryLongPoll?":longpoll":"")),l=new Error,u=0,c=0;const{request:f}=i,d=aa.isInstance(f);for(d&&(f.headers[nH]=SP());;)try{d&&(f.headers[iH]=`attempt=${u+1}; max=${s}`);const{response:h,output:g}=await t(i);return a.recordSuccess(o),g.$metadata.attempts=u+1,g.$metadata.totalRetryDelay=c,{response:h,output:g}}catch(h){const g=cH(h,e.logger);if(l=sH(h),d&&r(f))throw(n.logger instanceof lP?console:n.logger)?.warn("An error was encountered in a non-retryable streaming request."),l;try{o=await a.refreshRetryTokenForRetry(o,g)}catch{throw l.$metadata||(l.$metadata={}),l.$metadata.attempts=u+1,l.$metadata.totalRetryDelay=c,l}u=o.getRetryCount();const y=o.getRetryDelay();c+=(o?.$retryLog?.acquisitionDelay??0)+y,y>0&&await lH(y)}}else return a=a,a?.mode&&(n.userAgent=[...n.userAgent||[],["cfg/retry-mode",a.mode]]),a.retry(t,i)}}const lH=r=>new Promise(e=>setTimeout(e,r)),uH=r=>typeof r.acquireInitialRetryToken<"u"&&typeof r.refreshRetryTokenForRetry<"u"&&typeof r.recordSuccess<"u",cH=(r,e)=>{const t={error:r,errorType:dH(r)},n=aH(r.$response,e);return n&&(t.retryAfterHint=n),t},dH=r=>kP(r)?"THROTTLING":rb(r)?"TRANSIENT":eH(r)?"SERVER_ERROR":"CLIENT_ERROR",fH={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function hH(r){const e=oH(r);return t=>({applyToStack:n=>{n.add(e(t),fH)}})}class nb{static setTimeoutFn=(e,t)=>setTimeout(e,t);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(e){this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(e){let t;this.updateMeasuredRate();const n=e;if(n?.errorType==="THROTTLING"||kP(n?.error??e)){const s=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=s,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(s),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());const a=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(a)}getCurrentTimeInSeconds(){return Date.now()/1e3}async acquireTokenBucket(e){if(this.enabled){for(this.refillTokenBucket();e>this.availableTokens;){const t=(e-this.availableTokens)/this.fillRate*1e3;await new Promise(n=>nb.setTimeoutFn(n,t)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-e}}refillTokenBucket(){const e=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=e;return}const t=(e-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+t),this.lastTimestamp=e}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(e){return this.getPrecise(e*this.beta)}cubicSuccess(e){return this.getPrecise(this.scaleConstant*Math.pow(e-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(e){this.refillTokenBucket(),this.fillRate=Math.max(e,this.minFillRate),this.maxCapacity=Math.max(e,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){const e=this.getCurrentTimeInSeconds(),t=Math.floor(e*2)/2;if(this.requestCount++,t>this.lastTxRateBucket){const n=this.requestCount/(t-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(n*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=t}}getPrecise(e){return parseFloat(e.toFixed(8))}}class ki{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return ki.v2026?50:100}static throttlingDelay(){return ki.v2026?1e3:500}static cost(){return ki.v2026?14:5}static throttlingCost(){return ki.v2026?5:10}static modifiedCostType(){return ki.v2026?"THROTTLING":"TRANSIENT"}}class pH{x=ki.delay();computeNextBackoffDelay(e){const i=Math.random()*Math.min(this.x*2**e,TP);return Math.floor(i)}setDelayBase(e){this.x=e}}class t2{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(e,t,n,i){this.delay=e,this.count=t,this.cost=n,this.longPoll=i}getRetryCount(){return this.count}getRetryDelay(){return Math.min(TP,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var Bo;(function(r){r.STANDARD="standard",r.ADAPTIVE="adaptive"})(Bo||(Bo={}));const nf=3,gH=Bo.STANDARD,Pp={incompatible:1,attempts:2,capacity:3};class DA{mode=Bo.STANDARD;retryBackoffStrategy;capacity=e2;maxAttemptsProvider;baseDelay;constructor(e){typeof e=="number"?this.maxAttemptsProvider=async()=>e:typeof e=="function"?this.maxAttemptsProvider=e:e&&typeof e=="object"&&(this.maxAttemptsProvider=async()=>e.maxAttempts,this.baseDelay=e.baseDelay,this.retryBackoffStrategy=e.backoff),this.maxAttemptsProvider??=async()=>nf,this.baseDelay??=ki.delay(),this.retryBackoffStrategy??=new pH}async acquireInitialRetryToken(e){return new t2(ki.delay(),0,void 0,ki.v2026&&e.includes(":longpoll"))}async refreshRetryTokenForRetry(e,t){const n=await this.getMaxAttempts(),i=this.retryCode(e,t,n),a=i===0,s=e.isLongPoll?.();if(a||s){const o=t.errorType;this.retryBackoffStrategy.setDelayBase(o==="THROTTLING"?ki.throttlingDelay():this.baseDelay);const l=this.retryBackoffStrategy.computeNextBackoffDelay(e.getRetryCount());let u=l;if(t.retryAfterHint instanceof Date&&(u=Math.max(l,Math.min(t.retryAfterHint.getTime()-Date.now(),l+5e3))),a){const c=this.getCapacityCost(o);this.capacity-=c;const f=new t2(0,e.getRetryCount()+1,c,e.isLongPoll?.()??!1);return await new Promise(d=>setTimeout(d,u)),f.$retryLog.acquisitionDelay=u,f}else{const c=ki.v2026&&i===Pp.capacity&&s?u:0;c>0&&await new Promise(f=>setTimeout(f,c))}}throw new Error("No retry token available")}recordSuccess(e){this.capacity=Math.min(e2,this.capacity+(e.getRetryCost()??rH))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch{return console.warn(`Max attempts provider could not resolve. Using default of ${nf}`),nf}}retryCode(e,t,n){const i=e.getRetryCount()+1,a=this.isRetryableError(t.errorType)?0:Pp.incompatible,s=i<n?0:Pp.attempts,o=this.capacity>=this.getCapacityCost(t.errorType)?0:Pp.capacity;return a||s||o}getCapacityCost(e){return e===ki.modifiedCostType()?ki.throttlingCost():ki.cost()}isRetryableError(e){return e==="THROTTLING"||e==="TRANSIENT"}}class mH{mode=Bo.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(e,t){const{rateLimiter:n}=t??{};this.rateLimiter=n??new nb,this.standardRetryStrategy=t?new DA({maxAttempts:typeof e=="number"?e:3,...t}):new DA(e)}async acquireInitialRetryToken(e){const t=await this.standardRetryStrategy.acquireInitialRetryToken(e);return await this.rateLimiter.getSendToken(),t}async refreshRetryTokenForRetry(e,t){this.rateLimiter.updateClientSendingRate(t);const n=await this.standardRetryStrategy.refreshRetryTokenForRetry(e,t);return await this.rateLimiter.getSendToken(),n}recordSuccess(e){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(e)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}}const yH=(r,e)=>{const{retryStrategy:t,retryMode:n}=r,{defaultMaxAttempts:i=nf,defaultBaseDelay:a=ki.delay()}={},s=_s(r.maxAttempts??i);let o=t?Promise.resolve(t):void 0;const l=async()=>{const u=await s();return await _s(n)()===Bo.ADAPTIVE?new mH(s,{maxAttempts:u,baseDelay:a}):new DA({maxAttempts:u,baseDelay:a})};return Object.assign(r,{maxAttempts:s,retryStrategy:()=>o??=l()})},vH=hH(t$);ki.v2026||=typeof process=="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function Ds(r,e,t){r.__aws_sdk_context?r.__aws_sdk_context.features||(r.__aws_sdk_context.features={}):r.__aws_sdk_context={features:{}},r.__aws_sdk_context.features[e]=t}const AH=r=>e=>async t=>{if(!aa.isInstance(t.request))return e(t);const{request:n}=t,{handlerProtocol:i=""}=r.requestHandler.metadata||{};if(i.indexOf("h2")>=0&&!n.headers[":authority"])delete n.headers.host,n.headers[":authority"]=n.hostname+(n.port?":"+n.port:"");else if(!n.headers.host){let a=n.hostname;n.port!=null&&(a+=`:${n.port}`),n.headers.host=a}return e(t)},bH={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},wH=r=>({applyToStack:e=>{e.add(AH(r),bH)}}),xH=()=>(r,e)=>async t=>{try{const n=await r(t),{clientName:i,commandName:a,logger:s,dynamoDbDocumentClientOptions:o={}}=e,{overrideInputFilterSensitiveLog:l,overrideOutputFilterSensitiveLog:u}=o,c=l??e.inputFilterSensitiveLog,f=u??e.outputFilterSensitiveLog,{$metadata:d,...h}=n.output;return s?.info?.({clientName:i,commandName:a,input:c(t.input),output:f(h),metadata:d}),n}catch(n){const{clientName:i,commandName:a,logger:s,dynamoDbDocumentClientOptions:o={}}=e,{overrideInputFilterSensitiveLog:l}=o,u=l??e.inputFilterSensitiveLog;throw s?.error?.({clientName:i,commandName:a,input:u(t.input),error:n,metadata:n.$metadata}),n}},CH={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},SH=r=>({applyToStack:e=>{e.add(xH(),CH)}}),EH=r=>({applyToStack:e=>{}}),kH=(r,e)=>{if(!e||e.length===0)return r;const t=[];for(const n of e)for(const i of r)i.schemeId.split("#")[1]===n&&t.push(i);for(const n of r)t.find(({schemeId:i})=>i===n.schemeId)||t.push(n);return t};function TH(r){const e=new Map;for(const t of r)e.set(t.schemeId,t);return e}const FH=(r,e)=>(t,n)=>async i=>{const a=r.httpAuthSchemeProvider(await e.httpAuthSchemeParametersProvider(r,n,i.input)),s=r.authSchemePreference?await r.authSchemePreference():[],o=kH(a,s),l=TH(r.httpAuthSchemes),u=Ac(n),c=[];for(const f of o){const d=l.get(f.schemeId);if(!d){c.push(`HttpAuthScheme \`${f.schemeId}\` was not enabled for this service.`);continue}const h=d.identityProvider(await e.identityProviderConfigProvider(r));if(!h){c.push(`HttpAuthScheme \`${f.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties:g={},signingProperties:y={}}=f.propertiesExtractor?.(r,n)||{};f.identityProperties=Object.assign(f.identityProperties||{},g),f.signingProperties=Object.assign(f.signingProperties||{},y),u.selectedHttpAuthScheme={httpAuthOption:f,identity:await h(f.identityProperties),signer:d.signer};break}if(!u.selectedHttpAuthScheme)throw new Error(c.join(`
|
|
3108
|
+
`),O$={warn:console.warn},B$=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Z1=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function M$(r){const e=r.getUTCFullYear(),t=r.getUTCMonth(),n=r.getUTCDay(),i=r.getUTCDate(),a=r.getUTCHours(),s=r.getUTCMinutes(),o=r.getUTCSeconds(),l=i<10?`0${i}`:`${i}`,u=a<10?`0${a}`:`${a}`,c=s<10?`0${s}`:`${s}`,f=o<10?`0${o}`:`${o}`;return`${B$[n]}, ${l} ${Z1[t]} ${e} ${u}:${c}:${f} GMT`}const _$=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),N$=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");const e=_$.exec(r);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");const[t,n,i,a,s,o,l,u,c]=e,f=Ig(If(n)),d=wo(i,"month",1,12),h=wo(a,"day",1,31),g=ig(f,d,h,{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u});return c.toUpperCase()!="Z"&&g.setTime(g.getTime()-Y$(c)),g},L$=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),U$=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),V$=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),dP=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=L$.exec(r);if(e){const[t,n,i,a,s,o,l,u]=e;return ig(Ig(If(a)),jy(i),wo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u})}if(e=U$.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return G$(ig(z$(a),jy(i),wo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u}))}if(e=V$.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return ig(Ig(If(u)),jy(n),wo(i.trimLeft(),"day",1,31),{hours:a,minutes:s,seconds:o,fractionalMilliseconds:l})}throw new TypeError("Invalid RFC-7231 date-time value")},$$=r=>{if(r==null)return;let e;if(typeof r=="number")e=r;else if(typeof r=="string")e=F$(r);else if(typeof r=="object"&&r.tag===1)e=r.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(e)||e===1/0||e===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(e*1e3))},ig=(r,e,t,n)=>{const i=e-1;return q$(r,i,t),new Date(Date.UTC(r,i,t,wo(n.hours,"hour",0,23),wo(n.minutes,"minute",0,59),wo(n.seconds,"seconds",0,60),Q$(n.fractionalMilliseconds)))},z$=r=>{const e=new Date().getUTCFullYear(),t=Math.floor(e/100)*100+Ig(If(r));return t<e?t+100:t},H$=50*365*24*60*60*1e3,G$=r=>r.getTime()-new Date().getTime()>H$?new Date(Date.UTC(r.getUTCFullYear()-100,r.getUTCMonth(),r.getUTCDate(),r.getUTCHours(),r.getUTCMinutes(),r.getUTCSeconds(),r.getUTCMilliseconds())):r,jy=r=>{const e=Z1.indexOf(r);if(e<0)throw new TypeError(`Invalid month: ${r}`);return e+1},j$=[31,28,31,30,31,30,31,31,30,31,30,31],q$=(r,e,t)=>{let n=j$[e];if(e===1&&W$(r)&&(n=29),t>n)throw new TypeError(`Invalid day for ${Z1[e]} in ${r}: ${t}`)},W$=r=>r%4===0&&(r%100!==0||r%400===0),wo=(r,e,t,n)=>{const i=D$(If(r));if(i<t||i>n)throw new TypeError(`${e} must be between ${t} and ${n}, inclusive`);return i},Q$=r=>r==null?0:I$("0."+r)*1e3,Y$=r=>{const e=r[0];let t=1;if(e=="+")t=1;else if(e=="-")t=-1;else throw new TypeError(`Offset direction, ${e}, must be "+" or "-"`);const n=Number(r.substring(1,3)),i=Number(r.substring(4,6));return t*(n*60+i)*60*1e3},If=r=>{let e=0;for(;e<r.length-1&&r.charAt(e)==="0";)e++;return e===0?r:r.slice(e)},yo=function(e){return Object.assign(new String(e),{deserializeJSON(){return JSON.parse(String(e))},toString(){return String(e)},toJSON(){return String(e)}})};yo.from=r=>r&&typeof r=="object"&&(r instanceof yo||"deserializeJSON"in r)?r:typeof r=="string"||Object.getPrototypeOf(r)===String.prototype?yo(String(r)):yo(JSON.stringify(r));yo.fromObject=yo.from;const JE=/^-?\d*(\.\d+)?$/;class as{string;type;constructor(e,t){if(this.string=e,this.type=t,!JE.test(e))throw new Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](e){if(!e||typeof e!="object")return!1;const t=e;return as.prototype.isPrototypeOf(e)||t.type==="bigDecimal"&&JE.test(t.string)}}const fP={},IA={};for(let r=0;r<256;r++){let e=r.toString(16).toLowerCase();e.length===1&&(e=`0${e}`),fP[r]=e,IA[e]=r}function hP(r){if(r.length%2!==0)throw new Error("Hex encoded strings must have an even number length");const e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2){const n=r.slice(t,t+2).toLowerCase();if(n in IA)e[t/2]=IA[n];else throw new Error(`Cannot decode unrecognized sequence ${n} as hexadecimal`)}return e}function xo(r){let e="";for(let t=0;t<r.byteLength;t++)e+=fP[r[t]];return e}const KE=typeof TextEncoder=="function"?new TextEncoder:null,X$=r=>{if(typeof r=="string"){if(KE)return KE.encode(r).byteLength;let e=r.length;for(let t=e-1;t>=0;t--){const n=r.charCodeAt(t);n>127&&n<=2047?e++:n>2047&&n<=65535&&(e+=2),n>=56320&&n<=57343&&t--}return e}else{if(typeof r.byteLength=="number")return r.byteLength;if(typeof r.size=="number")return r.size}throw new Error(`Body Length computation failed for ${r}`)},Pf=r=>typeof r=="string"?Pl(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(r),J$=r=>typeof ArrayBuffer=="function"&&r instanceof ArrayBuffer||Object.prototype.toString.call(r)==="[object ArrayBuffer]",pP=async r=>{},K$=async r=>{const e=r?.Bucket||"";if(typeof r.Bucket=="string"&&(r.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),nz(e)){if(r.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!rz(e)||e.indexOf(".")!==-1&&!String(r.Endpoint).startsWith("http:")||e.toLowerCase()!==e||e.length<3)&&(r.ForcePathStyle=!0);return r.DisableMultiRegionAccessPoints&&(r.disableMultiRegionAccessPoints=!0,r.DisableMRAP=!0),r},Z$=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,ez=/(\d+\.){3}\d+/,tz=/\.\./,rz=r=>Z$.test(r)&&!ez.test(r)&&!tz.test(r),nz=r=>{const[e,t,n,,,i]=r.split(":"),a=e==="arn"&&r.split(":").length>=6,s=!!(a&&t&&n&&i);if(a&&!s)throw new Error(`Invalid ARN: ${r} was an invalid ARN.`);return s},iz=(r,e,t,n=!1)=>{const i=async()=>{let a;return n?a=t.clientContextParams?.[r]??t[r]??t[e]:a=t[r]??t[e],typeof a=="function"?a():a};return r==="credentialScope"||e==="CredentialScope"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.credentialScope??a?.CredentialScope}:r==="accountId"||e==="AccountId"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.accountId??a?.AccountId}:r==="endpoint"||e==="endpoint"?async()=>{if(t.isCustomEndpoint===!1)return;const a=await i();if(a&&typeof a=="object"){if("url"in a)return a.url.href;if("hostname"in a){const{protocol:s,hostname:o,port:l,path:u}=a;return`${s}//${o}${l?":"+l:""}${u}`}}return a}:i};function az(r){return async(e,t,n,i)=>{if(!n.isCustomEndpoint){let o;n.serviceConfiguredEndpoint?o=await n.serviceConfiguredEndpoint():o=await r(n.serviceId),o&&(n.endpoint=()=>Promise.resolve(J1(o)),n.isCustomEndpoint=!0)}const a=await sz(e,t,n);if(typeof n.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");const s=n.endpointProvider(a,i);if(n.isCustomEndpoint&&n.endpoint){const o=await n.endpoint();if(o?.headers){s.headers??={};for(const[l,u]of Object.entries(o.headers))s.headers[l]=Array.isArray(u)?u:[u]}}return s}}const sz=async(r,e,t)=>{const n={},i=e?.getEndpointParameterInstructions?.()||{};for(const[a,s]of Object.entries(i))switch(s.type){case"staticContextParams":n[a]=s.value;break;case"contextParams":n[a]=r[s.name];break;case"clientContextParams":case"builtInParams":n[a]=await iz(s.name,a,t,s.type!=="builtInParams")();break;case"operationContextParams":n[a]=s.get(r);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(s))}return Object.keys(i).length===0&&Object.assign(n,t),String(t.serviceId).toLowerCase()==="s3"&&await K$(n),n};function oz(r,e,t){r.__smithy_context?r.__smithy_context.features||(r.__smithy_context.features={}):r.__smithy_context={features:{}},r.__smithy_context.features[e]=t}function lz(r){const e=az(r);return({config:t,instructions:n})=>(i,a)=>async s=>{t.isCustomEndpoint&&oz(a,"ENDPOINT_OVERRIDE","N");const o=await e(s.input,{getEndpointParameterInstructions(){return n}},{...t},a);a.endpointV2=o,a.authSchemes=o.properties?.authSchemes;const l=a.authSchemes?.[0];if(l){a.signing_region=l.signingRegion,a.signing_service=l.signingName;const c=Ac(a)?.selectedHttpAuthScheme?.httpAuthOption;c&&(c.signingProperties=Object.assign(c.signingProperties||{},{signing_region:l.signingRegion,signingRegion:l.signingRegion,signing_service:l.signingName,signingName:l.signingName,signingRegionSet:l.signingRegionSet},l.properties))}return i({...s})}}const uz={name:"serializerMiddleware"},cz={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:uz.name};function dz(r){const e=lz(r);return(t,n)=>({applyToStack:i=>{i.addRelativeTo(e({config:t,instructions:n}),cz)}})}function fz(r){return e=>{const t=e.tls??!0,{endpoint:n,useDualstackEndpoint:i,useFipsEndpoint:a}=e,s=n!=null?async()=>J1(await _s(n)()):void 0,l=Object.assign(e,{endpoint:s,tls:t,isCustomEndpoint:!!n,useDualstackEndpoint:_s(i??!1),useFipsEndpoint:_s(a??!1)});let u;return l.serviceConfiguredEndpoint=async()=>(e.serviceId&&!u&&(u=r(e.serviceId)),u),l}}class eb{nodes;root;conditions;results;constructor(e,t,n,i){this.nodes=e,this.root=t,this.conditions=n,this.results=i}static from(e,t,n,i){return new eb(e,t,n,i)}}class hz{capacity;data=new Map;parameters=[];constructor({size:e,params:t}){this.capacity=e??50,t&&(this.parameters=t)}get(e,t){const n=this.hash(e);if(n===!1)return t();if(!this.data.has(n)){if(this.data.size>this.capacity+10){const i=this.data.keys();let a=0;for(;;){const{value:s,done:o}=i.next();if(this.data.delete(s),o||++a>10)break}}this.data.set(n,t())}return this.data.get(n)}size(){return this.data.size}hash(e){let t="";const{parameters:n}=this;if(n.length===0)return!1;for(const i of n){const a=String(e[i]??"");if(a.includes("|;"))return!1;t+=a+"|;"}return t}}class _a extends Error{constructor(e){super(e),this.name="EndpointError"}}const pz="endpoints";function Pg(r){return typeof r!="object"||r==null?r:"ref"in r?`$${Pg(r.ref)}`:"fn"in r?`${r.fn}(${(r.argv||[]).map(Pg).join(", ")})`:JSON.stringify(r,null,2)}const tb={},gz=(r,e)=>r===e;function mz(...r){for(const e of r)if(e!=null)return e}const yz=r=>{const e=r.split("."),t=[];for(const n of e){const i=n.indexOf("[");if(i!==-1){if(n.indexOf("]")!==n.length-1)throw new _a(`Path: '${r}' does not end with ']'`);const a=n.slice(i+1,-1);if(Number.isNaN(parseInt(a)))throw new _a(`Invalid array index: '${a}' in path: '${r}'`);i!==0&&t.push(n.slice(0,i)),t.push(a)}else t.push(n)}return t},gP=(r,e)=>yz(e).reduce((t,n)=>{if(typeof t!="object")throw new _a(`Index '${n}' in '${e}' not found in '${JSON.stringify(r)}'`);if(Array.isArray(t)){const i=parseInt(n);return t[i<0?t.length+i:i]}return t[n]},r),vz=r=>r!=null;function Az(r,e,t){return r?e:t}const bz=r=>!r,wz=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),mP=r=>wz.test(r)||r.startsWith("[")&&r.endsWith("]"),qy={[Tf.HTTP]:80,[Tf.HTTPS]:443},xz=r=>{const e=(()=>{try{if(r instanceof URL)return r;if(typeof r=="object"&&"hostname"in r){const{hostname:d,port:h,protocol:g="",path:y="",query:v={}}=r,A=new URL(`${g}//${d}${h?`:${h}`:""}${y}`);return A.search=Object.entries(v).map(([x,S])=>`${x}=${S}`).join("&"),A}return new URL(r)}catch{return null}})();if(!e)return console.error(`Unable to parse ${JSON.stringify(r)} as a whatwg URL.`),null;const t=e.href,{host:n,hostname:i,pathname:a,protocol:s,search:o}=e;if(o)return null;const l=s.slice(0,-1);if(!Object.values(Tf).includes(l))return null;const u=mP(i),c=t.includes(`${n}:${qy[l]}`)||typeof r=="string"&&r.includes(`${n}:${qy[l]}`),f=`${n}${c?`:${qy[l]}`:""}`;return{scheme:l,authority:f,path:a,normalizedPath:a.endsWith("/")?a:`${a}/`,isIp:u}};function Cz(r,e,t){if(t===1)return[r];if(r==="")return[""];const n=r.split(e);return t===0?n:n.slice(0,t-1).concat(n.slice(1).join(e))}const Sz=(r,e)=>r===e,Ez=(r,e,t,n)=>r==null||e>=t||r.length<t||/[^\u0000-\u007f]/.test(r)?null:n?r.substring(r.length-t,r.length-e):r.substring(e,t),kz=r=>encodeURIComponent(r).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),Tz={booleanEquals:gz,coalesce:mz,getAttr:gP,isSet:vz,isValidHostLabel:nm,ite:Az,not:bz,parseURL:xz,split:Cz,stringEquals:Sz,substring:Ez,uriEncode:kz},yP=(r,e)=>{const t=[],{referenceRecord:n,endpointParams:i}=e;let a=0;for(;a<r.length;){const s=r.indexOf("{",a);if(s===-1){t.push(r.slice(a));break}t.push(r.slice(a,s));const o=r.indexOf("}",s);if(o===-1){t.push(r.slice(s));break}r[s+1]==="{"&&r[o+1]==="}"&&(t.push(r.slice(s+1,o)),a=o+2);const l=r.substring(s+1,o);if(l.includes("#")){const[u,c]=l.split("#");t.push(gP(n[u]??i[u],c))}else t.push(n[l]??i[l]);a=o+1}return t.join("")},Fz=({ref:r},e)=>e.referenceRecord[r]??e.endpointParams[r],om=(r,e,t)=>{if(typeof r=="string")return yP(r,t);if(r.fn)return AP.callFunction(r,t);if(r.ref)return Fz(r,t);throw new _a(`'${e}': ${String(r)} is not a string, function or reference.`)},vP=({fn:r,argv:e},t)=>{const n=Array(e.length);for(let s=0;s<n.length;++s){const o=e[s];typeof o=="boolean"||typeof o=="number"?n[s]=o:n[s]=AP.evaluateExpression(o,"arg",t)}const i=r.indexOf(".");if(i!==-1){const o=tb[r.slice(0,i)]?.[r.slice(i+1)];if(typeof o=="function")return o(...n)}const a=Tz[r];if(typeof a=="function")return a(...n);throw new Error(`function ${r} not loaded in endpointFunctions.`)},AP={evaluateExpression:om,callFunction:vP},Iz=(r,e)=>{const{assign:t}=r;if(t&&t in e.referenceRecord)throw new _a(`'${t}' is already defined in Reference Record.`);const n=vP(r,e);e.logger?.debug?.(`${pz} evaluateCondition: ${Pg(r)} = ${Pg(n)}`);const i=n===""?!0:!!n;return t!=null?{result:i,toAssign:{name:t,value:n}}:{result:i}},Pz=(r,e)=>Object.entries(r??{}).reduce((t,[n,i])=>(t[n]=i.map(a=>{const s=om(a,"Header value entry",e);if(typeof s!="string")throw new _a(`Header '${n}' value '${s}' is not a string`);return s}),t),{}),bP=(r,e)=>Object.entries(r).reduce((t,[n,i])=>(t[n]=xP.getEndpointProperty(i,e),t),{}),wP=(r,e)=>{if(Array.isArray(r))return r.map(t=>wP(t,e));switch(typeof r){case"string":return yP(r,e);case"object":if(r===null)throw new _a(`Unexpected endpoint property: ${r}`);return xP.getEndpointProperties(r,e);case"boolean":return r;default:throw new _a(`Unexpected endpoint property type: ${typeof r}`)}},xP={getEndpointProperty:wP,getEndpointProperties:bP},Dz=(r,e)=>{const t=om(r,"Endpoint URL",e);if(typeof t=="string")try{return new URL(t)}catch(n){throw console.error(`Failed to construct URL with ${t}`,n),n}throw new _a(`Endpoint URL must be a string, got ${typeof t}`)},Wy=1e8,Rz=(r,e)=>{const{nodes:t,root:n,results:i,conditions:a}=r;let s=n;const o={},l={referenceRecord:o,endpointParams:e.endpointParams,logger:e.logger};for(;s!==1&&s!==-1&&s<Wy;){const u=3*(Math.abs(s)-1),[c,f,d]=[t[u],t[u+1],t[u+2]],[h,g,y]=a[c],v=Iz({fn:h,assign:y,argv:g},l);if(v.toAssign){const{name:A,value:x}=v.toAssign;o[A]=x}s=s>=0===v.result?f:d}if(s>=Wy){const u=i[s-Wy];if(u[0]===-1){const[,h]=u;throw new _a(om(h,"Error",l))}const[c,f,d]=u;return{url:Dz(c,l),properties:bP(f,l),headers:Pz(d??{},l)}}throw new _a("No matching endpoint.")},Oz=fz(pP),CP=dz(pP);class Qy extends C$(am,Pl,Fg,im){}const Bz=r=>crypto.getRandomValues(r),SP=S$(Bz),Mz=SP,PA=async(r=new Uint8Array,e)=>{if(r instanceof Uint8Array)return Qy.mutate(r);if(!r)return Qy.mutate(new Uint8Array);const t=e.streamCollector(r);return Qy.mutate(await t)};class _z{serdeContext;setSerdeContext(e){this.serdeContext=e}}class Nz extends _z{options;compositeErrorRegistry;constructor(e){super(),this.options=e,this.compositeErrorRegistry=ta.for(e.defaultNamespace);for(const t of e.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return aa}getResponseType(){return oc}setSerdeContext(e){this.serdeContext=e,this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e),this.getPayloadCodec()&&this.getPayloadCodec().setSerdeContext(e)}updateServiceEndpoint(e,t){if("url"in t){e.protocol=t.url.protocol,e.hostname=t.url.hostname,e.port=t.url.port?Number(t.url.port):void 0,e.path=t.url.pathname,e.fragment=t.url.hash||void 0,e.username=t.url.username||void 0,e.password=t.url.password||void 0,e.query||(e.query={});for(const[n,i]of t.url.searchParams.entries())e.query[n]=i;if(t.headers)for(const n in t.headers)e.headers[n]=t.headers[n].join(", ");return e}else{if(e.protocol=t.protocol,e.hostname=t.hostname,e.port=t.port?Number(t.port):void 0,e.path=t.path,e.query={...t.query},t.headers)for(const n in t.headers)e.headers[n]=t.headers[n];return e}}setHostPrefix(e,t,n){if(this.serdeContext?.disableHostPrefix)return;const i=yi.of(t.input),a=jd(t.traits??{});if(a.endpoint){let s=a.endpoint?.[0];if(typeof s=="string"){for(const[o,l]of i.structIterator()){if(!l.getMergedTraits().hostLabel)continue;const u=n[o];if(typeof u!="string")throw new Error(`@smithy/core/schema - ${o} in input must be a string as hostLabel.`);s=s.replace(`{${o}}`,u)}e.hostname=s+e.hostname}}}deserializeMetadata(e){return{httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:e,requestSchema:t,initialRequest:n}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:e,requestSchema:t,initialRequest:n})}async deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:n}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:n})}async loadEventStreamCapability(){const{EventStreamSerde:e,eventStreamSerdeProvider:t}=await Promise.resolve().then(()=>require("./index.browser-C2H4mjal.cjs")),n=this.resolveEventStreamMarshaller(t);return new e({marshaller:n,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}resolveEventStreamMarshaller(e){const t=this.serdeContext;return t.eventStreamMarshaller?t.eventStreamMarshaller:e(this.serdeContext)}getDefaultContentType(){throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(e,t,n,i,a){return[]}getEventStreamMarshaller(){const e=this.serdeContext;if(!e.eventStreamMarshaller)throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return e.eventStreamMarshaller}}class Lz extends Nz{async serializeRequest(e,t,n){const i=this.serializer,a={},s={},o=await n.endpoint(),l=yi.of(e?.input),u=l.getSchema();let c;const f=t&&typeof t=="object"?t:{},d=new aa({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:a,headers:s,body:void 0});if(o&&(this.updateServiceEndpoint(d,o),this.setHostPrefix(d,e,f)),f){const h=l.getEventStreamMember();if(h){if(f[h]){const g={};for(const[y,v]of l.structIterator())y!==h&&f[y]&&(i.write(v,f[y]),g[y]=i.flush());c=await this.serializeEventStream({eventStream:f[h],requestSchema:l,initialRequest:g})}}else i.write(u,f),c=i.flush()}return d.headers=Object.assign(d.headers,s),d.query=a,d.body=c,d.method="POST",d}async deserializeResponse(e,t,n){const i=this.deserializer,a=yi.of(e.output),s={};if(n.statusCode>=300){const l=await PA(n.body,t);throw l.byteLength>0&&Object.assign(s,await i.read(15,l)),await this.handleError(e,t,n,s,this.deserializeMetadata(n)),new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(const l in n.headers){const u=n.headers[l];delete n.headers[l],n.headers[l.toLowerCase()]=u}const o=a.getEventStreamMember();if(o)s[o]=await this.deserializeEventStream({response:n,responseSchema:a,initialResponseContainer:s});else{const l=await PA(n.body,t);l.byteLength>0&&Object.assign(s,await i.read(a,l))}return s.$metadata=this.deserializeMetadata(n),s}}function EP(r,e){if(e.timestampFormat.useTrait&&r.isTimestampSchema()&&(r.getSchema()===5||r.getSchema()===6||r.getSchema()===7))return r.getSchema();const{httpLabel:t,httpPrefixHeaders:n,httpHeader:i,httpQuery:a}=r.getMergedTraits();return(e.httpBindings?typeof n=="string"||i?6:a||t?5:void 0:void 0)??e.timestampFormat.default}const Uz=r=>({setHttpHandler(e){r.httpHandler=e},httpHandler(){return r.httpHandler},updateHttpClientConfig(e,t){r.httpHandler?.updateHttpClientConfig(e,t)},httpHandlerConfigs(){return r.httpHandler.httpHandlerConfigs()}}),Vz=r=>({httpHandler:r.httpHandler()}),ZE="content-length";function $z(r){return e=>async t=>{const n=t.request;if(aa.isInstance(n)){const{body:i,headers:a}=n;if(i&&Object.keys(a).map(s=>s.toLowerCase()).indexOf(ZE)===-1)try{const s=r(i);n.headers={...n.headers,[ZE]:String(s)}}catch{}}return e({...t,request:n})}}const zz={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},Hz=r=>({applyToStack:e=>{e.add($z(r.bodyLengthChecker),zz)}}),kl=r=>encodeURIComponent(r).replace(/[!'()*]/g,Gz),Gz=r=>`%${r.charCodeAt(0).toString(16).toUpperCase()}`;function jz(r){const e=[];for(let t of Object.keys(r).sort()){const n=r[t];if(t=kl(t),Array.isArray(n))for(let i=0,a=n.length;i<a;i++)e.push(`${t}=${kl(n[i])}`);else{let i=t;(n||typeof n=="string")&&(i+=`=${kl(n)}`),e.push(i)}}return e.join("&")}const qz=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],Wz=["TimeoutError","RequestTimeout","RequestTimeoutException"],Qz=[500,502,503,504],Yz=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],Xz=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],Jz=r=>r?.$retryable!==void 0,Kz=r=>r.$metadata?.clockSkewCorrected,Zz=r=>{const e=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);return r&&r instanceof TypeError?e.has(r.message):!1},kP=r=>r.$metadata?.httpStatusCode===429||qz.includes(r.name)||r.$retryable?.throttling==!0,rb=(r,e=0)=>Jz(r)||Kz(r)||r.name==="InvalidSignatureException"&&r.message?.includes("Signature expired")||Wz.includes(r.name)||Yz.includes(r?.code||"")||Xz.includes(r?.code||"")||Qz.includes(r.$metadata?.httpStatusCode||0)||Zz(r)||tH(r)||r.cause!==void 0&&e<=10&&rb(r.cause,e+1),eH=r=>{if(r.$metadata?.httpStatusCode!==void 0){const e=r.$metadata.httpStatusCode;return 500<=e&&e<=599&&!rb(r)}return!1};function tH(r){return r.code==="ERR_HTTP2_STREAM_ERROR"&&r.message.includes("NGHTTP2_REFUSED_STREAM")}const TP=20*1e3,e2=500,rH=1,nH="amz-sdk-invocation-id",iH="amz-sdk-request";function aH(r,e){if(oc.isInstance(r))for(const t of Object.keys(r.headers)){const n=t.toLowerCase();if(n==="retry-after"){const i=r.headers[t];let a=NaN;if(i.endsWith("GMT"))try{a=(dP(i).getTime()-Date.now())/1e3}catch(s){e?.trace?.("Failed to parse retry-after header"),e?.trace?.(s)}else i.match(/ GMT, ((\d+)|(\d+\.\d+))$/)?a=Number(i.match(/ GMT, ([\d.]+)$/)?.[1]):i.match(/^((\d+)|(\d+\.\d+))$/)?a=Number(i):Date.parse(i)>=Date.now()&&(a=(Date.parse(i)-Date.now())/1e3);return isNaN(a)?void 0:new Date(Date.now()+a*1e3)}else if(n==="x-amz-retry-after"){const i=r.headers[t],a=Number(i);if(isNaN(a)){e?.trace?.(`Failed to parse x-amz-retry-after=${i}`);return}return new Date(Date.now()+a)}}}const sH=r=>r instanceof Error?r:r instanceof Object?Object.assign(new Error,r):typeof r=="string"?new Error(r):new Error(`AWS SDK error wrapper for ${r}`);function oH(r){return e=>(t,n)=>async i=>{let a=await e.retryStrategy();const s=await e.maxAttempts();if(uH(a)){a=a;let o=await a.acquireInitialRetryToken((n.partition_id??"")+(n.__retryLongPoll?":longpoll":"")),l=new Error,u=0,c=0;const{request:f}=i,d=aa.isInstance(f);for(d&&(f.headers[nH]=SP());;)try{d&&(f.headers[iH]=`attempt=${u+1}; max=${s}`);const{response:h,output:g}=await t(i);return a.recordSuccess(o),g.$metadata.attempts=u+1,g.$metadata.totalRetryDelay=c,{response:h,output:g}}catch(h){const g=cH(h,e.logger);if(l=sH(h),d&&r(f))throw(n.logger instanceof lP?console:n.logger)?.warn("An error was encountered in a non-retryable streaming request."),l;try{o=await a.refreshRetryTokenForRetry(o,g)}catch{throw l.$metadata||(l.$metadata={}),l.$metadata.attempts=u+1,l.$metadata.totalRetryDelay=c,l}u=o.getRetryCount();const y=o.getRetryDelay();c+=(o?.$retryLog?.acquisitionDelay??0)+y,y>0&&await lH(y)}}else return a=a,a?.mode&&(n.userAgent=[...n.userAgent||[],["cfg/retry-mode",a.mode]]),a.retry(t,i)}}const lH=r=>new Promise(e=>setTimeout(e,r)),uH=r=>typeof r.acquireInitialRetryToken<"u"&&typeof r.refreshRetryTokenForRetry<"u"&&typeof r.recordSuccess<"u",cH=(r,e)=>{const t={error:r,errorType:dH(r)},n=aH(r.$response,e);return n&&(t.retryAfterHint=n),t},dH=r=>kP(r)?"THROTTLING":rb(r)?"TRANSIENT":eH(r)?"SERVER_ERROR":"CLIENT_ERROR",fH={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function hH(r){const e=oH(r);return t=>({applyToStack:n=>{n.add(e(t),fH)}})}class nb{static setTimeoutFn=(e,t)=>setTimeout(e,t);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(e){this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(e){let t;this.updateMeasuredRate();const n=e;if(n?.errorType==="THROTTLING"||kP(n?.error??e)){const s=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=s,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(s),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());const a=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(a)}getCurrentTimeInSeconds(){return Date.now()/1e3}async acquireTokenBucket(e){if(this.enabled){for(this.refillTokenBucket();e>this.availableTokens;){const t=(e-this.availableTokens)/this.fillRate*1e3;await new Promise(n=>nb.setTimeoutFn(n,t)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-e}}refillTokenBucket(){const e=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=e;return}const t=(e-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+t),this.lastTimestamp=e}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(e){return this.getPrecise(e*this.beta)}cubicSuccess(e){return this.getPrecise(this.scaleConstant*Math.pow(e-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(e){this.refillTokenBucket(),this.fillRate=Math.max(e,this.minFillRate),this.maxCapacity=Math.max(e,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){const e=this.getCurrentTimeInSeconds(),t=Math.floor(e*2)/2;if(this.requestCount++,t>this.lastTxRateBucket){const n=this.requestCount/(t-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(n*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=t}}getPrecise(e){return parseFloat(e.toFixed(8))}}class ki{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return ki.v2026?50:100}static throttlingDelay(){return ki.v2026?1e3:500}static cost(){return ki.v2026?14:5}static throttlingCost(){return ki.v2026?5:10}static modifiedCostType(){return ki.v2026?"THROTTLING":"TRANSIENT"}}class pH{x=ki.delay();computeNextBackoffDelay(e){const i=Math.random()*Math.min(this.x*2**e,TP);return Math.floor(i)}setDelayBase(e){this.x=e}}class t2{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(e,t,n,i){this.delay=e,this.count=t,this.cost=n,this.longPoll=i}getRetryCount(){return this.count}getRetryDelay(){return Math.min(TP,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var Bo;(function(r){r.STANDARD="standard",r.ADAPTIVE="adaptive"})(Bo||(Bo={}));const nf=3,gH=Bo.STANDARD,Pp={incompatible:1,attempts:2,capacity:3};class DA{mode=Bo.STANDARD;retryBackoffStrategy;capacity=e2;maxAttemptsProvider;baseDelay;constructor(e){typeof e=="number"?this.maxAttemptsProvider=async()=>e:typeof e=="function"?this.maxAttemptsProvider=e:e&&typeof e=="object"&&(this.maxAttemptsProvider=async()=>e.maxAttempts,this.baseDelay=e.baseDelay,this.retryBackoffStrategy=e.backoff),this.maxAttemptsProvider??=async()=>nf,this.baseDelay??=ki.delay(),this.retryBackoffStrategy??=new pH}async acquireInitialRetryToken(e){return new t2(ki.delay(),0,void 0,ki.v2026&&e.includes(":longpoll"))}async refreshRetryTokenForRetry(e,t){const n=await this.getMaxAttempts(),i=this.retryCode(e,t,n),a=i===0,s=e.isLongPoll?.();if(a||s){const o=t.errorType;this.retryBackoffStrategy.setDelayBase(o==="THROTTLING"?ki.throttlingDelay():this.baseDelay);const l=this.retryBackoffStrategy.computeNextBackoffDelay(e.getRetryCount());let u=l;if(t.retryAfterHint instanceof Date&&(u=Math.max(l,Math.min(t.retryAfterHint.getTime()-Date.now(),l+5e3))),a){const c=this.getCapacityCost(o);this.capacity-=c;const f=new t2(0,e.getRetryCount()+1,c,e.isLongPoll?.()??!1);return await new Promise(d=>setTimeout(d,u)),f.$retryLog.acquisitionDelay=u,f}else{const c=ki.v2026&&i===Pp.capacity&&s?u:0;c>0&&await new Promise(f=>setTimeout(f,c))}}throw new Error("No retry token available")}recordSuccess(e){this.capacity=Math.min(e2,this.capacity+(e.getRetryCost()??rH))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch{return console.warn(`Max attempts provider could not resolve. Using default of ${nf}`),nf}}retryCode(e,t,n){const i=e.getRetryCount()+1,a=this.isRetryableError(t.errorType)?0:Pp.incompatible,s=i<n?0:Pp.attempts,o=this.capacity>=this.getCapacityCost(t.errorType)?0:Pp.capacity;return a||s||o}getCapacityCost(e){return e===ki.modifiedCostType()?ki.throttlingCost():ki.cost()}isRetryableError(e){return e==="THROTTLING"||e==="TRANSIENT"}}class mH{mode=Bo.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(e,t){const{rateLimiter:n}=t??{};this.rateLimiter=n??new nb,this.standardRetryStrategy=t?new DA({maxAttempts:typeof e=="number"?e:3,...t}):new DA(e)}async acquireInitialRetryToken(e){const t=await this.standardRetryStrategy.acquireInitialRetryToken(e);return await this.rateLimiter.getSendToken(),t}async refreshRetryTokenForRetry(e,t){this.rateLimiter.updateClientSendingRate(t);const n=await this.standardRetryStrategy.refreshRetryTokenForRetry(e,t);return await this.rateLimiter.getSendToken(),n}recordSuccess(e){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(e)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}}const yH=(r,e)=>{const{retryStrategy:t,retryMode:n}=r,{defaultMaxAttempts:i=nf,defaultBaseDelay:a=ki.delay()}={},s=_s(r.maxAttempts??i);let o=t?Promise.resolve(t):void 0;const l=async()=>{const u=await s();return await _s(n)()===Bo.ADAPTIVE?new mH(s,{maxAttempts:u,baseDelay:a}):new DA({maxAttempts:u,baseDelay:a})};return Object.assign(r,{maxAttempts:s,retryStrategy:()=>o??=l()})},vH=hH(t$);ki.v2026||=typeof process=="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function Ds(r,e,t){r.__aws_sdk_context?r.__aws_sdk_context.features||(r.__aws_sdk_context.features={}):r.__aws_sdk_context={features:{}},r.__aws_sdk_context.features[e]=t}const AH=r=>e=>async t=>{if(!aa.isInstance(t.request))return e(t);const{request:n}=t,{handlerProtocol:i=""}=r.requestHandler.metadata||{};if(i.indexOf("h2")>=0&&!n.headers[":authority"])delete n.headers.host,n.headers[":authority"]=n.hostname+(n.port?":"+n.port:"");else if(!n.headers.host){let a=n.hostname;n.port!=null&&(a+=`:${n.port}`),n.headers.host=a}return e(t)},bH={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},wH=r=>({applyToStack:e=>{e.add(AH(r),bH)}}),xH=()=>(r,e)=>async t=>{try{const n=await r(t),{clientName:i,commandName:a,logger:s,dynamoDbDocumentClientOptions:o={}}=e,{overrideInputFilterSensitiveLog:l,overrideOutputFilterSensitiveLog:u}=o,c=l??e.inputFilterSensitiveLog,f=u??e.outputFilterSensitiveLog,{$metadata:d,...h}=n.output;return s?.info?.({clientName:i,commandName:a,input:c(t.input),output:f(h),metadata:d}),n}catch(n){const{clientName:i,commandName:a,logger:s,dynamoDbDocumentClientOptions:o={}}=e,{overrideInputFilterSensitiveLog:l}=o,u=l??e.inputFilterSensitiveLog;throw s?.error?.({clientName:i,commandName:a,input:u(t.input),error:n,metadata:n.$metadata}),n}},CH={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},SH=r=>({applyToStack:e=>{e.add(xH(),CH)}}),EH=r=>({applyToStack:e=>{}}),kH=(r,e)=>{if(!e||e.length===0)return r;const t=[];for(const n of e)for(const i of r)i.schemeId.split("#")[1]===n&&t.push(i);for(const n of r)t.find(({schemeId:i})=>i===n.schemeId)||t.push(n);return t};function TH(r){const e=new Map;for(const t of r)e.set(t.schemeId,t);return e}const FH=(r,e)=>(t,n)=>async i=>{const a=r.httpAuthSchemeProvider(await e.httpAuthSchemeParametersProvider(r,n,i.input)),s=r.authSchemePreference?await r.authSchemePreference():[],o=kH(a,s),l=TH(r.httpAuthSchemes),u=Ac(n),c=[];for(const f of o){const d=l.get(f.schemeId);if(!d){c.push(`HttpAuthScheme \`${f.schemeId}\` was not enabled for this service.`);continue}const h=d.identityProvider(await e.identityProviderConfigProvider(r));if(!h){c.push(`HttpAuthScheme \`${f.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties:g={},signingProperties:y={}}=f.propertiesExtractor?.(r,n)||{};f.identityProperties=Object.assign(f.identityProperties||{},g),f.signingProperties=Object.assign(f.signingProperties||{},y),u.selectedHttpAuthScheme={httpAuthOption:f,identity:await h(f.identityProperties),signer:d.signer};break}if(!u.selectedHttpAuthScheme)throw new Error(c.join(`
|
|
3109
3109
|
`));return t(i)},IH={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},PH=(r,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:t})=>({applyToStack:n=>{n.addRelativeTo(FH(r,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:t}),IH)}}),DH=r=>e=>{throw e},RH=(r,e)=>{},OH=r=>(e,t)=>async n=>{if(!aa.isInstance(n.request))return e(n);const a=Ac(t).selectedHttpAuthScheme;if(!a)throw new Error("No HttpAuthScheme was selected: unable to sign request");const{httpAuthOption:{signingProperties:s={}},identity:o,signer:l}=a,u=await e({...n,request:await l.sign(n.request,o,s)}).catch((l.errorHandler||DH)(s));return(l.successHandler||RH)(u.response,s),u},BH={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},MH=r=>({applyToStack:e=>{e.addRelativeTo(OH(),BH)}}),af=r=>{if(typeof r=="function")return r;const e=Promise.resolve(r);return()=>e};class _H{authSchemes=new Map;constructor(e){for(const t in e){const n=e[t];n!==void 0&&this.authSchemes.set(t,n)}}getIdentityProvider(e){return this.authSchemes.get(e)}}class NH{async sign(e,t,n){return e}}const LH=r=>function(t){return FP(t)&&t.expiration.getTime()-Date.now()<r},UH=3e5,VH=LH(UH),FP=r=>r.expiration!==void 0,$H=(r,e,t)=>{if(r===void 0)return;const n=typeof r!="function"?async()=>Promise.resolve(r):r;let i,a,s,o=!1;const l=async u=>{a||(a=n(u));try{i=await a,s=!0,o=!1}finally{a=void 0}return i};return e===void 0?async u=>((!s||u?.forceRefresh)&&(i=await l(u)),i):async u=>((!s||u?.forceRefresh)&&(i=await l(u)),o?i:t(i)?(e(i)&&await l(u),i):(o=!0,i))},zH=void 0;function HH(r){return r===void 0?!0:typeof r=="string"&&r.length<=50}function GH(r){const e=af(r.userAgentAppId??zH),{customUserAgent:t}=r;return Object.assign(r,{customUserAgent:typeof t=="string"?[[t]]:t,userAgentAppId:async()=>{const n=await e();if(!HH(n)){const i=r.logger?.constructor?.name==="NoOpLogger"||!r.logger?console:r.logger;typeof n!="string"?i?.warn("userAgentAppId must be a string or undefined."):n.length>50&&i?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return n}})}const jH={partitions:[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-east-2":{description:"Asia Pacific (Taipei)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"aws-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"aws-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}]};let qH=jH;const WH=r=>{const{partitions:e}=qH;for(const n of e){const{regions:i,outputs:a}=n;for(const[s,o]of Object.entries(i))if(s===r)return{...a,...o}}for(const n of e){const{regionRegex:i,outputs:a}=n;if(new RegExp(i).test(r))return{...a}}const t=e.find(n=>n.id==="aws");if(!t)throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...t.outputs}},QH=/\d{12}\.ddb/;async function YH(r,e,t){if(t.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor"&&Ds(r,"PROTOCOL_RPC_V2_CBOR","M"),typeof e.retryStrategy=="function"){const a=await e.retryStrategy();if(typeof a.mode=="string")switch(a.mode){case Bo.ADAPTIVE:Ds(r,"RETRY_MODE_ADAPTIVE","F");break;case Bo.STANDARD:Ds(r,"RETRY_MODE_STANDARD","E");break}}if(typeof e.accountIdEndpointMode=="function"){const a=r.endpointV2;switch(String(a?.url?.hostname).match(QH)&&Ds(r,"ACCOUNT_ID_ENDPOINT","O"),await e.accountIdEndpointMode?.()){case"disabled":Ds(r,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":Ds(r,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":Ds(r,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const i=r.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){const a=i;a.accountId&&Ds(r,"RESOLVED_ACCOUNT_ID","T");for(const[s,o]of Object.entries(a.$source??{}))Ds(r,s,o)}}const r2="user-agent",Yy="x-amz-user-agent",n2=" ",Xy="/",XH=/[^!$%&'*+\-.^_`|~\w]/g,JH=/[^!$%&'*+\-.^_`|~\w#]/g,i2="-",KH=1024;function ZH(r){let e="";for(const t in r){const n=r[t];if(e.length+n.length+1<=KH){e.length?e+=","+n:e+=n;continue}break}return e}const eG=r=>(e,t)=>async n=>{const{request:i}=n;if(!aa.isInstance(i))return e(n);const{headers:a}=i,s=t?.userAgent?.map(Dp)||[],o=(await r.defaultUserAgentProvider()).map(Dp);await YH(t,r,n);const l=t;o.push(`m/${ZH(Object.assign({},t.__smithy_context?.features,l.__aws_sdk_context?.features))}`);const u=r?.customUserAgent?.map(Dp)||[],c=await r.userAgentAppId();c&&o.push(Dp(["app",`${c}`]));const f=[].concat([...o,...s,...u]).join(n2),d=[...o.filter(h=>h.startsWith("aws-sdk-")),...u].join(n2);return r.runtime!=="browser"?(d&&(a[Yy]=a[Yy]?`${a[r2]} ${d}`:d),a[r2]=f):a[Yy]=f,e({...n,request:i})},Dp=r=>{const e=r[0].split(Xy).map(s=>s.replace(XH,i2)).join(Xy),t=r[1]?.replace(JH,i2),n=e.indexOf(Xy),i=e.substring(0,n);let a=e.substring(n+1);return i==="api"&&(a=a.toLowerCase()),[i,a,t].filter(s=>s&&s.length>0).reduce((s,o,l)=>{switch(l){case 0:return o;case 1:return`${s}/${o}`;default:return`${s}#${o}`}},"")},tG={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},rG=r=>({applyToStack:e=>{e.add(eG(r),tG)}}),nG=({serviceId:r,clientVersion:e})=>async t=>{const n=typeof window<"u"?window.navigator:void 0,i=n?.userAgent??"",a=n?.userAgentData?.platform??a2.os(i)??"other",s=void 0,o=n?.userAgentData?.brands??[],l=o[o.length-1],u=l?.brand??a2.browser(i)??"unknown",c=l?.version??"unknown",f=[["aws-sdk-js",e],["ua","2.1"],[`os/${a}`,s],["lang/js"],["md/browser",`${u}_${c}`]];r&&f.push([`api/${r}`,e]);const d=await t?.userAgentAppId?.();return d&&f.push([`app/${d}`]),f},a2={os(r){if(/iPhone|iPad|iPod/.test(r))return"iOS";if(/Macintosh|Mac OS X/.test(r))return"macOS";if(/Windows NT/.test(r))return"Windows";if(/Android/.test(r))return"Android";if(/Linux/.test(r))return"Linux"},browser(r){if(/EdgiOS|EdgA|Edg\//.test(r))return"Microsoft Edge";if(/Firefox\//.test(r))return"Firefox";if(/Chrome\//.test(r))return"Chrome";if(/Safari\//.test(r))return"Safari"}},IP=(r,e=!1)=>{if(e){for(const t of r.split("."))if(!IP(t))return!1;return!0}return!(!nm(r)||r.length<3||r.length>63||r!==r.toLowerCase()||mP(r))},s2=":",iG="/",aG=r=>{const e=r.split(s2);if(e.length<6)return null;const[t,n,i,a,s,...o]=e;if(t!=="arn"||n===""||i===""||o.join(s2)==="")return null;const l=o.map(u=>u.split(iG)).flat();return{partition:n,service:i,region:a,accountId:s,resourceId:l}},PP={isVirtualHostableS3Bucket:IP,parseArn:aG,partition:WH};tb.aws=PP;const sG=(r,e,t)=>{let n,i,a,s=!1;const o=async()=>{i||(i=r());try{n=await i,a=!0,s=!1}finally{i=void 0}return n};return async l=>((!a||l?.forceRefresh)&&(n=await o()),n)},o2=new Set,oG=(r,e=nm)=>{if(!o2.has(r)&&!e(r))if(r==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw new Error(`Region not accepted: region="${r}" is not a valid hostname component.`);else o2.add(r)},DP=r=>typeof r=="string"&&(r.startsWith("fips-")||r.endsWith("-fips")),lG=r=>DP(r)?["fips-aws-global","aws-fips"].includes(r)?"us-east-1":r.replace(/fips-(dkr-|prod-)?|-fips/,""):r,uG=r=>{const{region:e,useFipsEndpoint:t}=r;if(!e)throw new Error("Region is missing");return Object.assign(r,{region:async()=>{const n=typeof e=="function"?await e():e,i=lG(n);return oG(i),i},useFipsEndpoint:async()=>{const n=typeof e=="string"?e:await e();return DP(n)?!0:typeof t!="function"?Promise.resolve(!!t):t()}})},cG=["in-region","cross-region","mobile","standard","legacy"],dG=({defaultsMode:r}={})=>sG(async()=>{const e=typeof r=="function"?await r():r;switch(e?.toLowerCase()){case"auto":return Promise.resolve(fG()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(e?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${cG.join(", ")}, got ${e}`)}}),fG=()=>{const r=window?.navigator;if(r?.connection){const{effectiveType:e,rtt:t,downlink:n}=r?.connection;if(typeof e=="string"&&e!=="4g"||Number(t)>100||Number(n)<10)return!0}return r?.userAgentData?.mobile||typeof r?.maxTouchPoints=="number"&&r?.maxTouchPoints>1},hG=!1,pG=!1,gG=r=>({setRegion(e){r.region=e},region(){return r.region}}),mG=r=>({region:r.region()}),l2=r=>oc.isInstance(r)?r.headers?.date??r.headers?.Date:void 0,RP=r=>new Date(Date.now()+r),yG=(r,e)=>Math.abs(RP(e).getTime()-r)>=3e5,u2=(r,e)=>{const t=Date.parse(r);return yG(t,e)?t-Date.now():e},sf=(r,e)=>{if(!e)throw new Error(`Property \`${r}\` is not resolved for AWS SDK SigV4Auth`);return e},vG=async r=>{const e=sf("context",r.context),t=sf("config",r.config),n=e.endpointV2?.properties?.authSchemes?.[0],a=await sf("signer",t.signer)(n),s=r?.signingRegion,o=r?.signingRegionSet,l=r?.signingName;return{config:t,signer:a,signingRegion:s,signingRegionSet:o,signingName:l}};class AG{async sign(e,t,n){if(!aa.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const i=await vG(n),{config:a,signer:s}=i;let{signingRegion:o,signingName:l}=i;const u=n.context;if(u?.authSchemes?.length??!1){const[f,d]=u.authSchemes;f?.name==="sigv4a"&&d?.name==="sigv4"&&(o=d?.signingRegion??o,l=d?.signingName??l)}return n._preRequestSystemClockOffset=a.systemClockOffset,await s.sign(e,{signingDate:RP(a.systemClockOffset),signingRegion:o,signingService:l})}errorHandler(e){return t=>{const n=t,i=n.ServerTime??l2(n.$response);if(i){const a=sf("config",e.config),s=e._preRequestSystemClockOffset,o=u2(i,a.systemClockOffset);(o!==a.systemClockOffset||s!==void 0&&s!==o)&&n.$metadata&&(a.systemClockOffset=o,n.$metadata.clockSkewCorrected=!0)}throw t}}successHandler(e,t){const n=l2(e);if(n){const i=sf("config",t.config);i.systemClockOffset=u2(n,i.systemClockOffset)}}}class bG{format(e){const t=[];for(const a of Object.keys(e)){const s=Pl(a);t.push(Uint8Array.from([s.byteLength]),s,this.formatHeaderValue(e[a]))}const n=new Uint8Array(t.reduce((a,s)=>a+s.byteLength,0));let i=0;for(const a of t)n.set(a,i),i+=a.byteLength;return n}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":const t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":const n=new DataView(new ArrayBuffer(5));return n.setUint8(0,4),n.setInt32(1,e.value,!1),new Uint8Array(n.buffer);case"long":const i=new Uint8Array(9);return i[0]=5,i.set(e.value.bytes,1),i;case"binary":const a=new DataView(new ArrayBuffer(3+e.value.byteLength));a.setUint8(0,6),a.setUint16(1,e.value.byteLength,!1);const s=new Uint8Array(a.buffer);return s.set(e.value,3),s;case"string":const o=Pl(e.value),l=new DataView(new ArrayBuffer(3+o.byteLength));l.setUint8(0,7),l.setUint16(1,o.byteLength,!1);const u=new Uint8Array(l.buffer);return u.set(o,3),u;case"timestamp":const c=new Uint8Array(9);return c[0]=8,c.set(ib.fromNumber(e.value.valueOf()).bytes,1),c;case"uuid":if(!wG.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const f=new Uint8Array(17);return f[0]=9,f.set(hP(e.value.replace(/\-/g,"")),1),f}}}var c2;(function(r){r[r.boolTrue=0]="boolTrue",r[r.boolFalse=1]="boolFalse",r[r.byte=2]="byte",r[r.short=3]="short",r[r.integer=4]="integer",r[r.long=5]="long",r[r.byteArray=6]="byteArray",r[r.string=7]="string",r[r.timestamp=8]="timestamp",r[r.uuid=9]="uuid"})(c2||(c2={}));const wG=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class ib{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776e3||e<-9223372036854776e3)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);const t=new Uint8Array(8);for(let n=7,i=Math.abs(Math.round(e));n>-1&&i>0;n--,i/=256)t[n]=i;return e<0&&d2(t),new ib(t)}valueOf(){const e=this.bytes.slice(0),t=e[0]&128;return t&&d2(e),parseInt(xo(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function d2(r){for(let e=0;e<8;e++)r[e]^=255;for(let e=7;e>-1&&(r[e]++,r[e]===0);e--);}const xG="X-Amz-Algorithm",CG="X-Amz-Credential",OP="X-Amz-Date",SG="X-Amz-SignedHeaders",EG="X-Amz-Expires",BP="X-Amz-Signature",MP="X-Amz-Security-Token",_P="authorization",NP=OP.toLowerCase(),kG="date",TG=[_P,NP,kG],FG=BP.toLowerCase(),RA="x-amz-content-sha256",IG=MP.toLowerCase(),PG={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},DG=/^proxy-/,RG=/^sec-/,Jy="AWS4-HMAC-SHA256",OG="AWS4-HMAC-SHA256-PAYLOAD",BG="UNSIGNED-PAYLOAD",MG=50,LP="aws4_request",_G=3600*24*7,NG=({query:r={}})=>{const e=[],t={};for(const n of Object.keys(r)){if(n.toLowerCase()===FG)continue;const i=kl(n);e.push(i);const a=r[n];typeof a=="string"?t[i]=`${i}=${kl(a)}`:Array.isArray(a)&&(t[i]=a.slice(0).reduce((s,o)=>s.concat([`${i}=${kl(o)}`]),[]).sort().join("&"))}return e.sort().map(n=>t[n]).filter(n=>n).join("&")},LG=r=>UG(r).toISOString().replace(/\.\d{3}Z$/,"Z"),UG=r=>typeof r=="number"?new Date(r*1e3):typeof r=="string"?Number(r)?new Date(Number(r)*1e3):new Date(r):r;class VG{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:e,credentials:t,region:n,service:i,sha256:a,uriEscapePath:s=!0}){this.service=i,this.sha256=a,this.uriEscapePath=s,this.applyChecksum=typeof e=="boolean"?e:!0,this.regionProvider=_s(n),this.credentialProvider=_s(t)}createCanonicalRequest(e,t,n){const i=Object.keys(t).sort();return`${e.method}
|
|
3110
3110
|
${this.getCanonicalPath(e)}
|
|
3111
3111
|
${NG(e)}
|
|
@@ -3149,7 +3149,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
3149
3149
|
}
|
|
3150
3150
|
}
|
|
3151
3151
|
`;class gY{constructor(e){this.resource=e}getId(){return this.resource.id}getName(){return this.resource.name}getCreatedDate(){return new Date(this.resource.createdAt)}getUpdatedDate(){return new Date(this.resource.updatedAt)}getGlobalPropertyConfiguration(){return{id:this.resource.globalPropertyConfiguration.id,name:this.resource.globalPropertyConfiguration.name}}async applyToBundle(e){const n=(await Le.getShadowGraphqlClient().query({query:D9,variables:{ids:[this.resource.globalPropertyConfiguration.id]}})).data.globalPropertyConfigurations[0];await e.setGlobalPropertyConfiguration(n),await e.applyGlobalPropertyState({aspects:this.resource.aspectValues??[]})}}const mY=async(r,e)=>{const t=gM(e?.assets?.metadata||!1),n={ids:r};console.log("[getWorkflowsInternal] Requesting workflows.",{url:`${ls.getServerUrl()}/graphql`,variables:JSON.stringify(n)}),console.log(`[getWorkflowsInternal] Query:
|
|
3152
|
-
${X2(t)}`);const i=await Le.getShadowGraphqlClient().query({query:t,errorPolicy:"all",variables:n,context:{logRequestHeaders:!0}});if(i.error)throw console.log("[getWorkflowsInternal] Response errored."),i.error;if(i.errors)throw i.errors.forEach(s=>console.error(s)),new Error("Unable to read workflows. Consult GraphQL errors.");if(!i.data.workflows||i.data.workflows.length!==r.length)throw new Error(`Unable to read workflows: ${i.errors??"Length mismatch in response"}`);const a=Ao(i.data.workflows);return a.forEach(s=>{s.finalizeStepConfig||(s.finalizeStepConfig={}),s.finalizeStepConfig.termsMarkdown=s.finalizeStepConfig.termsMarkdown||s.partner.termsMarkdown}),a},yY=async(r,e)=>{const n=(await e).find(i=>i.id===r);if(!n)throw new Error(`Workflow not found: ${r}`);return n},fw=async(r,e)=>{const t=r.map(o=>Af.get({id:o,options:e})),n=r.filter((o,l)=>t[l]===void 0);if(n.length===0)return Promise.all(t);const i=mY(n,e),a=n.map(o=>Af.set({id:o,options:e},yY(o,i))),s=t.filter(o=>o!==void 0);return await Promise.all(s.concat(a))},sD=async(r,e)=>(await fw([r],e))[0],oD=async r=>{const e=await Le.getShadowGraphqlClient().query({query:PT,variables:{ids:r},errorPolicy:"all",fetchPolicy:"no-cache"});return e.errors&&console.error(e.errors),e.data.integrationProducts||[]};class vY{constructor(e){this.activeIntegration=void 0,this.updateTransactionState=async t=>{try{return Le.getShadowGraphqlClient().mutate({...t,mutation:eM})}catch(n){throw console.error(n),new fo("Critical - Unable to synchronize workflow state with server.")}},this.options=e,this.options.applicationKey&&oT(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 44.8.0"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(e){ls.setHubUrl(e.hubUrl),ls.setServerUrl(e.serverUrl),ls.setServicesApiUrl(e.servicesApiUrl),this.marketplaceThemeInstallId=e.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=e.marketplaceThemeInstallConfigurationId,this.userPoolClientId=e.userPoolClientId,this.userPoolRegion=e.userPoolRegion,this.spiffRegion=e.spiffRegion,e.bearerAuthenticationToken&&uT(e.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Dd.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getVersion(){return"44.8.0"}getAssetManager(){return Un}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!bB())throw new Error("Application key required to use Flow Service.");return new nP}async getCurrencyContext(e){const n=(await this.getIntegration()).partner.currencyCode,a=await Le.getShadowGraphqlClient().query({query:wM,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:n,to:e}}),{rateFrom:s,rateTo:o}=a.data.currencyConversion;return new aD(s,o,n,e)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=lD(this.options.applicationKey),this.activeIntegration}async canUseAddon(e){try{return(await this.getIntegration()).partner.activeAddons?.includes(e)??!1}catch(t){return console.error(t),!1}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(e){const t=wr.getMap("transactionCustomerIds");t?.has(e)&&(t.delete(e),wr.setMap("transactionCustomerIds",t))}async customerHasBundleTemplates(e){const i=(await Le.getShadowGraphqlClient().query({query:Ly,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;return i.id?i.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(e){const t=this.customer?.stakeholders?.find(n=>n.transaction?.id===e);if(t)return t.type}async getOrCreateCustomer(e){this.customer=void 0;const t=Le.getShadowGraphqlClient(),i=(await t.query({query:Ly,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;if(!i.id){const o=(await t.mutate({mutation:YV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:e}}})).data?.customerCreate;if(!o)throw new Error("Unable to create customer.");return this.storeCustomer(o),this.customer=o,{customer:o,isAuthenticated:!1}}this.storeCustomer(i);const a=await this.reloadLoggedInCustomer();return{customer:this.customer||i,isAuthenticated:a}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const e=localStorage.getItem("last-refreshed-cognito-tokens"),t=localStorage.getItem("cognito-tokens"),n=localStorage.getItem("cognito-email");if(!e||!t||!n)return!1;const i=JSON.parse(t),a=new Date().getTime()/1e3;if(!i.ExpiresIn||i.ExpiresIn<a-parseInt(e)){const u=await Dd.refreshTokens();if(u?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),i.AccessToken=u.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(i));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=localStorage.getItem("customer-login-token");s&&A0(s);const l=(await Le.getShadowGraphqlClient().query({query:Ly,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:n}})).data.customer;return l.id?(this.customer=l,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(e){await Le.getShadowGraphqlClient().mutate({mutation:XV,variables:{emailAddress:e}}),await Dd.generateCode(e)}async verifyCode(e,t){const n=(await this.getIntegration()).partner.id||"",i=await Dd.verifyCode(e,t,n);if(i?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(i.AuthenticationResult)),localStorage.setItem("cognito-email",e);const s=(await Le.getShadowGraphqlClient().mutate({mutation:JV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e,verificationCode:t}})).data?.customerVerifyCode;if(!s?.id)throw new Error("Failed to get customer.");return this.customer=s,s.loginToken&&(localStorage.setItem("customer-login-token",s.loginToken),A0(s.loginToken)),!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),localStorage.removeItem("customer-login-token"),A0(""),this.clearCustomer()}async loggedInBearerToken(){const e=localStorage.getItem("last-refreshed-cognito-tokens"),t=localStorage.getItem("cognito-tokens");if(!e||!t)throw new Error("No token data in storage.");const n=JSON.parse(t),i=new Date().getTime()/1e3,a=!n?.AccessToken||Cg(n.AccessToken);if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(e)||a){const s=await Dd.refreshTokens();if(s?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=s.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!n.AccessToken)throw new Error("No bearer token in storage.");return n.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await Le.getShadowGraphqlClient().query({query:KV,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(e,t,n,i){const s=(await Le.getShadowGraphqlClient().mutate({mutation:_9(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:e,initialMetadata:t?Object.entries(t).map((c,f)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,activationId:i,test:n?.test},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!s?.id)throw new Error("Unable to create bundle");const o=wr.getMap("bundlePartnerIds")||new Map;o.set(s.id,s.partner.id),wr.setMap("bundlePartnerIds",o);const l=wr.getMap("bundleOwnerIds")||new Map;l.set(s.id,s.bundleOwnerId),wr.setMap("bundleOwnerIds",l);const u=new HE(this,s,void 0,void 0,s.bundleOwnerId,{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts});return await u.getInitializationPromise(),u}async getExistingBundle(e,t,n,i,a){const o=wr.getMap("bundleOwnerIds")?.get(e),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const v=Object.entries(localStorage).find(([x,S])=>x.startsWith("CognitoIdentityServiceProvider")&&x.endsWith("idToken"))?.[0]||"",A=localStorage.getItem(v);A&&!Cg(A)&&(l.Authorization=`Bearer ${A}`)}const u={bundleOwnerId:o,...l,...i?.graphql?.additionalHeaders},c=await Le.getShadowGraphqlClient().query({query:R9(i?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:e},fetchPolicy:"no-cache",context:{headers:u}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${e}`);const f=c.data?.bundles[0],d=wr.getMap("bundlePartnerIds")||new Map;d.set(f.id,f.partner.id),wr.setMap("bundlePartnerIds",d);const h=new HE(this,f,t,n,o,{additionalHeaders:i?.graphql?.additionalHeaders,eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:i?.readonly},a);return await h.getInitializationPromise(),h}async duplicateBundle(e,t,n,i){const s={...await dD(e),...i?.graphql?.additionalHeaders},l=(await Le.getShadowGraphqlClient().mutate({mutation:N9(),variables:{id:e,template:t,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:n,test:i?.test},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const u=wr.getMap("bundlePartnerIds")||new Map;u.set(l.id,l.partner.id),wr.setMap("bundlePartnerIds",u);const c=wr.getMap("bundleOwnerIds")||new Map;return c.set(l.id,l.bundleOwnerId),wr.setMap("bundleOwnerIds",c),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(e){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:t,...n}=e;return(await Le.getShadowGraphqlClient().query({query:Q9(t??!1),variables:{...n,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getTemplatesForCustomer(e){if(!this.customer?.id)throw new Error("Customer not authenticated.");const t=await Le.getShadowGraphqlClient().query({query:pY,variables:{...e,customerId:this.customer.id},fetchPolicy:"no-cache"});return{total:t.data.globalPropertyTemplatesFeed.total,items:t.data.globalPropertyTemplatesFeed.items.map(n=>new gY(n))}}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const e=await Le.getShadowGraphqlClient().query({query:O9,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!e.data?.customers||e.data.customers.length===0)throw new Error("Unable to find customer.");const n=e.data.customers[0].bundleStakeholders||[],i=wr.getMap("bundlePartnerIds")||new Map;return n.forEach(a=>{a.bundle?.id&&a.bundle.partner?.id&&i.set(a.bundle.id,a.bundle.partner.id)}),wr.setMap("bundlePartnerIds",i),n}async getWorkflowExperience(e,t){if(!e)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const n=await this.getWorkflowExperiences([e],e.graphql),i=n[0],a=i.getWorkflow();return t&&!a&&console.error("No workflow instantiated when trying to create preview service."),t&&a&&await i.getWorkflowManager().injectIntoPreviewService(t(a)),n[0]}async getWorkflowExperiences(e,t,n,i){if(e.length===0)throw new fo("No options provided!");const a=e.map((U,$)=>({option:U,index:$})),s=a.filter(U=>U.option.type==="transaction"),o=a.filter(U=>U.option.type==="integration"||U.option.type==="external"||U.option.type==="blank"),l=50,u=xA(s,l),c=xA(o,l);let f=0;const d=Le.getShadowGraphqlClient(),h=async U=>{if(U.length===0)return[];const $=U.map(K=>K.option.transactionId),z=await d.query({query:Z3,variables:{ids:$},errorPolicy:"all",fetchPolicy:"no-cache"}),Q=z.data.transactions;if(f=f+Q.length,i&&i(f,s.length),Q.length!==U.length){const K=z.errors?.[0]?.message||"Unknown error";throw new fo(`Not all transactions were found: ${K}`)}return!this.activeIntegration&&Q[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(Q[0].integrationProduct.integration)),Q.map((K,le)=>({transaction:K,workflowId:K.workflowId,readOnly:U.find(he=>he.option.transactionId===K.id)?.option.readOnly??!1,index:U[le].index}))},g=async U=>{if(U.length===0)return[];const $=await d.mutate({mutation:K3,variables:{inputs:U.map(Q=>({integrationProductId:Q.option.type==="integration"?Q.option.integrationProductId:void 0,externalIntegrationId:Q.option.type==="external"?Q.option.externalIntegrationId:void 0,externalProductId:Q.option.type==="external"?Q.option.externalProductId:void 0,workflowId:Q.option.workflowId,designName:Q.option.designName,claim:!0,quantity:Q.option.quantity,recipient:Q.option.recipient,parentTransactionId:Q.option.parentTransactionId})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.getCreateTransactionContext(U,t)}),z=$.data?.transactionCreateMany;if(!z||z.length===0){const Q=$.errors?.[0]?.message||"Unknown error";throw new fo(`Failed to create transactions: ${Q}`)}return f=f+z.length,i&&i(f,s.length),z.map((Q,K)=>({transaction:Q,workflowId:Q.workflowId,readOnly:!1,index:U[K].index}))},y=(await Promise.all([...u.map(h),...c.map(g)])).flat();let v=[...new Set(y.map(U=>U.transaction.integrationProductId))].filter(U=>!!U);v=v.filter(U=>!!U);let A=[...new Set(y.map(U=>U.workflowId))].filter(U=>!!U);A=A.filter(U=>!!U);const[x,S]=await Promise.all([(async()=>v.length>0?await oD(v):[])(),(async()=>A.length>0?await fw(A,t):[])()]),F=new Map(x.map(U=>[U.id,U])),E=new Map(S.map(U=>[U.id,U])),R=y.map(async U=>{const{transaction:$,workflowId:z,readOnly:Q,index:K}=U,le=z?E.get(z):void 0,he=e[K];if($.integrationProductId){const ue=F.get($.integrationProductId);$.integrationProduct=ue,$.product=ue?.product,$.integrationProduct||console.error("failed to find transaction's product")}const Me=wr.getMap("transactionOwnerIds")||new Map;!Me.get($.id)&&$.transactionOwnerId&&(Me.set($.id,$.transactionOwnerId),wr.setMap("transactionOwnerIds",Me));const De=Me.get($.id)||void 0,Pe=new ZV({onMutate:()=>({context:{transactionOwnerId:De,bundleOwnerId:t?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:De,bundleOwnerId:t?.bundleOwnerId}})}),re={workflow:le,transaction:$,singleVariantsRenderable:he?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:Q?async()=>{throw new an("State mutation is forbidden in read only mode!")}:async ue=>this.updateTransactionState({...ue,context:{transactionOwnerId:De,bundleOwnerId:t?.bundleOwnerId}}),graphQlClient:()=>Pe,readOnly:Q,isReloadedTransaction:he.type==="transaction"};if(he.type==="transaction"&&$.workflowState){const ue=JSON.parse($.workflowState);await gA(ue),re.reloadedState=ue}else if(!Q&&he.workflowState){const ue=JSON.parse(he.workflowState);await gA(ue),re.reloadedState=ue}return re.delayWorkflowStateSync=!0,{experienceOptions:re,index:K,options:he}}),W=(await Promise.all(R)).sort((U,$)=>U.index-$.index);let Y=[],ae=[];for(const U of W){const{experienceOptions:$,options:z}=U,Q=new q1(this,$);await Q.getWorkflowManager().getInitializationPromise(),n&&n(),z.type!=="transaction"&&this.customer&&ae.push(Q),Y=[...Y,Q],Q.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}if(ae.length>0){const U=this.customer.emailAddress,$=ae.map(K=>K.getTransaction().id),Q=(await d.mutate({mutation:CV,variables:{ids:$,details:{emailAddress:U},type:"Owner"},errorPolicy:"all"})).data?.transactionsAddStakeholder;if(Q&&Q?.length>0){const K=Q[0].stakeholders?.find(le=>le.customer?.emailAddress===U);if(K?.customer)for(const le of ae)le.assignCustomerInternal(K.customer)}}return Y}getCreateTransactionContext(e,t){const n=e.find(s=>s.option.parentTransactionId)?.option.parentTransactionId;if(!n&&!t?.bundleOwnerId)return;const i=wr.getMap("transactionOwnerIds")||new Map,a=n?i.get(n):void 0;return{...a?{transactionOwnerId:a}:{},...t?.bundleOwnerId?{bundleOwnerId:t.bundleOwnerId}:{}}}storeCustomer(e){const t=wr.getMap("partnerCustomerIds")||new Map;t.set(e.partner.id,e.id),wr.setMap("partnerCustomerIds",t)}async getIntegrationProductById(e,t){const a=(await Le.getShadowGraphqlClient().query({query:oM(t),variables:{ids:[e]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!a||a.length===0||!a[0]?.id)throw new Error("Integration product not found.");return new EA(a[0])}async getIntegrationProductFromExternalIds(e,t,n){const s=(await Le.getShadowGraphqlClient().query({query:lM(n),variables:{externalProductId:t,externalIntegrationId:e},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!s?.id)throw new Error("Integration product not found.");return new EA(s)}async getIntegrationProduct(e){return e.type==="integration"?this.getIntegrationProductById(e.integrationProductId):this.getIntegrationProductFromExternalIds(e.externalIntegrationId,e.externalProductId)}async getShareActionsForTransaction(e){const n=(wr.getMap("transactionOwnerIds")||new Map).get(e)||void 0,i=await Le.getShadowGraphqlClient().query({query:aM,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:e},context:{transactionOwnerId:n}});if(!i.data.transactions||i.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${e}`);return i.data.transactions[0].transactionShareActions}async placeOrder(e){const t=await Le.getShadowGraphqlClient().mutate({mutation:bM,variables:{orderItems:e}});if(t.errors)throw new Error(t.errors[0].message);if(!t.data)throw new Error("Failed to create order: No order data in response.");return{id:t.data.orderCreate.id,internalId:t.data.orderCreate.internalId}}}const lD=async(r,e)=>(await Le.getShadowGraphqlClient().query({query:yM,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r},skipIntegrationCheck:!0},variables:{themeConfigurationId:e}})).data.currentIntegration,AY=async r=>{const t=await Le.getShadowGraphqlClient().query({query:iM,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(t.data.transactions.length!==0)return t.data.transactions[0]},bY=async(r,e)=>(await Le.getShadowGraphqlClient().query({query:mM,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:e}})).data?.marketplaceThemeInstallConfiguration,wY=async r=>(await Le.getShadowGraphqlClient().query({query:AM,errorPolicy:"all",variables:{id:r}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,xY=async r=>(await Le.getShadowGraphqlClient().query({query:vM,errorPolicy:"all",variables:{id:r}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration,uD=async(r,e)=>(await Le.getShadowGraphqlClient().query({query:FM(!!e),errorPolicy:"all",variables:{id:r,productIds:e}})).data?.activation,CY=async r=>(await uD(r))?.marketplaceThemeInstallConfiguration;async function cD(){const r={};try{const e=await this.loggedInBearerToken();r.Authorization=`Bearer ${e}`}catch{const n=Object.entries(localStorage).find(([a,s])=>a.startsWith("CognitoIdentityServiceProvider")&&a.endsWith("idToken"))?.[0]||"",i=localStorage.getItem(n);i&&!Cg(i)&&(r.Authorization=`Bearer ${i}`)}return r}async function dD(r){const t=wr.getMap("bundleOwnerIds")?.get(r),n=await cD();return{bundleOwnerId:t,...n}}async function SY(r){const t=wr.getMap("transactionOwnerIds")?.get(r),n=await cD();return{transactionOwnerId:t,...n}}const EY=async r=>{const e=await dD(r),t=await Le.getShadowGraphqlClient().mutate({mutation:nV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r},context:{headers:e}});if(t.data?.bundleDelete!==r)throw new Error(`Failed to delete bundle: ${t.errors}`)},kY=async r=>{const e=await SY(r),t=await Le.getShadowGraphqlClient().mutate({mutation:iV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[r]},context:{headers:e}});if(!t.data?.transactions||t.data.transactions.length!==1||t.data.transactions[0].id!==r)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(t.errors)}`);return t.data.transactions[0].bundle?.id};function fD(r,e,t,n){const i=t.width*r.zoom,a=t.height*r.zoom;if(n){const s=Math.max(e.width/t.width,e.height/t.height),o=Math.max(s,r.zoom),l=t.width*o,u=t.height*o;return{...r,x:Mp(r.x,e.width-l,0),y:Mp(r.y,e.height-u,0),zoom:o}}return{...r,x:Mp(r.x,-i,e.width),y:Mp(r.y,-a,e.height)}}function Mp(r,e,t){return Math.min(Math.max(r,e),t)}class hD{constructor(e,t){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=v1(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.onRotationChangeListeners=[],this.forceImageCover=e,this.initialZoom=t,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(e,t){t&&e.addStepSpecificStorageCallback(async n=>{if(n){const i=n;if(i.currentFrameSources){let a=!1;for(let s=0;s<i.currentFrameSources.length;s++){const o=i.currentFrameSources[s],l=await Zf(o),u=this.frameData?this.frameData[s]:void 0;wf(l,u)||(this.frameData||(this.frameData=new Array(i.currentFrameSources.length)),this.frameData[s]=l,a=!0)}a&&(this.onFrameDataChangeListeners.forEach(s=>s(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},t),this.workflowManager=e,this.stepName=t}setTargetElements(e){this.targetElements=e}getFrameData(){return this.frameData}setFrameData(e){if(!e){this.frameData=void 0;return}e.forEach((t,n)=>{const i=Uu.get(t);i&&(this.frameData||(this.frameData=new Array(e.length)),this.frameData[n]=i)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const e=Wg(this.imageData.svg,this.imageData.colors||{},!1);return jg(e)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(e){this.offsets=e}setZoom(e,t,n,i){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const a=this.frameData.map((s,o)=>{const l=(t[o]-this.offsets[o].x)/this.offsets[o].zoom,u=(n[o]-this.offsets[o].y)/this.offsets[o].zoom,c=t[o]-l*e[o],f=n[o]-u*e[o];return{x:c,y:f,zoom:this.imageData.width*e[o]/this.imageData.width,rotation:this.offsets[o].rotation}});this.updateOffsets(a,i),this.onZoomChangeListeners.forEach(s=>s(e))}}setRotation(e,t){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const n=this.frameData.map((i,a)=>({...this.offsets[a],rotation:e[a]}));this.updateOffsets(n,t),this.onRotationChangeListeners.forEach(i=>i(e))}}setPatternData(e,t=!0){this.imageData=e,e&&this.frameData&&((t||!this.offsets)&&this.recalculateOffsets(e,t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(e,t,n){const i=this.imageData;if(!i||!this.frameData)return;if(this.frameData.length!==e.length)throw new an("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(e[o].x===s.x&&e[o].y===s.y&&e[o].zoom===s.zoom&&e[o].rotation===s.rotation))&&!n){t&&t();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=fD(e[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,i,this.frameData,this.thresholdSettings,t)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(e){this.thresholdSettings=e,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,e)}onFrameDataChanged(e){e(this.frameData),this.onFrameDataChangeListeners.push(e)}onZoom(e){this.onZoomChangeListeners.push(e)}onRotation(e){this.onRotationChangeListeners.push(e)}updateFrameOffsets(e,t,n,i,a){if(!n||n.length===0||n.some(l=>!l))throw new an("Frame data not set. This is a bug");if(!this.workflowManager)throw new an("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getRegionElements(this.stepName||""),o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,u)=>{let c=s.find(f=>f.id===l)?.regionIndex??u;c>=e.length&&(c=u);try{o(new In([new YL(l,t,e[c]),new XL(l,i.useThreshold,i.invertThreshold,i.threshold,i.thresholdSaturation)]))}catch{}}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:e}),a&&a()}recalculateZoomLimits(e,t){(this.minZoomScale.length!==t.length||this.maxZoomScale.length!==t.length)&&(this.minZoomScale=new Array(t.length),this.maxZoomScale=new Array(t.length)),t.forEach((n,i)=>{const a=Math.max(n.width/e.width,n.height/e.height);this.forceImageCover?(this.minZoomScale[i]=a,this.maxZoomScale[i]=a*2.5):(this.minZoomScale[i]=a/10,this.maxZoomScale[i]=a*2.5)})}recalculateOffsets(e,t=!0){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((n,i)=>{const a=t?0:this.offsets[i]?.rotation||0;this.offsets[i]={...O1(e,n,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover),rotation:a}}),this._debouncedUpdateFrameOffsets(this.offsets,e,this.frameData,this.thresholdSettings))}}class TY{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(e,t,n,i,a,s,o,l,u,c,f,d,h,g,y,v,A){throw new Error("Method not implemented.")}approveTransaction(e){throw new Error("Method not implemented.")}rejectTransaction(e){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(e){this.client=e}getInitializationPromise(){return Promise.resolve()}async updateWorkflowConfiguration(e){throw new Error("Method not implemented.")}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(e){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(e){}addPoller(e){}addConfirmCallback(e){}addEditedCallback(e){}addElementsCallback(e){}addInformationResultCallback(e){}addInitCallback(e){}addMakingAdjustmentsCallback(e){}addMandatoryCallback(e){}addMetadataCallback(e){}addSelectionCallback(e){}addStepSpecificStorageCallback(e,t){}addStorageCallback(e){}getCommandDispatcher(){return e=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(e){return[]}getSerializedStep(e,t){}getStepSpecificServices(e){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getInitialOptionIds(){return new Promise(()=>new Set)}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(e){}markUpdateCompleted(e){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(e){}setEditedStatus(e,t){}setInformationResults(e){}setMandatoryFulfilled(e,t){}async setSelectionsAndElements(e,t,n){}toggleDesignConfirmed(){}updateMetadata(e,t){}async updateStorage(e,t){}injectIntoPreviewService(e){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(e){}async updateTransactionShareActions(){}addValidationCallback(e){}setStepError(e,t,n){}getStepErrors(e){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(e){return[]}}var pD=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(pD||{}),gD=(r=>(r.Original="original",r.BackgroundRemoved="backgroundRemoved",r.Optimized="optimized",r))(gD||{});class mD extends $i{constructor(e,t,n){super(e,t,n);const i=t.data;this.frameService=new hD(i.forceImageCover,i.initialZoomLevel),this.frameService.connectWorkflowManager(e,t.stepName)}selectVariant(e){const t=this.manager.getRegionElements(this.step.stepName);return uo.selectVariant(this.step,e.getResource(),t,this.manager,n=>this.setUpdateState(n))}onFrameDataChanged(e){this.frameService&&this.frameService.onFrameDataChanged(t=>{t&&e(t)})}async selectImage(e,t=!0,n=!0){await uo.selectImage(this.step,e,this.manager,n),t&&this.manager.updateStorage(this.step.stepName,{framePatternData:{originalAssetKey:e.key,backgroundRemovedAssetKey:void 0,vectorizedAssetKey:void 0,enhancedAssetKey:void 0,useOriginalAsset:void 0}})}async canUseAdvancedImageManipulation(){return this.manager.getClient().canUseAddon(Vg.AdvancedImageManipulation)}async canRemoveBackground(){return await this.canUseAdvancedImageManipulation()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(e=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseAdvancedImageManipulation to ensure you disable this feature when appropriate.");const t=await this.getOriginalImageSelection();if(!t)throw new Error("You must supply an image selection before attempting to remove the background.");const n=await Un.removeBackgroundFromAsset(t);e&&await uo.selectImage(this.step,n,this.manager,!1);const i=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,backgroundRemovedAssetKey:n.key,useOriginalAsset:!e}}),n}async vectorize(e,t=void 0){const n=e??await this.getOriginalImageSelection();if(!n)throw new Error("You must supply an image selection before attempting to vectorize the image.");const i=await Un.vectorizeAsset(n,t);await this.selectImage(i,!1);const a=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,vectorizedAssetKey:i.key,useOriginalAsset:!1}}),i}async enhanceWithAI(e,t){const n=e??await this.getOriginalImageSelection();if(!n)throw new Error("You must supply an image selection before attempting to enhance the image with AI.");const i=await Un.enhanceWithAI(n,t);await this.selectImage(i,!1);const a=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{originalAssetKey:a.originalAssetKey,backgroundRemovedAssetKey:a.backgroundRemovedAssetKey,vectorizedAssetKey:a.vectorizedAssetKey,enhancedAssetKey:i.key,useOriginalAsset:!1}}),i}async getBackgroundRemovedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey;if(e)return Un.getLocalOrFromServer(e)}async getVectorizedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey;if(e)return Un.getLocalOrFromServer(e)}async getEnhancedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.enhancedAssetKey;if(e)return Un.getLocalOrFromServer(e)}hasOriginalImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}hasEnhancedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.enhancedAssetKey}async changeColors(e){await uo.changeColors(this.step,this.manager,e)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await ct.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?uo.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const e=this.getImageData();return e?.svg?(await Ra(e.svg)).colors:void 0}async mergeColors(e,t,n){const i=this.frameService.getImageData();if(!i?.svg||!i.colors)throw new Error("Cannot merge colors on non-SVG image or image without color information");const{svg:a,colors:s}=ST(i.svg,i.colors,e,t,n);this.frameService.setPatternData({...i,svg:a,colors:s},!1),this.manager.updateStorage(this.step.stepName,{colors:s})}async unmergeColors(e,t,n,i){const a=this.frameService.getImageData();if(!a?.svg||!a.colors)throw new Error("Cannot unmerge colors on non-SVG image or image without color information");this.frameService.setPatternData({...a,svg:i,colors:n},!1),this.manager.updateStorage(this.step.stepName,{colors:n})}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMinimumPixelThresholdForOptimization(){return this.step.data.vectorizationMinimumPixelThreshold}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return uo.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(e,t,n,i){return i&&i.length>1&&e===void 0?"SelectFrame":t||n||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.originalAssetKey;if(e)return Un.getLocalOrFromServer(e)}getCurrentImageState(){const e=this.getFrameStepStorage()?.framePatternData;return e?e.vectorizedAssetKey&&!e.useOriginalAsset?"optimized":e.useOriginalAsset!==!1?"original":"backgroundRemoved":"original"}async setImageState(e){const t=this.getFrameStepStorage()?.framePatternData||{};let n,i;switch(e){case"original":if(n=await this.getOriginalImageSelection(),!n)throw new Error("No original image available");i=!0;break;case"backgroundRemoved":if(n=await this.getBackgroundRemovedImageSelection(),!n)throw new Error("No background-removed image available. Call removeBackgroundFromImageSelection first.");i=!1;break;case"optimized":if(n=await this.getVectorizedImageSelection(),!n)throw new Error("No optimized image available. Call vectorize first.");i=!1;break}await this.selectImage(n,!1,!0),this.manager.updateStorage(this.step.stepName,{framePatternData:{...t,useOriginalAsset:i}})}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(e){const t=this.getFrameStepStorage()?.framePatternData||{};if(t.useOriginalAsset===e)return;const n=await this.getOriginalImageSelection();if(!n)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(e)await this.selectImage(n,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...t,useOriginalAsset:e}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const FY=Ce`
|
|
3152
|
+
${X2(t)}`);const i=await Le.getShadowGraphqlClient().query({query:t,errorPolicy:"all",variables:n,context:{logRequestHeaders:!0}});if(i.error)throw console.log("[getWorkflowsInternal] Response errored."),i.error;if(i.errors)throw i.errors.forEach(s=>console.error(s)),new Error("Unable to read workflows. Consult GraphQL errors.");if(!i.data.workflows||i.data.workflows.length!==r.length)throw new Error(`Unable to read workflows: ${i.errors??"Length mismatch in response"}`);const a=Ao(i.data.workflows);return a.forEach(s=>{s.finalizeStepConfig||(s.finalizeStepConfig={}),s.finalizeStepConfig.termsMarkdown=s.finalizeStepConfig.termsMarkdown||s.partner.termsMarkdown}),a},yY=async(r,e)=>{const n=(await e).find(i=>i.id===r);if(!n)throw new Error(`Workflow not found: ${r}`);return n},fw=async(r,e)=>{const t=r.map(o=>Af.get({id:o,options:e})),n=r.filter((o,l)=>t[l]===void 0);if(n.length===0)return Promise.all(t);const i=mY(n,e),a=n.map(o=>Af.set({id:o,options:e},yY(o,i))),s=t.filter(o=>o!==void 0);return await Promise.all(s.concat(a))},sD=async(r,e)=>(await fw([r],e))[0],oD=async r=>{const e=await Le.getShadowGraphqlClient().query({query:PT,variables:{ids:r},errorPolicy:"all",fetchPolicy:"no-cache"});return e.errors&&console.error(e.errors),e.data.integrationProducts||[]};class vY{constructor(e){this.activeIntegration=void 0,this.updateTransactionState=async t=>{try{return Le.getShadowGraphqlClient().mutate({...t,mutation:eM})}catch(n){throw console.error(n),new fo("Critical - Unable to synchronize workflow state with server.")}},this.options=e,this.options.applicationKey&&oT(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 44.8.1-alpha.0"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(e){ls.setHubUrl(e.hubUrl),ls.setServerUrl(e.serverUrl),ls.setServicesApiUrl(e.servicesApiUrl),this.marketplaceThemeInstallId=e.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=e.marketplaceThemeInstallConfigurationId,this.userPoolClientId=e.userPoolClientId,this.userPoolRegion=e.userPoolRegion,this.spiffRegion=e.spiffRegion,e.bearerAuthenticationToken&&uT(e.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Dd.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getVersion(){return"44.8.1-alpha.0"}getAssetManager(){return Un}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!bB())throw new Error("Application key required to use Flow Service.");return new nP}async getCurrencyContext(e){const n=(await this.getIntegration()).partner.currencyCode,a=await Le.getShadowGraphqlClient().query({query:wM,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:n,to:e}}),{rateFrom:s,rateTo:o}=a.data.currencyConversion;return new aD(s,o,n,e)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=lD(this.options.applicationKey),this.activeIntegration}async canUseAddon(e){try{return(await this.getIntegration()).partner.activeAddons?.includes(e)??!1}catch(t){return console.error(t),!1}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(e){const t=wr.getMap("transactionCustomerIds");t?.has(e)&&(t.delete(e),wr.setMap("transactionCustomerIds",t))}async customerHasBundleTemplates(e){const i=(await Le.getShadowGraphqlClient().query({query:Ly,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;return i.id?i.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(e){const t=this.customer?.stakeholders?.find(n=>n.transaction?.id===e);if(t)return t.type}async getOrCreateCustomer(e){this.customer=void 0;const t=Le.getShadowGraphqlClient(),i=(await t.query({query:Ly,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;if(!i.id){const o=(await t.mutate({mutation:YV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:e}}})).data?.customerCreate;if(!o)throw new Error("Unable to create customer.");return this.storeCustomer(o),this.customer=o,{customer:o,isAuthenticated:!1}}this.storeCustomer(i);const a=await this.reloadLoggedInCustomer();return{customer:this.customer||i,isAuthenticated:a}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const e=localStorage.getItem("last-refreshed-cognito-tokens"),t=localStorage.getItem("cognito-tokens"),n=localStorage.getItem("cognito-email");if(!e||!t||!n)return!1;const i=JSON.parse(t),a=new Date().getTime()/1e3;if(!i.ExpiresIn||i.ExpiresIn<a-parseInt(e)){const u=await Dd.refreshTokens();if(u?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),i.AccessToken=u.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(i));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=localStorage.getItem("customer-login-token");s&&A0(s);const l=(await Le.getShadowGraphqlClient().query({query:Ly,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:n}})).data.customer;return l.id?(this.customer=l,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(e){await Le.getShadowGraphqlClient().mutate({mutation:XV,variables:{emailAddress:e}}),await Dd.generateCode(e)}async verifyCode(e,t){const n=(await this.getIntegration()).partner.id||"",i=await Dd.verifyCode(e,t,n);if(i?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(i.AuthenticationResult)),localStorage.setItem("cognito-email",e);const s=(await Le.getShadowGraphqlClient().mutate({mutation:JV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e,verificationCode:t}})).data?.customerVerifyCode;if(!s?.id)throw new Error("Failed to get customer.");return this.customer=s,s.loginToken&&(localStorage.setItem("customer-login-token",s.loginToken),A0(s.loginToken)),!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),localStorage.removeItem("customer-login-token"),A0(""),this.clearCustomer()}async loggedInBearerToken(){const e=localStorage.getItem("last-refreshed-cognito-tokens"),t=localStorage.getItem("cognito-tokens");if(!e||!t)throw new Error("No token data in storage.");const n=JSON.parse(t),i=new Date().getTime()/1e3,a=!n?.AccessToken||Cg(n.AccessToken);if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(e)||a){const s=await Dd.refreshTokens();if(s?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=s.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!n.AccessToken)throw new Error("No bearer token in storage.");return n.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await Le.getShadowGraphqlClient().query({query:KV,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(e,t,n,i){const s=(await Le.getShadowGraphqlClient().mutate({mutation:_9(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:e,initialMetadata:t?Object.entries(t).map((c,f)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,activationId:i,test:n?.test},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!s?.id)throw new Error("Unable to create bundle");const o=wr.getMap("bundlePartnerIds")||new Map;o.set(s.id,s.partner.id),wr.setMap("bundlePartnerIds",o);const l=wr.getMap("bundleOwnerIds")||new Map;l.set(s.id,s.bundleOwnerId),wr.setMap("bundleOwnerIds",l);const u=new HE(this,s,void 0,void 0,s.bundleOwnerId,{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts});return await u.getInitializationPromise(),u}async getExistingBundle(e,t,n,i,a){const o=wr.getMap("bundleOwnerIds")?.get(e),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const v=Object.entries(localStorage).find(([x,S])=>x.startsWith("CognitoIdentityServiceProvider")&&x.endsWith("idToken"))?.[0]||"",A=localStorage.getItem(v);A&&!Cg(A)&&(l.Authorization=`Bearer ${A}`)}const u={bundleOwnerId:o,...l,...i?.graphql?.additionalHeaders},c=await Le.getShadowGraphqlClient().query({query:R9(i?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:e},fetchPolicy:"no-cache",context:{headers:u}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${e}`);const f=c.data?.bundles[0],d=wr.getMap("bundlePartnerIds")||new Map;d.set(f.id,f.partner.id),wr.setMap("bundlePartnerIds",d);const h=new HE(this,f,t,n,o,{additionalHeaders:i?.graphql?.additionalHeaders,eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:i?.readonly},a);return await h.getInitializationPromise(),h}async duplicateBundle(e,t,n,i){const s={...await dD(e),...i?.graphql?.additionalHeaders},l=(await Le.getShadowGraphqlClient().mutate({mutation:N9(),variables:{id:e,template:t,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:n,test:i?.test},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const u=wr.getMap("bundlePartnerIds")||new Map;u.set(l.id,l.partner.id),wr.setMap("bundlePartnerIds",u);const c=wr.getMap("bundleOwnerIds")||new Map;return c.set(l.id,l.bundleOwnerId),wr.setMap("bundleOwnerIds",c),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(e){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:t,...n}=e;return(await Le.getShadowGraphqlClient().query({query:Q9(t??!1),variables:{...n,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getTemplatesForCustomer(e){if(!this.customer?.id)throw new Error("Customer not authenticated.");const t=await Le.getShadowGraphqlClient().query({query:pY,variables:{...e,customerId:this.customer.id},fetchPolicy:"no-cache"});return{total:t.data.globalPropertyTemplatesFeed.total,items:t.data.globalPropertyTemplatesFeed.items.map(n=>new gY(n))}}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const e=await Le.getShadowGraphqlClient().query({query:O9,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!e.data?.customers||e.data.customers.length===0)throw new Error("Unable to find customer.");const n=e.data.customers[0].bundleStakeholders||[],i=wr.getMap("bundlePartnerIds")||new Map;return n.forEach(a=>{a.bundle?.id&&a.bundle.partner?.id&&i.set(a.bundle.id,a.bundle.partner.id)}),wr.setMap("bundlePartnerIds",i),n}async getWorkflowExperience(e,t){if(!e)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const n=await this.getWorkflowExperiences([e],e.graphql),i=n[0],a=i.getWorkflow();return t&&!a&&console.error("No workflow instantiated when trying to create preview service."),t&&a&&await i.getWorkflowManager().injectIntoPreviewService(t(a)),n[0]}async getWorkflowExperiences(e,t,n,i){if(e.length===0)throw new fo("No options provided!");const a=e.map((U,$)=>({option:U,index:$})),s=a.filter(U=>U.option.type==="transaction"),o=a.filter(U=>U.option.type==="integration"||U.option.type==="external"||U.option.type==="blank"),l=50,u=xA(s,l),c=xA(o,l);let f=0;const d=Le.getShadowGraphqlClient(),h=async U=>{if(U.length===0)return[];const $=U.map(K=>K.option.transactionId),z=await d.query({query:Z3,variables:{ids:$},errorPolicy:"all",fetchPolicy:"no-cache"}),Q=z.data.transactions;if(f=f+Q.length,i&&i(f,s.length),Q.length!==U.length){const K=z.errors?.[0]?.message||"Unknown error";throw new fo(`Not all transactions were found: ${K}`)}return!this.activeIntegration&&Q[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(Q[0].integrationProduct.integration)),Q.map((K,le)=>({transaction:K,workflowId:K.workflowId,readOnly:U.find(he=>he.option.transactionId===K.id)?.option.readOnly??!1,index:U[le].index}))},g=async U=>{if(U.length===0)return[];const $=await d.mutate({mutation:K3,variables:{inputs:U.map(Q=>({integrationProductId:Q.option.type==="integration"?Q.option.integrationProductId:void 0,externalIntegrationId:Q.option.type==="external"?Q.option.externalIntegrationId:void 0,externalProductId:Q.option.type==="external"?Q.option.externalProductId:void 0,workflowId:Q.option.workflowId,designName:Q.option.designName,claim:!0,quantity:Q.option.quantity,recipient:Q.option.recipient,parentTransactionId:Q.option.parentTransactionId})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.getCreateTransactionContext(U,t)}),z=$.data?.transactionCreateMany;if(!z||z.length===0){const Q=$.errors?.[0]?.message||"Unknown error";throw new fo(`Failed to create transactions: ${Q}`)}return f=f+z.length,i&&i(f,s.length),z.map((Q,K)=>({transaction:Q,workflowId:Q.workflowId,readOnly:!1,index:U[K].index}))},y=(await Promise.all([...u.map(h),...c.map(g)])).flat();let v=[...new Set(y.map(U=>U.transaction.integrationProductId))].filter(U=>!!U);v=v.filter(U=>!!U);let A=[...new Set(y.map(U=>U.workflowId))].filter(U=>!!U);A=A.filter(U=>!!U);const[x,S]=await Promise.all([(async()=>v.length>0?await oD(v):[])(),(async()=>A.length>0?await fw(A,t):[])()]),F=new Map(x.map(U=>[U.id,U])),E=new Map(S.map(U=>[U.id,U])),R=y.map(async U=>{const{transaction:$,workflowId:z,readOnly:Q,index:K}=U,le=z?E.get(z):void 0,he=e[K];if($.integrationProductId){const ue=F.get($.integrationProductId);$.integrationProduct=ue,$.product=ue?.product,$.integrationProduct||console.error("failed to find transaction's product")}const Me=wr.getMap("transactionOwnerIds")||new Map;!Me.get($.id)&&$.transactionOwnerId&&(Me.set($.id,$.transactionOwnerId),wr.setMap("transactionOwnerIds",Me));const De=Me.get($.id)||void 0,Pe=new ZV({onMutate:()=>({context:{transactionOwnerId:De,bundleOwnerId:t?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:De,bundleOwnerId:t?.bundleOwnerId}})}),re={workflow:le,transaction:$,singleVariantsRenderable:he?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:Q?async()=>{throw new an("State mutation is forbidden in read only mode!")}:async ue=>this.updateTransactionState({...ue,context:{transactionOwnerId:De,bundleOwnerId:t?.bundleOwnerId}}),graphQlClient:()=>Pe,readOnly:Q,isReloadedTransaction:he.type==="transaction"};if(he.type==="transaction"&&$.workflowState){const ue=JSON.parse($.workflowState);await gA(ue),re.reloadedState=ue}else if(!Q&&he.workflowState){const ue=JSON.parse(he.workflowState);await gA(ue),re.reloadedState=ue}return re.delayWorkflowStateSync=!0,{experienceOptions:re,index:K,options:he}}),W=(await Promise.all(R)).sort((U,$)=>U.index-$.index);let Y=[],ae=[];for(const U of W){const{experienceOptions:$,options:z}=U,Q=new q1(this,$);await Q.getWorkflowManager().getInitializationPromise(),n&&n(),z.type!=="transaction"&&this.customer&&ae.push(Q),Y=[...Y,Q],Q.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}if(ae.length>0){const U=this.customer.emailAddress,$=ae.map(K=>K.getTransaction().id),Q=(await d.mutate({mutation:CV,variables:{ids:$,details:{emailAddress:U},type:"Owner"},errorPolicy:"all"})).data?.transactionsAddStakeholder;if(Q&&Q?.length>0){const K=Q[0].stakeholders?.find(le=>le.customer?.emailAddress===U);if(K?.customer)for(const le of ae)le.assignCustomerInternal(K.customer)}}return Y}getCreateTransactionContext(e,t){const n=e.find(s=>s.option.parentTransactionId)?.option.parentTransactionId;if(!n&&!t?.bundleOwnerId)return;const i=wr.getMap("transactionOwnerIds")||new Map,a=n?i.get(n):void 0;return{...a?{transactionOwnerId:a}:{},...t?.bundleOwnerId?{bundleOwnerId:t.bundleOwnerId}:{}}}storeCustomer(e){const t=wr.getMap("partnerCustomerIds")||new Map;t.set(e.partner.id,e.id),wr.setMap("partnerCustomerIds",t)}async getIntegrationProductById(e,t){const a=(await Le.getShadowGraphqlClient().query({query:oM(t),variables:{ids:[e]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!a||a.length===0||!a[0]?.id)throw new Error("Integration product not found.");return new EA(a[0])}async getIntegrationProductFromExternalIds(e,t,n){const s=(await Le.getShadowGraphqlClient().query({query:lM(n),variables:{externalProductId:t,externalIntegrationId:e},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!s?.id)throw new Error("Integration product not found.");return new EA(s)}async getIntegrationProduct(e){return e.type==="integration"?this.getIntegrationProductById(e.integrationProductId):this.getIntegrationProductFromExternalIds(e.externalIntegrationId,e.externalProductId)}async getShareActionsForTransaction(e){const n=(wr.getMap("transactionOwnerIds")||new Map).get(e)||void 0,i=await Le.getShadowGraphqlClient().query({query:aM,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:e},context:{transactionOwnerId:n}});if(!i.data.transactions||i.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${e}`);return i.data.transactions[0].transactionShareActions}async placeOrder(e){const t=await Le.getShadowGraphqlClient().mutate({mutation:bM,variables:{orderItems:e}});if(t.errors)throw new Error(t.errors[0].message);if(!t.data)throw new Error("Failed to create order: No order data in response.");return{id:t.data.orderCreate.id,internalId:t.data.orderCreate.internalId}}}const lD=async(r,e)=>(await Le.getShadowGraphqlClient().query({query:yM,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r},skipIntegrationCheck:!0},variables:{themeConfigurationId:e}})).data.currentIntegration,AY=async r=>{const t=await Le.getShadowGraphqlClient().query({query:iM,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(t.data.transactions.length!==0)return t.data.transactions[0]},bY=async(r,e)=>(await Le.getShadowGraphqlClient().query({query:mM,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:e}})).data?.marketplaceThemeInstallConfiguration,wY=async r=>(await Le.getShadowGraphqlClient().query({query:AM,errorPolicy:"all",variables:{id:r}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,xY=async r=>(await Le.getShadowGraphqlClient().query({query:vM,errorPolicy:"all",variables:{id:r}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration,uD=async(r,e)=>(await Le.getShadowGraphqlClient().query({query:FM(!!e),errorPolicy:"all",variables:{id:r,productIds:e}})).data?.activation,CY=async r=>(await uD(r))?.marketplaceThemeInstallConfiguration;async function cD(){const r={};try{const e=await this.loggedInBearerToken();r.Authorization=`Bearer ${e}`}catch{const n=Object.entries(localStorage).find(([a,s])=>a.startsWith("CognitoIdentityServiceProvider")&&a.endsWith("idToken"))?.[0]||"",i=localStorage.getItem(n);i&&!Cg(i)&&(r.Authorization=`Bearer ${i}`)}return r}async function dD(r){const t=wr.getMap("bundleOwnerIds")?.get(r),n=await cD();return{bundleOwnerId:t,...n}}async function SY(r){const t=wr.getMap("transactionOwnerIds")?.get(r),n=await cD();return{transactionOwnerId:t,...n}}const EY=async r=>{const e=await dD(r),t=await Le.getShadowGraphqlClient().mutate({mutation:nV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r},context:{headers:e}});if(t.data?.bundleDelete!==r)throw new Error(`Failed to delete bundle: ${t.errors}`)},kY=async r=>{const e=await SY(r),t=await Le.getShadowGraphqlClient().mutate({mutation:iV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[r]},context:{headers:e}});if(!t.data?.transactions||t.data.transactions.length!==1||t.data.transactions[0].id!==r)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(t.errors)}`);return t.data.transactions[0].bundle?.id};function fD(r,e,t,n){const i=t.width*r.zoom,a=t.height*r.zoom;if(n){const s=Math.max(e.width/t.width,e.height/t.height),o=Math.max(s,r.zoom),l=t.width*o,u=t.height*o;return{...r,x:Mp(r.x,e.width-l,0),y:Mp(r.y,e.height-u,0),zoom:o}}return{...r,x:Mp(r.x,-i,e.width),y:Mp(r.y,-a,e.height)}}function Mp(r,e,t){return Math.min(Math.max(r,e),t)}class hD{constructor(e,t){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=v1(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.onRotationChangeListeners=[],this.forceImageCover=e,this.initialZoom=t,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(e,t){t&&e.addStepSpecificStorageCallback(async n=>{if(n){const i=n;if(i.currentFrameSources){let a=!1;for(let s=0;s<i.currentFrameSources.length;s++){const o=i.currentFrameSources[s],l=await Zf(o),u=this.frameData?this.frameData[s]:void 0;wf(l,u)||(this.frameData||(this.frameData=new Array(i.currentFrameSources.length)),this.frameData[s]=l,a=!0)}a&&(this.onFrameDataChangeListeners.forEach(s=>s(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},t),this.workflowManager=e,this.stepName=t}setTargetElements(e){this.targetElements=e}getFrameData(){return this.frameData}setFrameData(e){if(!e){this.frameData=void 0;return}e.forEach((t,n)=>{const i=Uu.get(t);i&&(this.frameData||(this.frameData=new Array(e.length)),this.frameData[n]=i)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const e=Wg(this.imageData.svg,this.imageData.colors||{},!1);return jg(e)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(e){this.offsets=e}setZoom(e,t,n,i){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const a=this.frameData.map((s,o)=>{const l=(t[o]-this.offsets[o].x)/this.offsets[o].zoom,u=(n[o]-this.offsets[o].y)/this.offsets[o].zoom,c=t[o]-l*e[o],f=n[o]-u*e[o];return{x:c,y:f,zoom:this.imageData.width*e[o]/this.imageData.width,rotation:this.offsets[o].rotation}});this.updateOffsets(a,i),this.onZoomChangeListeners.forEach(s=>s(e))}}setRotation(e,t){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const n=this.frameData.map((i,a)=>({...this.offsets[a],rotation:e[a]}));this.updateOffsets(n,t),this.onRotationChangeListeners.forEach(i=>i(e))}}setPatternData(e,t=!0){this.imageData=e,e&&this.frameData&&((t||!this.offsets)&&this.recalculateOffsets(e,t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(e,t,n){const i=this.imageData;if(!i||!this.frameData)return;if(this.frameData.length!==e.length)throw new an("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(e[o].x===s.x&&e[o].y===s.y&&e[o].zoom===s.zoom&&e[o].rotation===s.rotation))&&!n){t&&t();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=fD(e[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,i,this.frameData,this.thresholdSettings,t)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(e){this.thresholdSettings=e,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,e)}onFrameDataChanged(e){e(this.frameData),this.onFrameDataChangeListeners.push(e)}onZoom(e){this.onZoomChangeListeners.push(e)}onRotation(e){this.onRotationChangeListeners.push(e)}updateFrameOffsets(e,t,n,i,a){if(!n||n.length===0||n.some(l=>!l))throw new an("Frame data not set. This is a bug");if(!this.workflowManager)throw new an("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getRegionElements(this.stepName||""),o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,u)=>{let c=s.find(f=>f.id===l)?.regionIndex??u;c>=e.length&&(c=u);try{o(new In([new YL(l,t,e[c]),new XL(l,i.useThreshold,i.invertThreshold,i.threshold,i.thresholdSaturation)]))}catch{}}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:e}),a&&a()}recalculateZoomLimits(e,t){(this.minZoomScale.length!==t.length||this.maxZoomScale.length!==t.length)&&(this.minZoomScale=new Array(t.length),this.maxZoomScale=new Array(t.length)),t.forEach((n,i)=>{const a=Math.max(n.width/e.width,n.height/e.height);this.forceImageCover?(this.minZoomScale[i]=a,this.maxZoomScale[i]=a*2.5):(this.minZoomScale[i]=a/10,this.maxZoomScale[i]=a*2.5)})}recalculateOffsets(e,t=!0){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((n,i)=>{const a=t?0:this.offsets[i]?.rotation||0;this.offsets[i]={...O1(e,n,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover),rotation:a}}),this._debouncedUpdateFrameOffsets(this.offsets,e,this.frameData,this.thresholdSettings))}}class TY{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(e,t,n,i,a,s,o,l,u,c,f,d,h,g,y,v,A){throw new Error("Method not implemented.")}approveTransaction(e){throw new Error("Method not implemented.")}rejectTransaction(e){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(e){this.client=e}getInitializationPromise(){return Promise.resolve()}async updateWorkflowConfiguration(e){throw new Error("Method not implemented.")}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(e){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(e){}addPoller(e){}addConfirmCallback(e){}addEditedCallback(e){}addElementsCallback(e){}addInformationResultCallback(e){}addInitCallback(e){}addMakingAdjustmentsCallback(e){}addMandatoryCallback(e){}addMetadataCallback(e){}addSelectionCallback(e){}addStepSpecificStorageCallback(e,t){}addStorageCallback(e){}getCommandDispatcher(){return e=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(e){return[]}getSerializedStep(e,t){}getStepSpecificServices(e){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getInitialOptionIds(){return new Promise(()=>new Set)}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(e){}markUpdateCompleted(e){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(e){}setEditedStatus(e,t){}setInformationResults(e){}setMandatoryFulfilled(e,t){}async setSelectionsAndElements(e,t,n){}toggleDesignConfirmed(){}updateMetadata(e,t){}async updateStorage(e,t){}injectIntoPreviewService(e){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(e){}async updateTransactionShareActions(){}addValidationCallback(e){}setStepError(e,t,n){}getStepErrors(e){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(e){return[]}}var pD=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(pD||{}),gD=(r=>(r.Original="original",r.BackgroundRemoved="backgroundRemoved",r.Optimized="optimized",r))(gD||{});class mD extends $i{constructor(e,t,n){super(e,t,n);const i=t.data;this.frameService=new hD(i.forceImageCover,i.initialZoomLevel),this.frameService.connectWorkflowManager(e,t.stepName)}selectVariant(e){const t=this.manager.getRegionElements(this.step.stepName);return uo.selectVariant(this.step,e.getResource(),t,this.manager,n=>this.setUpdateState(n))}onFrameDataChanged(e){this.frameService&&this.frameService.onFrameDataChanged(t=>{t&&e(t)})}async selectImage(e,t=!0,n=!0){await uo.selectImage(this.step,e,this.manager,n),t&&this.manager.updateStorage(this.step.stepName,{framePatternData:{originalAssetKey:e.key,backgroundRemovedAssetKey:void 0,vectorizedAssetKey:void 0,enhancedAssetKey:void 0,useOriginalAsset:void 0}})}async canUseAdvancedImageManipulation(){return this.manager.getClient().canUseAddon(Vg.AdvancedImageManipulation)}async canRemoveBackground(){return await this.canUseAdvancedImageManipulation()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(e=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseAdvancedImageManipulation to ensure you disable this feature when appropriate.");const t=await this.getOriginalImageSelection();if(!t)throw new Error("You must supply an image selection before attempting to remove the background.");const n=await Un.removeBackgroundFromAsset(t);e&&await uo.selectImage(this.step,n,this.manager,!1);const i=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,backgroundRemovedAssetKey:n.key,useOriginalAsset:!e}}),n}async vectorize(e,t=void 0){const n=e??await this.getOriginalImageSelection();if(!n)throw new Error("You must supply an image selection before attempting to vectorize the image.");const i=await Un.vectorizeAsset(n,t);await this.selectImage(i,!1);const a=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,vectorizedAssetKey:i.key,useOriginalAsset:!1}}),i}async enhanceWithAI(e,t){const n=e??await this.getOriginalImageSelection();if(!n)throw new Error("You must supply an image selection before attempting to enhance the image with AI.");const i=await Un.enhanceWithAI(n,t);await this.selectImage(i,!1);const a=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{originalAssetKey:a.originalAssetKey,backgroundRemovedAssetKey:a.backgroundRemovedAssetKey,vectorizedAssetKey:a.vectorizedAssetKey,enhancedAssetKey:i.key,useOriginalAsset:!1}}),i}async getBackgroundRemovedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey;if(e)return Un.getLocalOrFromServer(e)}async getVectorizedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey;if(e)return Un.getLocalOrFromServer(e)}async getEnhancedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.enhancedAssetKey;if(e)return Un.getLocalOrFromServer(e)}hasOriginalImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}hasEnhancedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.enhancedAssetKey}async changeColors(e){await uo.changeColors(this.step,this.manager,e)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await ct.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?uo.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const e=this.getImageData();return e?.svg?(await Ra(e.svg)).colors:void 0}async mergeColors(e,t,n){const i=this.frameService.getImageData();if(!i?.svg||!i.colors)throw new Error("Cannot merge colors on non-SVG image or image without color information");const{svg:a,colors:s}=ST(i.svg,i.colors,e,t,n);this.frameService.setPatternData({...i,svg:a,colors:s},!1),this.manager.updateStorage(this.step.stepName,{colors:s})}async unmergeColors(e,t,n,i){const a=this.frameService.getImageData();if(!a?.svg||!a.colors)throw new Error("Cannot unmerge colors on non-SVG image or image without color information");this.frameService.setPatternData({...a,svg:i,colors:n},!1),this.manager.updateStorage(this.step.stepName,{colors:n})}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMinimumPixelThresholdForOptimization(){return this.step.data.vectorizationMinimumPixelThreshold}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return uo.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(e,t,n,i){return i&&i.length>1&&e===void 0?"SelectFrame":t||n||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.originalAssetKey;if(e)return Un.getLocalOrFromServer(e)}getCurrentImageState(){const e=this.getFrameStepStorage()?.framePatternData;return e?e.vectorizedAssetKey&&!e.useOriginalAsset?"optimized":e.useOriginalAsset!==!1?"original":"backgroundRemoved":"original"}async setImageState(e){const t=this.getFrameStepStorage()?.framePatternData||{};let n,i;switch(e){case"original":if(n=await this.getOriginalImageSelection(),!n)throw new Error("No original image available");i=!0;break;case"backgroundRemoved":if(n=await this.getBackgroundRemovedImageSelection(),!n)throw new Error("No background-removed image available. Call removeBackgroundFromImageSelection first.");i=!1;break;case"optimized":if(n=await this.getVectorizedImageSelection(),!n)throw new Error("No optimized image available. Call vectorize first.");i=!1;break}await this.selectImage(n,!1,!0),this.manager.updateStorage(this.step.stepName,{framePatternData:{...t,useOriginalAsset:i}})}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(e){const t=this.getFrameStepStorage()?.framePatternData||{};if(t.useOriginalAsset===e)return;const n=await this.getOriginalImageSelection();if(!n)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(e)await this.selectImage(n,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...t,useOriginalAsset:e}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const FY=Ce`
|
|
3153
3153
|
query GetLoggedInCustomer($email: String!) {
|
|
3154
3154
|
customer(emailAddress: $email) {
|
|
3155
3155
|
id
|
|
@@ -3362,4 +3362,4 @@ ${X2(t)}`);const i=await Le.getShadowGraphqlClient().query({query:t,errorPolicy:
|
|
|
3362
3362
|
}
|
|
3363
3363
|
}
|
|
3364
3364
|
`,sX=async r=>(await Le.getShadowGraphqlClient().query({query:aX,variables:{ids:r}})).data.integrationProducts;function oX(r){return new q1({},{stateMutationFunc:(()=>Promise.resolve()),transaction:{id:"local-transaction",product:{modelUrl:r.modelUrl}},graphQlClient:{},workflow:r.workflow,reloadedState:r.reloadedState})}function lX(r){return Object.entries(r).map(([e,t])=>{const n=t.selectedVariants?.map(s=>({id:s.id,priceModifier:s.priceModifier}));let i;const a=Object.keys(t).length;if(n!==void 0&&a>1||n===void 0&&a>0){i={};const s=t;i={...i,color:s.color,customColor:s.customColor,defaultCleared:s.defaultCleared,inputText:s.inputText,text:s.text,customiseAllText:s.customiseAllText};const o=t;i={...i,framePatternSrc:o.framePatternAsset?AA(o.framePatternAsset):void 0,currentFrameSources:o.currentFrameSources,framePatternData:o.framePatternData},i={...i,transactionIds:t.transactionIds}}return{stepName:e,selectedVariants:n,storage:i}})}exports.AddonHandle=Vg;exports.AddressValidationJobStatus=AD;exports.AddressValidationResultConfirmationLevel=vD;exports.AddressValidationStatus=Ug;exports.ArrayInput=QV;exports.AspectType=Gn;exports.AssetNotFoundError=To;exports.AssetType=gf;exports.BringForwardCommand=tU;exports.BringToBackCommand=eU;exports.BringToFrontCommand=ZL;exports.BundleDesignCreationCartAddMode=Yk;exports.CanvasCommand=Pn;exports.CollectionProduct=Ou;exports.ColorOptionGlobalPropertyHandle=CA;exports.CommandContext=gI;exports.ConversionDataType=Kd;exports.CreateElementCommand=ai;exports.CreateLayoutCommand=_1;exports.CurrencyContext=aD;exports.CurrencyService=iD;exports.DeleteElementCommand=Oo;exports.DigitalContentStepHandle=WI;exports.FileUploadGlobalPropertyHandle=KI;exports.FlowExecutionNodeResult=Gd;exports.FlowExecutionResult=iP;exports.FlowService=nP;exports.FontAlignmentCommand=bI;exports.FontColorCommand=mA;exports.FontSizeCommand=AI;exports.FontSourceCommand=yA;exports.FrameService=hD;exports.FrameStep=pD;exports.FrameStepHandle=mD;exports.GlobalPropertyHandle=rm;exports.GroupCommand=In;exports.IllustrationStepHandle=UI;exports.ImageState=gD;exports.InformationMessageType=th;exports.InformationStepHandle=qI;exports.IntegrationProduct=EA;exports.IntegrationType=Jk;exports.LayoutElementFactory=jL;exports.LayoutElementType=er;exports.LayoutNotFoundError=Ai;exports.LayoutRenderingPurpose=tc;exports.MaterialStepHandle=VI;exports.MisconfigurationError=os;exports.MockWorkflowManager=TY;exports.ModelStepHandle=$I;exports.ModuleStepHandle=QI;exports.MoveCommand=qL;exports.ObjectInput=X1;exports.ObjectInputType=aP;exports.OptionGlobalPropertyHandle=W1;exports.OptionNotFoundError=mf;exports.ParseError=Cl;exports.PictureStepHandle=zI;exports.ProductCameraRig=Kk;exports.ProductCollection=Q1;exports.ProductCollectionProductSortKey=rP;exports.ProductStepHandle=YI;exports.ProductWorkflow=co;exports.PromiseQueue=Jg;exports.QuestionStepHandle=HI;exports.QueueablePromise=Xg;exports.ResizeCommand=QL;exports.ResourceNotFoundError=pc;exports.RotateCommand=WL;exports.ScaleAxis=gi;exports.SendBackwardsCommand=rU;exports.ShapeStepHandle=GI;exports.ShareActionType=Xk;exports.SpiffCommerceClient=vY;exports.StakeholderType=t1;exports.StepAspectType=Qk;exports.StepHandle=$i;exports.StepType=Ye;exports.TextAlgorithm=Rl;exports.TextChangeCommand=wI;exports.TextGlobalPropertyHandle=ZI;exports.TextInput=WV;exports.TextStepHandle=jI;exports.UnhandledBehaviorError=an;exports.UnitOfMeasurement=Zk;exports.UpdateImageSourceCommand=JL;exports.Variant=Pa;exports.WorkflowExperienceEventType=Sg;exports.WorkflowExperienceImpl=q1;exports.__values=FD;exports.amtChannelsForAspect=eP;exports.assetConfigurationDeleteMutation=SM;exports.assetConfigurationUpdateMutation=CM;exports.assetConfigurationsQuery=xM;exports.assetService=Un;exports.browserColorToHex=bT;exports.bundleEmailMutation=aV;exports.cmPerPixel=C5;exports.createLocalWorkflowExperience=oX;exports.currentDirection=b5;exports.dataUrlFromExternalUrl=lB;exports.deleteBundle=EY;exports.designService=tg;exports.determineCorrectFontSizeAndLines=tf;exports.digitalContentStepService=L1;exports.domParser=ds;exports.duplicateBundle=LY;exports.duplicateTransaction=UY;exports.fetchAsString=ia;exports.findAngle=h5;exports.findElement=Vn;exports.findPmsColors=k3;exports.frameDataCache=Uu;exports.frameStepService=uo;exports.fromHex=hP;exports.fromUtf8=Pl;exports.generate=Ar;exports.generateCommands=RI;exports.generateSVGWithUnknownColors=Ra;exports.generateStateFromDesignInputSteps=S9;exports.getActivation=uD;exports.getActivationThemeConfiguration=CY;exports.getAddressValidationJobs=eX;exports.getAssetsForProductImagesQuery=EM;exports.getAttributesFromArrayBuffer=Vf;exports.getAxisAlignedBoundingBox=f5;exports.getBoundedOffsets=fD;exports.getBundleIdForTransaction=kY;exports.getBundleThemeConfiguration=wY;exports.getCustomer=VY;exports.getCustomerBundles=$Y;exports.getElementVertices=w5;exports.getFrameData=Zf;exports.getGlobalPropertyStateForBundle=F9;exports.getIntegration=lD;exports.getIntegrationProducts=sX;exports.getLayoutCanvasSize=MI;exports.getNEPoint=v5;exports.getNWPoint=y5;exports.getOrderedTransactions=GY;exports.getOverrideThemeConfiguration=bY;exports.getPointOfRotation=m5;exports.getProductCollections=$V;exports.getSEPoint=A5;exports.getSvgElement=em;exports.getTemplateBundles=qY;exports.getTemplateTransactions=jY;exports.getTransaction=AY;exports.getTransactionThemeConfiguration=xY;exports.getTransactionsForBundle=zY;exports.getTransformedAssetURL=Qg;exports.getTrueCoordinates=g5;exports.getUnorderedTransactions=HY;exports.getValidationJobsForWorkflowExperiences=ZY;exports.getWorkflow=sD;exports.getWorkflows=fw;exports.graphQlManager=Le;exports.illustrationStepService=ef;exports.isCloseToValue=p5;exports.loadFont=_l;exports.matchHexToPms=C3;exports.materialStepService=U1;exports.mergeColorClasses=ST;exports.metafieldManager=Eg;exports.mmPerPixel=x5;exports.modelStepService=V1;exports.modifySVGColors=Wg;exports.moduleStepService=$1;exports.nameBundle=_Y;exports.nameTransaction=NY;exports.nonPotTexSupport=BI;exports.optionService=ct;exports.outlineFontsInSvg=eL;exports.overrideWorkflowExperienceRecipientAddress=nX;exports.patternImageDataCache=Os;exports.persistenceService=wr;exports.pictureStepService=z1;exports.pmsToRgb=x3;exports.promiseCache=Af;exports.questionStepService=H1;exports.registerFetchImplementation=nB;exports.registerWindowImplementation=rB;exports.rehydrateSerializedLayout=gA;exports.rgbToPms=AT;exports.rotateAroundPoint=zd;exports.sanitizeSvgTree=qg;exports.setApplicationKey=oT;exports.setBearerAuthenticationToken=uT;exports.setCanvasModule=n1;exports.shapeStepService=Vu;exports.shortenUrl=TI;exports.skipWorkflowExperienceRecipientAddress=iX;exports.spiffCoreConfiguration=ls;exports.stepAspectValuesToDesignInputSteps=C9;exports.stepSelectionsToSerializableSteps=lX;exports.svgColorValueToDefinition=Qv;exports.svgStringDimensions=M1;exports.svgToDataUrl=jg;exports.textStepService=ri;exports.toHex=xo;exports.toUtf8=am;exports.toast=II;exports.validateWorkflowExperienceRecipient=tX;exports.validateWorkflowExperienceRecipients=rX;exports.xmlSerializer=Mo;
|
|
3365
|
-
//# sourceMappingURL=index-
|
|
3365
|
+
//# sourceMappingURL=index-CPGnAXAs.cjs.map
|