@spiffcommerce/core 43.1.1-alpha.0 → 43.1.1-alpha.1

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.
@@ -2874,7 +2874,7 @@ Minimum version required to store current data is: `+q+`.
2874
2874
  `;class dV{constructor(e,t=He.getShadowGraphqlClient.bind(He)){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 hV(r,e,t){return r.$source||(r.$source={}),r.$source[e]=t,r}const pV=r=>r?.body instanceof ReadableStream,fl=(r,e)=>{const t=[];if(r&&t.push(r),e)for(const n of e)t.push(n);return t},to=(r,e)=>`${r||"anonymous"}${e&&e.length>0?` (a.k.a. ${e.join(",")})`:""}`,yg=()=>{let r=[],e=[],t=!1;const n=new Set,i=d=>d.sort((f,h)=>IE[h.step]-IE[f.step]||DE[h.priority||"normal"]-DE[f.priority||"normal"]),a=d=>{let f=!1;const h=g=>{const v=fl(g.name,g.aliases);if(v.includes(d)){f=!0;for(const y of v)n.delete(y);return!1}return!0};return r=r.filter(h),e=e.filter(h),f},s=d=>{let f=!1;const h=g=>{if(g.middleware===d){f=!0;for(const v of fl(g.name,g.aliases))n.delete(v);return!1}return!0};return r=r.filter(h),e=e.filter(h),f},o=d=>(r.forEach(f=>{d.add(f.middleware,{...f})}),e.forEach(f=>{d.addRelativeTo(f.middleware,{...f})}),d.identifyOnResolve?.(c.identifyOnResolve()),d),l=d=>{const f=[];return d.before.forEach(h=>{h.before.length===0&&h.after.length===0?f.push(h):f.push(...l(h))}),f.push(d),d.after.reverse().forEach(h=>{h.before.length===0&&h.after.length===0?f.push(h):f.push(...l(h))}),f},u=(d=!1)=>{const f=[],h=[],g={};return r.forEach(y=>{const A={...y,before:[],after:[]};for(const C of fl(A.name,A.aliases))g[C]=A;f.push(A)}),e.forEach(y=>{const A={...y,before:[],after:[]};for(const C of fl(A.name,A.aliases))g[C]=A;h.push(A)}),h.forEach(y=>{if(y.toMiddleware){const A=g[y.toMiddleware];if(A===void 0){if(d)return;throw new Error(`${y.toMiddleware} is not found when adding ${to(y.name,y.aliases)} middleware ${y.relation} ${y.toMiddleware}`)}y.relation==="after"&&A.after.push(y),y.relation==="before"&&A.before.push(y)}}),i(f).map(l).reduce((y,A)=>(y.push(...A),y),[])},c={add:(d,f={})=>{const{name:h,override:g,aliases:v}=f,y={step:"initialize",priority:"normal",middleware:d,...f},A=fl(h,v);if(A.length>0){if(A.some(C=>n.has(C))){if(!g)throw new Error(`Duplicate middleware name '${to(h,v)}'`);for(const C of A){const k=r.findIndex(S=>S.name===C||S.aliases?.some(R=>R===C));if(k===-1)continue;const F=r[k];if(F.step!==y.step||y.priority!==F.priority)throw new Error(`"${to(F.name,F.aliases)}" middleware with ${F.priority} priority in ${F.step} step cannot be overridden by "${to(h,v)}" middleware with ${y.priority} priority in ${y.step} step.`);r.splice(k,1)}}for(const C of A)n.add(C)}r.push(y)},addRelativeTo:(d,f)=>{const{name:h,override:g,aliases:v}=f,y={middleware:d,...f},A=fl(h,v);if(A.length>0){if(A.some(C=>n.has(C))){if(!g)throw new Error(`Duplicate middleware name '${to(h,v)}'`);for(const C of A){const k=e.findIndex(S=>S.name===C||S.aliases?.some(R=>R===C));if(k===-1)continue;const F=e[k];if(F.toMiddleware!==y.toMiddleware||F.relation!==y.relation)throw new Error(`"${to(F.name,F.aliases)}" middleware ${F.relation} "${F.toMiddleware}" middleware cannot be overridden by "${to(h,v)}" middleware ${y.relation} "${y.toMiddleware}" middleware.`);e.splice(k,1)}}for(const C of A)n.add(C)}e.push(y)},clone:()=>o(yg()),use:d=>{d.applyToStack(c)},remove:d=>typeof d=="string"?a(d):s(d),removeByTag:d=>{let f=!1;const h=g=>{const{tags:v,name:y,aliases:A}=g;if(v&&v.includes(d)){const C=fl(y,A);for(const k of C)n.delete(k);return f=!0,!1}return!0};return r=r.filter(h),e=e.filter(h),f},concat:d=>{const f=o(yg());return f.use(d),f.identifyOnResolve(t||f.identifyOnResolve()||(d.identifyOnResolve?.()??!1)),f},applyToStack:o,identify:()=>u(!0).map(d=>{const f=d.step??d.relation+" "+d.toMiddleware;return to(d.name,d.aliases)+" - "+f}),identifyOnResolve(d){return typeof d=="boolean"&&(t=d),t},resolve:(d,f)=>{for(const h of u().map(g=>g.middleware).reverse())d=h(d,f);return t&&console.log(c.identify()),d}};return c},IE={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},DE={high:3,normal:2,low:1};var xd;(function(r){r.HTTP="http",r.HTTPS="https"})(xd||(xd={}));var Sd;(function(r){r.MD5="md5",r.CRC32="crc32",r.CRC32C="crc32c",r.SHA1="sha1",r.SHA256="sha256"})(Sd||(Sd={}));const gA="__smithy_context",mc=r=>r[gA]||(r[gA]={});class na{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 na({...e,headers:{...e.headers}});return t.query&&(t.query=gV(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 na.clone(this)}}function gV(r){return Object.keys(r).reduce((e,t)=>{const n=r[t];return{...e,[t]:Array.isArray(n)?[...n]:n}},{})}class ac{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 mV=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),Kg=(r,e=!1)=>{if(!e)return mV.test(r);const t=r.split(".");for(const n of t)if(!Kg(n))return!1;return!0},Ms=r=>{if(typeof r=="function")return r;const e=Promise.resolve(r);return()=>e};function vV(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 Ag=r=>{if(typeof r=="string")return Ag(new URL(r));const{hostname:e,pathname:t,port:n,protocol:i,search:a}=r;let s;return a&&(s=vV(a)),{hostname:e,port:n?parseInt(n):void 0,protocol:i,path:t,query:s}},N1=r=>{if(typeof r=="object"){if("url"in r){const e=Ag(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 Ag(r)},yV=r=>()=>Promise.reject(r);class AV{config;middlewareStack=yg();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 Wp=r=>typeof r=="function"?r():r,DI=(r,e,t,n,i)=>({name:e,namespace:r,traits:t,input:n,output:i}),bV=r=>(e,t)=>async n=>{const{response:i}=await e(n),{operationSchema:a}=mc(t),[,s,o,l,u,c]=a??[];try{const d=await r.protocol.deserializeResponse(DI(s,o,l,u,c),{...r,...t},i);return{response:i,output:d}}catch(d){if(Object.defineProperty(d,"$response",{value:i,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in d)){const f="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{d.message+=`
2875
2875
  `+f}catch{!t.logger||t.logger?.constructor?.name==="NoOpLogger"?console.warn(f):t.logger?.warn?.(f)}typeof d.$responseBodyText<"u"&&d.$response&&(d.$response.body=d.$responseBodyText);try{if(ac.isInstance(i)){const{headers:h={},statusCode:g}=i,v=Object.entries(h);d.$metadata={httpStatusCode:g,requestId:Bv(/^x-[\w-]+-request-?id$/,v),extendedRequestId:Bv(/^x-[\w-]+-id-2$/,v),cfId:Bv(/^x-[\w-]+-cf-id$/,v)}}}catch{}}throw d}},Bv=(r,e)=>(e.find(([t])=>t.match(r))||[void 0,void 0])[1],wV=r=>(e,t)=>async n=>{const{operationSchema:i}=mc(t),[,a,s,o,l,u]=i??[],c=t.endpointV2?async()=>N1(t.endpointV2):r.endpoint,d=await r.protocol.serializeRequest(DI(a,s,o,l,u),n.input,{...r,...t,endpoint:c});return e({...n,request:d})},CV={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},xV={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function SV(r){return{applyToStack:e=>{e.add(wV(r),xV),e.add(bV(r),CV),r.protocol.setSerdeContext(r)}}}const Mv=[];function $f(r){if(typeof r=="object")return r;if(r=r|0,Mv[r])return Mv[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 Mv[r]=e}const kf={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},_v=[],Nv={};class vi{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=vi.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;Lv(i);)n.push(i[1]),i=i[0],a=Wp(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,$f(o))}}else this.memberTraits=0;if(a instanceof vi){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=Wp(a),EV(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(_v[e])return _v[e]}else if(typeof e=="string"){if(Nv[e])return Nv[e]}else if(t&&e[kf.ns])return e[kf.ns];const n=Wp(e);if(n instanceof vi)return n;if(Lv(n)){const[a,s]=n;if(a instanceof vi)return Object.assign(a.getMergedTraits(),$f(s)),a;throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(e,null,2)}.`)}const i=new vi(n);return t?e[kf.ns]=i:typeof n=="string"?Nv[n]=i:typeof n=="number"?_v[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 $f(this.memberTraits)}getOwnTraits(){return $f(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 Tf([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 Tf([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 Tf(Lv(i)?i:[i,0],e)}if(this.isDocumentSchema())return Tf([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[kf.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=Tf([e[5][i],0],a);yield n[i]=[a,s]}e[kf.it]=n}}function Tf(r,e){if(r instanceof vi)return Object.assign(r,{memberName:e,_isMemberSchema:!0});const t=vi;return new t(r,e)}const Lv=r=>Array.isArray(r)&&r.length===2,EV=r=>Array.isArray(r)&&r.length>=5;class Zi{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 Zi.registries.has(e)||Zi.registries.set(e,new Zi(e)),Zi.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,Zi.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,Zi.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):Zi.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 Uv="***SensitiveInformation***";function mA(r,e){if(e==null)return e;const t=vi.of(r);if(t.getMergedTraits().sensitive)return Uv;if(t.isListSchema()){if(!!t.getValueSchema().getMergedTraits().sensitive)return Uv}else if(t.isMapSchema()){if(!!t.getKeySchema().getMergedTraits().sensitive||!!t.getValueSchema().getMergedTraits().sensitive)return Uv}else if(t.isStructSchema()&&typeof e=="object"){const n=e,i={};for(const[a,s]of t.structIterator())n[a]!=null&&(i[a]=mA(s,n[a]));return i}return e}class L1{middlewareStack=yg();schema;static classBuilder(){return new kV}resolveMiddlewareWithContext(e,t,n,{middlewareFn:i,clientName:a,commandName:s,inputFilterSensitiveLog:o,outputFilterSensitiveLog:l,smithyContext:u,additionalContext:c,CommandCtor:d}){for(const A of i.bind(this)(d,e,t,n))this.middlewareStack.use(A);const f=e.concat(this.middlewareStack),{logger:h}=t,g={logger:h,clientName:a,commandName:s,inputFilterSensitiveLog:o,outputFilterSensitiveLog:l,[gA]:{commandInstance:this,...u},...c},{requestHandler:v}=t;let y=n??{};return u.eventStream&&(y={isEventStream:!0,...y}),f.resolve(A=>v.handle(A.request,y),g)}}class kV{_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 L1{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?mA.bind(null,o):u=>u),outputFilterSensitiveLog:e._outputFilterSensitiveLog??(s?mA.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 PE=(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},TV=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{}}},PI=Object.values(Sd),FV=r=>{const e=[];for(const t in Sd){const n=Sd[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();PI.includes(n)?r.checksumAlgorithms[n.toUpperCase()]=i:r.checksumAlgorithms[n]=i,e.push(t)},checksumAlgorithms(){return e}}},IV=r=>{const e={};return r.checksumAlgorithms().forEach(t=>{const n=t.algorithmId();PI.includes(n)&&(e[n]=t.checksumConstructor())}),e},DV=r=>({setRetryStrategy(e){r.retryStrategy=e},retryStrategy(){return r.retryStrategy}}),PV=r=>{const e={};return e.retryStrategy=r.retryStrategy(),e},RV=r=>Object.assign(FV(r),DV(r)),OV=r=>Object.assign(IV(r),PV(r));class RI{trace(){}debug(){}info(){}warn(){}error(){}}const OI="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",RE=Object.entries(OI).reduce((r,[e,t])=>(r[t]=Number(e),r),{}),BV=OI.split(""),ju=6,ed=8,MV=63,Zg=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 RE))throw new TypeError(`Invalid character ${r[u]} in base64 string.`);a|=RE[r[u]]<<(c-u)*ju,s+=ju}else a>>=ju;const o=i/4*3;a>>=s%ed;const l=Math.floor(s/ed);for(let u=0;u<l;u++){const c=(l-u-1)*ed;n.setUint8(o+u,(a&255<<c)>>c)}}return new Uint8Array(t)},El=r=>new TextEncoder().encode(r);function bg(r){let e;typeof r=="string"?e=El(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)*ed,o+=ed;const l=Math.ceil(o/ju);s<<=l*ju-o;for(let u=1;u<=l;u++){const c=(l-u)*ju;i+=BV[(s&MV<<c)>>c]}i+="==".slice(0,4-l)}return i}function _V(r,e,t,n){return class Qp extends Uint8Array{static fromString(a,s="utf-8"){if(typeof a=="string")return s==="base64"?Qp.mutate(n(a)):Qp.mutate(e(a));throw new Error(`Unsupported conversion from ${typeof a} to Uint8ArrayBlobAdapter.`)}static mutate(a){return Object.setPrototypeOf(a,Qp.prototype),a}transformToString(a="utf-8"){return a==="base64"?t(this):r(this)}}}const em=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)},Ii=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function NV(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,Ii[e[0]]+Ii[e[1]]+Ii[e[2]]+Ii[e[3]]+"-"+Ii[e[4]]+Ii[e[5]]+"-"+Ii[e[6]]+Ii[e[7]]+"-"+Ii[e[8]]+Ii[e[9]]+"-"+Ii[e[10]]+Ii[e[11]]+Ii[e[12]]+Ii[e[13]]+Ii[e[14]]+Ii[e[15]]}}const vA=r=>{if(r!=null){if(typeof r=="string"){const e=parseFloat(r);if(!Number.isNaN(e))return String(e)!==String(r)&&qV.warn(GV(`Expected number but observed string: ${r}`)),e}if(typeof r=="number")return r;throw new TypeError(`Expected number, got ${typeof r}: ${r}`)}},LV=Math.ceil(2**127*(2-2**-23)),OE=r=>{const e=vA(r);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>LV)throw new TypeError(`Expected 32-bit float, got ${r}`);return e},UV=r=>{if(r!=null){if(Number.isInteger(r)&&!Number.isNaN(r))return r;throw new TypeError(`Expected integer, got ${typeof r}: ${r}`)}},BE=r=>BI(r,16),ME=r=>BI(r,8),BI=(r,e)=>{const t=UV(r);if(t!==void 0&&VV(t,e)!==t)throw new TypeError(`Expected ${e}-bit integer, got ${r}`);return t},VV=(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]}},zV=r=>vA(typeof r=="string"?tm(r):r),$V=r=>OE(typeof r=="string"?tm(r):r),HV=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,tm=r=>{const e=r.match(HV);if(e===null||e[0].length!==r.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(r)},wg=r=>BE(typeof r=="string"?tm(r):r),jV=r=>ME(typeof r=="string"?tm(r):r),GV=r=>String(new TypeError(r).stack||r).split(`
2876
2876
  `).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
2877
- `),qV={warn:console.warn},WV=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],U1=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function QV(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}`,d=o<10?`0${o}`:`${o}`;return`${WV[n]}, ${l} ${U1[t]} ${e} ${u}:${c}:${d} GMT`}const YV=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),XV=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");const e=YV.exec(r);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");const[t,n,i,a,s,o,l,u,c]=e,d=wg(Ed(n)),f=vo(i,"month",1,12),h=vo(a,"day",1,31),g=Yp(d,f,h,{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u});return c.toUpperCase()!="Z"&&g.setTime(g.getTime()-lz(c)),g},JV=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$/),KV=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$/),ZV=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})$/),MI=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=JV.exec(r);if(e){const[t,n,i,a,s,o,l,u]=e;return Yp(wg(Ed(a)),Vv(i),vo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u})}if(e=KV.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return nz(Yp(tz(a),Vv(i),vo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u}))}if(e=ZV.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return Yp(wg(Ed(u)),Vv(n),vo(i.trimLeft(),"day",1,31),{hours:a,minutes:s,seconds:o,fractionalMilliseconds:l})}throw new TypeError("Invalid RFC-7231 date-time value")},ez=r=>{if(r==null)return;let e;if(typeof r=="number")e=r;else if(typeof r=="string")e=zV(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))},Yp=(r,e,t,n)=>{const i=e-1;return az(r,i,t),new Date(Date.UTC(r,i,t,vo(n.hours,"hour",0,23),vo(n.minutes,"minute",0,59),vo(n.seconds,"seconds",0,60),oz(n.fractionalMilliseconds)))},tz=r=>{const e=new Date().getUTCFullYear(),t=Math.floor(e/100)*100+wg(Ed(r));return t<e?t+100:t},rz=50*365*24*60*60*1e3,nz=r=>r.getTime()-new Date().getTime()>rz?new Date(Date.UTC(r.getUTCFullYear()-100,r.getUTCMonth(),r.getUTCDate(),r.getUTCHours(),r.getUTCMinutes(),r.getUTCSeconds(),r.getUTCMilliseconds())):r,Vv=r=>{const e=U1.indexOf(r);if(e<0)throw new TypeError(`Invalid month: ${r}`);return e+1},iz=[31,28,31,30,31,30,31,31,30,31,30,31],az=(r,e,t)=>{let n=iz[e];if(e===1&&sz(r)&&(n=29),t>n)throw new TypeError(`Invalid day for ${U1[e]} in ${r}: ${t}`)},sz=r=>r%4===0&&(r%100!==0||r%400===0),vo=(r,e,t,n)=>{const i=jV(Ed(r));if(i<t||i>n)throw new TypeError(`${e} must be between ${t} and ${n}, inclusive`);return i},oz=r=>r==null?0:$V("0."+r)*1e3,lz=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},Ed=r=>{let e=0;for(;e<r.length-1&&r.charAt(e)==="0";)e++;return e===0?r:r.slice(e)},ho=function(e){return Object.assign(new String(e),{deserializeJSON(){return JSON.parse(String(e))},toString(){return String(e)},toJSON(){return String(e)}})};ho.from=r=>r&&typeof r=="object"&&(r instanceof ho||"deserializeJSON"in r)?r:typeof r=="string"||Object.getPrototypeOf(r)===String.prototype?ho(String(r)):ho(JSON.stringify(r));ho.fromObject=ho.from;const _E=/^-?\d*(\.\d+)?$/;class is{string;type;constructor(e,t){if(this.string=e,this.type=t,!_E.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 is.prototype.isPrototypeOf(e)||t.type==="bigDecimal"&&_E.test(t.string)}}const _I={},yA={};for(let r=0;r<256;r++){let e=r.toString(16).toLowerCase();e.length===1&&(e=`0${e}`),_I[r]=e,yA[e]=r}function NI(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 yA)e[t/2]=yA[n];else throw new Error(`Cannot decode unrecognized sequence ${n} as hexadecimal`)}return e}function yo(r){let e="";for(let t=0;t<r.byteLength;t++)e+=_I[r[t]];return e}const NE=typeof TextEncoder=="function"?new TextEncoder:null,uz=r=>{if(typeof r=="string"){if(NE)return NE.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}`)},kd=r=>typeof r=="string"?El(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(r),cz=r=>typeof ArrayBuffer=="function"&&r instanceof ArrayBuffer||Object.prototype.toString.call(r)==="[object ArrayBuffer]",LI=async r=>{},fz=async r=>{const e=r?.Bucket||"";if(typeof r.Bucket=="string"&&(r.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),mz(e)){if(r.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!gz(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},dz=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,hz=/(\d+\.){3}\d+/,pz=/\.\./,gz=r=>dz.test(r)&&!hz.test(r)&&!pz.test(r),mz=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},vz=(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 yz(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(N1(o)),n.isCustomEndpoint=!0)}const a=await Az(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 Az=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 vz(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 fz(n),n};function bz(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 wz(r){const e=yz(r);return({config:t,instructions:n})=>(i,a)=>async s=>{t.isCustomEndpoint&&bz(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=mc(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 Cz={name:"serializerMiddleware"},xz={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:Cz.name};function Sz(r){const e=wz(r);return(t,n)=>({applyToStack:i=>{i.addRelativeTo(e({config:t,instructions:n}),xz)}})}function Ez(r){return e=>{const t=e.tls??!0,{endpoint:n,useDualstackEndpoint:i,useFipsEndpoint:a}=e,s=n!=null?async()=>N1(await Ms(n)()):void 0,l=Object.assign(e,{endpoint:s,tls:t,isCustomEndpoint:!!n,useDualstackEndpoint:Ms(i??!1),useFipsEndpoint:Ms(a??!1)});let u;return l.serviceConfiguredEndpoint=async()=>(e.serviceId&&!u&&(u=r(e.serviceId)),u),l}}class V1{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 V1(e,t,n,i)}}class kz{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 Ma extends Error{constructor(e){super(e),this.name="EndpointError"}}const Tz="endpoints";function Cg(r){return typeof r!="object"||r==null?r:"ref"in r?`$${Cg(r.ref)}`:"fn"in r?`${r.fn}(${(r.argv||[]).map(Cg).join(", ")})`:JSON.stringify(r,null,2)}const z1={},Fz=(r,e)=>r===e;function Iz(...r){for(const e of r)if(e!=null)return e}const Dz=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 Ma(`Path: '${r}' does not end with ']'`);const a=n.slice(i+1,-1);if(Number.isNaN(parseInt(a)))throw new Ma(`Invalid array index: '${a}' in path: '${r}'`);i!==0&&t.push(n.slice(0,i)),t.push(a)}else t.push(n)}return t},UI=(r,e)=>Dz(e).reduce((t,n)=>{if(typeof t!="object")throw new Ma(`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),Pz=r=>r!=null;function Rz(r,e,t){return r?e:t}const Oz=r=>!r,Bz=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}$"),VI=r=>Bz.test(r)||r.startsWith("[")&&r.endsWith("]"),zv={[xd.HTTP]:80,[xd.HTTPS]:443},Mz=r=>{const e=(()=>{try{if(r instanceof URL)return r;if(typeof r=="object"&&"hostname"in r){const{hostname:f,port:h,protocol:g="",path:v="",query:y={}}=r,A=new URL(`${g}//${f}${h?`:${h}`:""}${v}`);return A.search=Object.entries(y).map(([C,k])=>`${C}=${k}`).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(xd).includes(l))return null;const u=VI(i),c=t.includes(`${n}:${zv[l]}`)||typeof r=="string"&&r.includes(`${n}:${zv[l]}`),d=`${n}${c?`:${zv[l]}`:""}`;return{scheme:l,authority:d,path:a,normalizedPath:a.endsWith("/")?a:`${a}/`,isIp:u}};function _z(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 Nz=(r,e)=>r===e,Lz=(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),Uz=r=>encodeURIComponent(r).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),Vz={booleanEquals:Fz,coalesce:Iz,getAttr:UI,isSet:Pz,isValidHostLabel:Kg,ite:Rz,not:Oz,parseURL:Mz,split:_z,stringEquals:Nz,substring:Lz,uriEncode:Uz},zI=(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(UI(n[u]??i[u],c))}else t.push(n[l]??i[l]);a=o+1}return t.join("")},zz=({ref:r},e)=>e.referenceRecord[r]??e.endpointParams[r],rm=(r,e,t)=>{if(typeof r=="string")return zI(r,t);if(r.fn)return HI.callFunction(r,t);if(r.ref)return zz(r,t);throw new Ma(`'${e}': ${String(r)} is not a string, function or reference.`)},$I=({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]=HI.evaluateExpression(o,"arg",t)}const i=r.indexOf(".");if(i!==-1){const o=z1[r.slice(0,i)]?.[r.slice(i+1)];if(typeof o=="function")return o(...n)}const a=Vz[r];if(typeof a=="function")return a(...n);throw new Error(`function ${r} not loaded in endpointFunctions.`)},HI={evaluateExpression:rm,callFunction:$I},$z=(r,e)=>{const{assign:t}=r;if(t&&t in e.referenceRecord)throw new Ma(`'${t}' is already defined in Reference Record.`);const n=$I(r,e);e.logger?.debug?.(`${Tz} evaluateCondition: ${Cg(r)} = ${Cg(n)}`);const i=n===""?!0:!!n;return t!=null?{result:i,toAssign:{name:t,value:n}}:{result:i}},Hz=(r,e)=>Object.entries(r??{}).reduce((t,[n,i])=>(t[n]=i.map(a=>{const s=rm(a,"Header value entry",e);if(typeof s!="string")throw new Ma(`Header '${n}' value '${s}' is not a string`);return s}),t),{}),jI=(r,e)=>Object.entries(r).reduce((t,[n,i])=>(t[n]=qI.getEndpointProperty(i,e),t),{}),GI=(r,e)=>{if(Array.isArray(r))return r.map(t=>GI(t,e));switch(typeof r){case"string":return zI(r,e);case"object":if(r===null)throw new Ma(`Unexpected endpoint property: ${r}`);return qI.getEndpointProperties(r,e);case"boolean":return r;default:throw new Ma(`Unexpected endpoint property type: ${typeof r}`)}},qI={getEndpointProperty:GI,getEndpointProperties:jI},jz=(r,e)=>{const t=rm(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 Ma(`Endpoint URL must be a string, got ${typeof t}`)},$v=1e8,Gz=(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<$v;){const u=3*(Math.abs(s)-1),[c,d,f]=[t[u],t[u+1],t[u+2]],[h,g,v]=a[c],y=$z({fn:h,assign:v,argv:g},l);if(y.toAssign){const{name:A,value:C}=y.toAssign;o[A]=C}s=s>=0===y.result?d:f}if(s>=$v){const u=i[s-$v];if(u[0]===-1){const[,h]=u;throw new Ma(rm(h,"Error",l))}const[c,d,f]=u;return{url:jz(c,l),properties:jI(d,l),headers:Hz(f??{},l)}}throw new Ma("No matching endpoint.")},qz=Ez(LI),WI=Sz(LI);class Hv extends _V(em,El,bg,Zg){}const Wz=r=>crypto.getRandomValues(r),QI=NV(Wz),Qz=QI,AA=async(r=new Uint8Array,e)=>{if(r instanceof Uint8Array)return Hv.mutate(r);if(!r)return Hv.mutate(new Uint8Array);const t=e.streamCollector(r);return Hv.mutate(await t)};class Yz{serdeContext;setSerdeContext(e){this.serdeContext=e}}class Xz extends Yz{options;compositeErrorRegistry;constructor(e){super(),this.options=e,this.compositeErrorRegistry=Zi.for(e.defaultNamespace);for(const t of e.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return na}getResponseType(){return ac}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=vi.of(t.input),a=$f(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-C_w5FtZy.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 Jz extends Xz{async serializeRequest(e,t,n){const i=this.serializer,a={},s={},o=await n.endpoint(),l=vi.of(e?.input),u=l.getSchema();let c;const d=t&&typeof t=="object"?t:{},f=new na({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:a,headers:s,body:void 0});if(o&&(this.updateServiceEndpoint(f,o),this.setHostPrefix(f,e,d)),d){const h=l.getEventStreamMember();if(h){if(d[h]){const g={};for(const[v,y]of l.structIterator())v!==h&&d[v]&&(i.write(y,d[v]),g[v]=i.flush());c=await this.serializeEventStream({eventStream:d[h],requestSchema:l,initialRequest:g})}}else i.write(u,d),c=i.flush()}return f.headers=Object.assign(f.headers,s),f.query=a,f.body=c,f.method="POST",f}async deserializeResponse(e,t,n){const i=this.deserializer,a=vi.of(e.output),s={};if(n.statusCode>=300){const l=await AA(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 AA(n.body,t);l.byteLength>0&&Object.assign(s,await i.read(a,l))}return s.$metadata=this.deserializeMetadata(n),s}}function YI(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 Kz=r=>({setHttpHandler(e){r.httpHandler=e},httpHandler(){return r.httpHandler},updateHttpClientConfig(e,t){r.httpHandler?.updateHttpClientConfig(e,t)},httpHandlerConfigs(){return r.httpHandler.httpHandlerConfigs()}}),Zz=r=>({httpHandler:r.httpHandler()}),LE="content-length";function e$(r){return e=>async t=>{const n=t.request;if(na.isInstance(n)){const{body:i,headers:a}=n;if(i&&Object.keys(a).map(s=>s.toLowerCase()).indexOf(LE)===-1)try{const s=r(i);n.headers={...n.headers,[LE]:String(s)}}catch{}}return e({...t,request:n})}}const t$={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},r$=r=>({applyToStack:e=>{e.add(e$(r.bodyLengthChecker),t$)}}),wl=r=>encodeURIComponent(r).replace(/[!'()*]/g,n$),n$=r=>`%${r.charCodeAt(0).toString(16).toUpperCase()}`;function i$(r){const e=[];for(let t of Object.keys(r).sort()){const n=r[t];if(t=wl(t),Array.isArray(n))for(let i=0,a=n.length;i<a;i++)e.push(`${t}=${wl(n[i])}`);else{let i=t;(n||typeof n=="string")&&(i+=`=${wl(n)}`),e.push(i)}}return e.join("&")}const a$=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],s$=["TimeoutError","RequestTimeout","RequestTimeoutException"],o$=[500,502,503,504],l$=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],u$=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],c$=r=>r?.$retryable!==void 0,f$=r=>r.$metadata?.clockSkewCorrected,d$=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},XI=r=>r.$metadata?.httpStatusCode===429||a$.includes(r.name)||r.$retryable?.throttling==!0,$1=(r,e=0)=>c$(r)||f$(r)||r.name==="InvalidSignatureException"&&r.message?.includes("Signature expired")||s$.includes(r.name)||l$.includes(r?.code||"")||u$.includes(r?.code||"")||o$.includes(r.$metadata?.httpStatusCode||0)||d$(r)||p$(r)||r.cause!==void 0&&e<=10&&$1(r.cause,e+1),h$=r=>{if(r.$metadata?.httpStatusCode!==void 0){const e=r.$metadata.httpStatusCode;return 500<=e&&e<=599&&!$1(r)}return!1};function p$(r){return r.code==="ERR_HTTP2_STREAM_ERROR"&&r.message.includes("NGHTTP2_REFUSED_STREAM")}const JI=20*1e3,UE=500,g$=1,m$="amz-sdk-invocation-id",v$="amz-sdk-request";function y$(r,e){if(ac.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=(MI(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 A$=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 b$(r){return e=>(t,n)=>async i=>{let a=await e.retryStrategy();const s=await e.maxAttempts();if(C$(a)){a=a;let o=await a.acquireInitialRetryToken((n.partition_id??"")+(n.__retryLongPoll?":longpoll":"")),l=new Error,u=0,c=0;const{request:d}=i,f=na.isInstance(d);for(f&&(d.headers[m$]=QI());;)try{f&&(d.headers[v$]=`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=x$(h,e.logger);if(l=A$(h),f&&r(d))throw(n.logger instanceof RI?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 v=o.getRetryDelay();c+=(o?.$retryLog?.acquisitionDelay??0)+v,v>0&&await w$(v)}}else return a=a,a?.mode&&(n.userAgent=[...n.userAgent||[],["cfg/retry-mode",a.mode]]),a.retry(t,i)}}const w$=r=>new Promise(e=>setTimeout(e,r)),C$=r=>typeof r.acquireInitialRetryToken<"u"&&typeof r.refreshRetryTokenForRetry<"u"&&typeof r.recordSuccess<"u",x$=(r,e)=>{const t={error:r,errorType:S$(r)},n=y$(r.$response,e);return n&&(t.retryAfterHint=n),t},S$=r=>XI(r)?"THROTTLING":$1(r)?"TRANSIENT":h$(r)?"SERVER_ERROR":"CLIENT_ERROR",E$={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function k$(r){const e=b$(r);return t=>({applyToStack:n=>{n.add(e(t),E$)}})}class H1{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"||XI(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=>H1.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 Ei{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return Ei.v2026?50:100}static throttlingDelay(){return Ei.v2026?1e3:500}static cost(){return Ei.v2026?14:5}static throttlingCost(){return Ei.v2026?5:10}static modifiedCostType(){return Ei.v2026?"THROTTLING":"TRANSIENT"}}class T${x=Ei.delay();computeNextBackoffDelay(e){const i=Math.random()*Math.min(this.x*2**e,JI);return Math.floor(i)}setDelayBase(e){this.x=e}}class VE{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(JI,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var Io;(function(r){r.STANDARD="standard",r.ADAPTIVE="adaptive"})(Io||(Io={}));const td=3,F$=Io.STANDARD,Sp={incompatible:1,attempts:2,capacity:3};class bA{mode=Io.STANDARD;retryBackoffStrategy;capacity=UE;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()=>td,this.baseDelay??=Ei.delay(),this.retryBackoffStrategy??=new T$}async acquireInitialRetryToken(e){return new VE(Ei.delay(),0,void 0,Ei.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"?Ei.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 d=new VE(0,e.getRetryCount()+1,c,e.isLongPoll?.()??!1);return await new Promise(f=>setTimeout(f,u)),d.$retryLog.acquisitionDelay=u,d}else{const c=Ei.v2026&&i===Sp.capacity&&s?u:0;c>0&&await new Promise(d=>setTimeout(d,c))}}throw new Error("No retry token available")}recordSuccess(e){this.capacity=Math.min(UE,this.capacity+(e.getRetryCost()??g$))}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 ${td}`),td}}retryCode(e,t,n){const i=e.getRetryCount()+1,a=this.isRetryableError(t.errorType)?0:Sp.incompatible,s=i<n?0:Sp.attempts,o=this.capacity>=this.getCapacityCost(t.errorType)?0:Sp.capacity;return a||s||o}getCapacityCost(e){return e===Ei.modifiedCostType()?Ei.throttlingCost():Ei.cost()}isRetryableError(e){return e==="THROTTLING"||e==="TRANSIENT"}}class I${mode=Io.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(e,t){const{rateLimiter:n}=t??{};this.rateLimiter=n??new H1,this.standardRetryStrategy=t?new bA({maxAttempts:typeof e=="number"?e:3,...t}):new bA(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 D$=(r,e)=>{const{retryStrategy:t,retryMode:n}=r,{defaultMaxAttempts:i=td,defaultBaseDelay:a=Ei.delay()}={},s=Ms(r.maxAttempts??i);let o=t?Promise.resolve(t):void 0;const l=async()=>{const u=await s();return await Ms(n)()===Io.ADAPTIVE?new I$(s,{maxAttempts:u,baseDelay:a}):new bA({maxAttempts:u,baseDelay:a})};return Object.assign(r,{maxAttempts:s,retryStrategy:()=>o??=l()})},P$=k$(pV);Ei.v2026||=typeof process=="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function Is(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 R$=r=>e=>async t=>{if(!na.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)},O$={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},B$=r=>({applyToStack:e=>{e.add(R$(r),O$)}}),M$=()=>(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,d=u??e.outputFilterSensitiveLog,{$metadata:f,...h}=n.output;return s?.info?.({clientName:i,commandName:a,input:c(t.input),output:d(h),metadata:f}),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}},_$={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},N$=r=>({applyToStack:e=>{e.add(M$(),_$)}}),L$=r=>({applyToStack:e=>{}}),U$=(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 V$(r){const e=new Map;for(const t of r)e.set(t.schemeId,t);return e}const z$=(r,e)=>(t,n)=>async i=>{const a=r.httpAuthSchemeProvider(await e.httpAuthSchemeParametersProvider(r,n,i.input)),s=r.authSchemePreference?await r.authSchemePreference():[],o=U$(a,s),l=V$(r.httpAuthSchemes),u=mc(n),c=[];for(const d of o){const f=l.get(d.schemeId);if(!f){c.push(`HttpAuthScheme \`${d.schemeId}\` was not enabled for this service.`);continue}const h=f.identityProvider(await e.identityProviderConfigProvider(r));if(!h){c.push(`HttpAuthScheme \`${d.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties:g={},signingProperties:v={}}=d.propertiesExtractor?.(r,n)||{};d.identityProperties=Object.assign(d.identityProperties||{},g),d.signingProperties=Object.assign(d.signingProperties||{},v),u.selectedHttpAuthScheme={httpAuthOption:d,identity:await h(d.identityProperties),signer:f.signer};break}if(!u.selectedHttpAuthScheme)throw new Error(c.join(`
2877
+ `),qV={warn:console.warn},WV=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],U1=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function QV(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}`,d=o<10?`0${o}`:`${o}`;return`${WV[n]}, ${l} ${U1[t]} ${e} ${u}:${c}:${d} GMT`}const YV=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),XV=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");const e=YV.exec(r);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");const[t,n,i,a,s,o,l,u,c]=e,d=wg(Ed(n)),f=vo(i,"month",1,12),h=vo(a,"day",1,31),g=Yp(d,f,h,{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u});return c.toUpperCase()!="Z"&&g.setTime(g.getTime()-lz(c)),g},JV=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$/),KV=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$/),ZV=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})$/),MI=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=JV.exec(r);if(e){const[t,n,i,a,s,o,l,u]=e;return Yp(wg(Ed(a)),Vv(i),vo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u})}if(e=KV.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return nz(Yp(tz(a),Vv(i),vo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u}))}if(e=ZV.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return Yp(wg(Ed(u)),Vv(n),vo(i.trimLeft(),"day",1,31),{hours:a,minutes:s,seconds:o,fractionalMilliseconds:l})}throw new TypeError("Invalid RFC-7231 date-time value")},ez=r=>{if(r==null)return;let e;if(typeof r=="number")e=r;else if(typeof r=="string")e=zV(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))},Yp=(r,e,t,n)=>{const i=e-1;return az(r,i,t),new Date(Date.UTC(r,i,t,vo(n.hours,"hour",0,23),vo(n.minutes,"minute",0,59),vo(n.seconds,"seconds",0,60),oz(n.fractionalMilliseconds)))},tz=r=>{const e=new Date().getUTCFullYear(),t=Math.floor(e/100)*100+wg(Ed(r));return t<e?t+100:t},rz=50*365*24*60*60*1e3,nz=r=>r.getTime()-new Date().getTime()>rz?new Date(Date.UTC(r.getUTCFullYear()-100,r.getUTCMonth(),r.getUTCDate(),r.getUTCHours(),r.getUTCMinutes(),r.getUTCSeconds(),r.getUTCMilliseconds())):r,Vv=r=>{const e=U1.indexOf(r);if(e<0)throw new TypeError(`Invalid month: ${r}`);return e+1},iz=[31,28,31,30,31,30,31,31,30,31,30,31],az=(r,e,t)=>{let n=iz[e];if(e===1&&sz(r)&&(n=29),t>n)throw new TypeError(`Invalid day for ${U1[e]} in ${r}: ${t}`)},sz=r=>r%4===0&&(r%100!==0||r%400===0),vo=(r,e,t,n)=>{const i=jV(Ed(r));if(i<t||i>n)throw new TypeError(`${e} must be between ${t} and ${n}, inclusive`);return i},oz=r=>r==null?0:$V("0."+r)*1e3,lz=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},Ed=r=>{let e=0;for(;e<r.length-1&&r.charAt(e)==="0";)e++;return e===0?r:r.slice(e)},ho=function(e){return Object.assign(new String(e),{deserializeJSON(){return JSON.parse(String(e))},toString(){return String(e)},toJSON(){return String(e)}})};ho.from=r=>r&&typeof r=="object"&&(r instanceof ho||"deserializeJSON"in r)?r:typeof r=="string"||Object.getPrototypeOf(r)===String.prototype?ho(String(r)):ho(JSON.stringify(r));ho.fromObject=ho.from;const _E=/^-?\d*(\.\d+)?$/;class is{string;type;constructor(e,t){if(this.string=e,this.type=t,!_E.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 is.prototype.isPrototypeOf(e)||t.type==="bigDecimal"&&_E.test(t.string)}}const _I={},yA={};for(let r=0;r<256;r++){let e=r.toString(16).toLowerCase();e.length===1&&(e=`0${e}`),_I[r]=e,yA[e]=r}function NI(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 yA)e[t/2]=yA[n];else throw new Error(`Cannot decode unrecognized sequence ${n} as hexadecimal`)}return e}function yo(r){let e="";for(let t=0;t<r.byteLength;t++)e+=_I[r[t]];return e}const NE=typeof TextEncoder=="function"?new TextEncoder:null,uz=r=>{if(typeof r=="string"){if(NE)return NE.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}`)},kd=r=>typeof r=="string"?El(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(r),cz=r=>typeof ArrayBuffer=="function"&&r instanceof ArrayBuffer||Object.prototype.toString.call(r)==="[object ArrayBuffer]",LI=async r=>{},fz=async r=>{const e=r?.Bucket||"";if(typeof r.Bucket=="string"&&(r.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),mz(e)){if(r.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!gz(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},dz=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,hz=/(\d+\.){3}\d+/,pz=/\.\./,gz=r=>dz.test(r)&&!hz.test(r)&&!pz.test(r),mz=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},vz=(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 yz(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(N1(o)),n.isCustomEndpoint=!0)}const a=await Az(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 Az=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 vz(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 fz(n),n};function bz(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 wz(r){const e=yz(r);return({config:t,instructions:n})=>(i,a)=>async s=>{t.isCustomEndpoint&&bz(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=mc(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 Cz={name:"serializerMiddleware"},xz={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:Cz.name};function Sz(r){const e=wz(r);return(t,n)=>({applyToStack:i=>{i.addRelativeTo(e({config:t,instructions:n}),xz)}})}function Ez(r){return e=>{const t=e.tls??!0,{endpoint:n,useDualstackEndpoint:i,useFipsEndpoint:a}=e,s=n!=null?async()=>N1(await Ms(n)()):void 0,l=Object.assign(e,{endpoint:s,tls:t,isCustomEndpoint:!!n,useDualstackEndpoint:Ms(i??!1),useFipsEndpoint:Ms(a??!1)});let u;return l.serviceConfiguredEndpoint=async()=>(e.serviceId&&!u&&(u=r(e.serviceId)),u),l}}class V1{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 V1(e,t,n,i)}}class kz{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 Ma extends Error{constructor(e){super(e),this.name="EndpointError"}}const Tz="endpoints";function Cg(r){return typeof r!="object"||r==null?r:"ref"in r?`$${Cg(r.ref)}`:"fn"in r?`${r.fn}(${(r.argv||[]).map(Cg).join(", ")})`:JSON.stringify(r,null,2)}const z1={},Fz=(r,e)=>r===e;function Iz(...r){for(const e of r)if(e!=null)return e}const Dz=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 Ma(`Path: '${r}' does not end with ']'`);const a=n.slice(i+1,-1);if(Number.isNaN(parseInt(a)))throw new Ma(`Invalid array index: '${a}' in path: '${r}'`);i!==0&&t.push(n.slice(0,i)),t.push(a)}else t.push(n)}return t},UI=(r,e)=>Dz(e).reduce((t,n)=>{if(typeof t!="object")throw new Ma(`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),Pz=r=>r!=null;function Rz(r,e,t){return r?e:t}const Oz=r=>!r,Bz=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}$"),VI=r=>Bz.test(r)||r.startsWith("[")&&r.endsWith("]"),zv={[xd.HTTP]:80,[xd.HTTPS]:443},Mz=r=>{const e=(()=>{try{if(r instanceof URL)return r;if(typeof r=="object"&&"hostname"in r){const{hostname:f,port:h,protocol:g="",path:v="",query:y={}}=r,A=new URL(`${g}//${f}${h?`:${h}`:""}${v}`);return A.search=Object.entries(y).map(([C,k])=>`${C}=${k}`).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(xd).includes(l))return null;const u=VI(i),c=t.includes(`${n}:${zv[l]}`)||typeof r=="string"&&r.includes(`${n}:${zv[l]}`),d=`${n}${c?`:${zv[l]}`:""}`;return{scheme:l,authority:d,path:a,normalizedPath:a.endsWith("/")?a:`${a}/`,isIp:u}};function _z(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 Nz=(r,e)=>r===e,Lz=(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),Uz=r=>encodeURIComponent(r).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),Vz={booleanEquals:Fz,coalesce:Iz,getAttr:UI,isSet:Pz,isValidHostLabel:Kg,ite:Rz,not:Oz,parseURL:Mz,split:_z,stringEquals:Nz,substring:Lz,uriEncode:Uz},zI=(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(UI(n[u]??i[u],c))}else t.push(n[l]??i[l]);a=o+1}return t.join("")},zz=({ref:r},e)=>e.referenceRecord[r]??e.endpointParams[r],rm=(r,e,t)=>{if(typeof r=="string")return zI(r,t);if(r.fn)return HI.callFunction(r,t);if(r.ref)return zz(r,t);throw new Ma(`'${e}': ${String(r)} is not a string, function or reference.`)},$I=({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]=HI.evaluateExpression(o,"arg",t)}const i=r.indexOf(".");if(i!==-1){const o=z1[r.slice(0,i)]?.[r.slice(i+1)];if(typeof o=="function")return o(...n)}const a=Vz[r];if(typeof a=="function")return a(...n);throw new Error(`function ${r} not loaded in endpointFunctions.`)},HI={evaluateExpression:rm,callFunction:$I},$z=(r,e)=>{const{assign:t}=r;if(t&&t in e.referenceRecord)throw new Ma(`'${t}' is already defined in Reference Record.`);const n=$I(r,e);e.logger?.debug?.(`${Tz} evaluateCondition: ${Cg(r)} = ${Cg(n)}`);const i=n===""?!0:!!n;return t!=null?{result:i,toAssign:{name:t,value:n}}:{result:i}},Hz=(r,e)=>Object.entries(r??{}).reduce((t,[n,i])=>(t[n]=i.map(a=>{const s=rm(a,"Header value entry",e);if(typeof s!="string")throw new Ma(`Header '${n}' value '${s}' is not a string`);return s}),t),{}),jI=(r,e)=>Object.entries(r).reduce((t,[n,i])=>(t[n]=qI.getEndpointProperty(i,e),t),{}),GI=(r,e)=>{if(Array.isArray(r))return r.map(t=>GI(t,e));switch(typeof r){case"string":return zI(r,e);case"object":if(r===null)throw new Ma(`Unexpected endpoint property: ${r}`);return qI.getEndpointProperties(r,e);case"boolean":return r;default:throw new Ma(`Unexpected endpoint property type: ${typeof r}`)}},qI={getEndpointProperty:GI,getEndpointProperties:jI},jz=(r,e)=>{const t=rm(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 Ma(`Endpoint URL must be a string, got ${typeof t}`)},$v=1e8,Gz=(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<$v;){const u=3*(Math.abs(s)-1),[c,d,f]=[t[u],t[u+1],t[u+2]],[h,g,v]=a[c],y=$z({fn:h,assign:v,argv:g},l);if(y.toAssign){const{name:A,value:C}=y.toAssign;o[A]=C}s=s>=0===y.result?d:f}if(s>=$v){const u=i[s-$v];if(u[0]===-1){const[,h]=u;throw new Ma(rm(h,"Error",l))}const[c,d,f]=u;return{url:jz(c,l),properties:jI(d,l),headers:Hz(f??{},l)}}throw new Ma("No matching endpoint.")},qz=Ez(LI),WI=Sz(LI);class Hv extends _V(em,El,bg,Zg){}const Wz=r=>crypto.getRandomValues(r),QI=NV(Wz),Qz=QI,AA=async(r=new Uint8Array,e)=>{if(r instanceof Uint8Array)return Hv.mutate(r);if(!r)return Hv.mutate(new Uint8Array);const t=e.streamCollector(r);return Hv.mutate(await t)};class Yz{serdeContext;setSerdeContext(e){this.serdeContext=e}}class Xz extends Yz{options;compositeErrorRegistry;constructor(e){super(),this.options=e,this.compositeErrorRegistry=Zi.for(e.defaultNamespace);for(const t of e.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return na}getResponseType(){return ac}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=vi.of(t.input),a=$f(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-Btllo-9n.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 Jz extends Xz{async serializeRequest(e,t,n){const i=this.serializer,a={},s={},o=await n.endpoint(),l=vi.of(e?.input),u=l.getSchema();let c;const d=t&&typeof t=="object"?t:{},f=new na({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:a,headers:s,body:void 0});if(o&&(this.updateServiceEndpoint(f,o),this.setHostPrefix(f,e,d)),d){const h=l.getEventStreamMember();if(h){if(d[h]){const g={};for(const[v,y]of l.structIterator())v!==h&&d[v]&&(i.write(y,d[v]),g[v]=i.flush());c=await this.serializeEventStream({eventStream:d[h],requestSchema:l,initialRequest:g})}}else i.write(u,d),c=i.flush()}return f.headers=Object.assign(f.headers,s),f.query=a,f.body=c,f.method="POST",f}async deserializeResponse(e,t,n){const i=this.deserializer,a=vi.of(e.output),s={};if(n.statusCode>=300){const l=await AA(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 AA(n.body,t);l.byteLength>0&&Object.assign(s,await i.read(a,l))}return s.$metadata=this.deserializeMetadata(n),s}}function YI(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 Kz=r=>({setHttpHandler(e){r.httpHandler=e},httpHandler(){return r.httpHandler},updateHttpClientConfig(e,t){r.httpHandler?.updateHttpClientConfig(e,t)},httpHandlerConfigs(){return r.httpHandler.httpHandlerConfigs()}}),Zz=r=>({httpHandler:r.httpHandler()}),LE="content-length";function e$(r){return e=>async t=>{const n=t.request;if(na.isInstance(n)){const{body:i,headers:a}=n;if(i&&Object.keys(a).map(s=>s.toLowerCase()).indexOf(LE)===-1)try{const s=r(i);n.headers={...n.headers,[LE]:String(s)}}catch{}}return e({...t,request:n})}}const t$={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},r$=r=>({applyToStack:e=>{e.add(e$(r.bodyLengthChecker),t$)}}),wl=r=>encodeURIComponent(r).replace(/[!'()*]/g,n$),n$=r=>`%${r.charCodeAt(0).toString(16).toUpperCase()}`;function i$(r){const e=[];for(let t of Object.keys(r).sort()){const n=r[t];if(t=wl(t),Array.isArray(n))for(let i=0,a=n.length;i<a;i++)e.push(`${t}=${wl(n[i])}`);else{let i=t;(n||typeof n=="string")&&(i+=`=${wl(n)}`),e.push(i)}}return e.join("&")}const a$=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],s$=["TimeoutError","RequestTimeout","RequestTimeoutException"],o$=[500,502,503,504],l$=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],u$=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],c$=r=>r?.$retryable!==void 0,f$=r=>r.$metadata?.clockSkewCorrected,d$=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},XI=r=>r.$metadata?.httpStatusCode===429||a$.includes(r.name)||r.$retryable?.throttling==!0,$1=(r,e=0)=>c$(r)||f$(r)||r.name==="InvalidSignatureException"&&r.message?.includes("Signature expired")||s$.includes(r.name)||l$.includes(r?.code||"")||u$.includes(r?.code||"")||o$.includes(r.$metadata?.httpStatusCode||0)||d$(r)||p$(r)||r.cause!==void 0&&e<=10&&$1(r.cause,e+1),h$=r=>{if(r.$metadata?.httpStatusCode!==void 0){const e=r.$metadata.httpStatusCode;return 500<=e&&e<=599&&!$1(r)}return!1};function p$(r){return r.code==="ERR_HTTP2_STREAM_ERROR"&&r.message.includes("NGHTTP2_REFUSED_STREAM")}const JI=20*1e3,UE=500,g$=1,m$="amz-sdk-invocation-id",v$="amz-sdk-request";function y$(r,e){if(ac.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=(MI(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 A$=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 b$(r){return e=>(t,n)=>async i=>{let a=await e.retryStrategy();const s=await e.maxAttempts();if(C$(a)){a=a;let o=await a.acquireInitialRetryToken((n.partition_id??"")+(n.__retryLongPoll?":longpoll":"")),l=new Error,u=0,c=0;const{request:d}=i,f=na.isInstance(d);for(f&&(d.headers[m$]=QI());;)try{f&&(d.headers[v$]=`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=x$(h,e.logger);if(l=A$(h),f&&r(d))throw(n.logger instanceof RI?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 v=o.getRetryDelay();c+=(o?.$retryLog?.acquisitionDelay??0)+v,v>0&&await w$(v)}}else return a=a,a?.mode&&(n.userAgent=[...n.userAgent||[],["cfg/retry-mode",a.mode]]),a.retry(t,i)}}const w$=r=>new Promise(e=>setTimeout(e,r)),C$=r=>typeof r.acquireInitialRetryToken<"u"&&typeof r.refreshRetryTokenForRetry<"u"&&typeof r.recordSuccess<"u",x$=(r,e)=>{const t={error:r,errorType:S$(r)},n=y$(r.$response,e);return n&&(t.retryAfterHint=n),t},S$=r=>XI(r)?"THROTTLING":$1(r)?"TRANSIENT":h$(r)?"SERVER_ERROR":"CLIENT_ERROR",E$={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function k$(r){const e=b$(r);return t=>({applyToStack:n=>{n.add(e(t),E$)}})}class H1{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"||XI(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=>H1.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 Ei{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return Ei.v2026?50:100}static throttlingDelay(){return Ei.v2026?1e3:500}static cost(){return Ei.v2026?14:5}static throttlingCost(){return Ei.v2026?5:10}static modifiedCostType(){return Ei.v2026?"THROTTLING":"TRANSIENT"}}class T${x=Ei.delay();computeNextBackoffDelay(e){const i=Math.random()*Math.min(this.x*2**e,JI);return Math.floor(i)}setDelayBase(e){this.x=e}}class VE{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(JI,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var Io;(function(r){r.STANDARD="standard",r.ADAPTIVE="adaptive"})(Io||(Io={}));const td=3,F$=Io.STANDARD,Sp={incompatible:1,attempts:2,capacity:3};class bA{mode=Io.STANDARD;retryBackoffStrategy;capacity=UE;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()=>td,this.baseDelay??=Ei.delay(),this.retryBackoffStrategy??=new T$}async acquireInitialRetryToken(e){return new VE(Ei.delay(),0,void 0,Ei.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"?Ei.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 d=new VE(0,e.getRetryCount()+1,c,e.isLongPoll?.()??!1);return await new Promise(f=>setTimeout(f,u)),d.$retryLog.acquisitionDelay=u,d}else{const c=Ei.v2026&&i===Sp.capacity&&s?u:0;c>0&&await new Promise(d=>setTimeout(d,c))}}throw new Error("No retry token available")}recordSuccess(e){this.capacity=Math.min(UE,this.capacity+(e.getRetryCost()??g$))}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 ${td}`),td}}retryCode(e,t,n){const i=e.getRetryCount()+1,a=this.isRetryableError(t.errorType)?0:Sp.incompatible,s=i<n?0:Sp.attempts,o=this.capacity>=this.getCapacityCost(t.errorType)?0:Sp.capacity;return a||s||o}getCapacityCost(e){return e===Ei.modifiedCostType()?Ei.throttlingCost():Ei.cost()}isRetryableError(e){return e==="THROTTLING"||e==="TRANSIENT"}}class I${mode=Io.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(e,t){const{rateLimiter:n}=t??{};this.rateLimiter=n??new H1,this.standardRetryStrategy=t?new bA({maxAttempts:typeof e=="number"?e:3,...t}):new bA(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 D$=(r,e)=>{const{retryStrategy:t,retryMode:n}=r,{defaultMaxAttempts:i=td,defaultBaseDelay:a=Ei.delay()}={},s=Ms(r.maxAttempts??i);let o=t?Promise.resolve(t):void 0;const l=async()=>{const u=await s();return await Ms(n)()===Io.ADAPTIVE?new I$(s,{maxAttempts:u,baseDelay:a}):new bA({maxAttempts:u,baseDelay:a})};return Object.assign(r,{maxAttempts:s,retryStrategy:()=>o??=l()})},P$=k$(pV);Ei.v2026||=typeof process=="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function Is(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 R$=r=>e=>async t=>{if(!na.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)},O$={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},B$=r=>({applyToStack:e=>{e.add(R$(r),O$)}}),M$=()=>(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,d=u??e.outputFilterSensitiveLog,{$metadata:f,...h}=n.output;return s?.info?.({clientName:i,commandName:a,input:c(t.input),output:d(h),metadata:f}),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}},_$={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},N$=r=>({applyToStack:e=>{e.add(M$(),_$)}}),L$=r=>({applyToStack:e=>{}}),U$=(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 V$(r){const e=new Map;for(const t of r)e.set(t.schemeId,t);return e}const z$=(r,e)=>(t,n)=>async i=>{const a=r.httpAuthSchemeProvider(await e.httpAuthSchemeParametersProvider(r,n,i.input)),s=r.authSchemePreference?await r.authSchemePreference():[],o=U$(a,s),l=V$(r.httpAuthSchemes),u=mc(n),c=[];for(const d of o){const f=l.get(d.schemeId);if(!f){c.push(`HttpAuthScheme \`${d.schemeId}\` was not enabled for this service.`);continue}const h=f.identityProvider(await e.identityProviderConfigProvider(r));if(!h){c.push(`HttpAuthScheme \`${d.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties:g={},signingProperties:v={}}=d.propertiesExtractor?.(r,n)||{};d.identityProperties=Object.assign(d.identityProperties||{},g),d.signingProperties=Object.assign(d.signingProperties||{},v),u.selectedHttpAuthScheme={httpAuthOption:d,identity:await h(d.identityProperties),signer:f.signer};break}if(!u.selectedHttpAuthScheme)throw new Error(c.join(`
2878
2878
  `));return t(i)},$$={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},H$=(r,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:t})=>({applyToStack:n=>{n.addRelativeTo(z$(r,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:t}),$$)}}),j$=r=>e=>{throw e},G$=(r,e)=>{},q$=r=>(e,t)=>async n=>{if(!na.isInstance(n.request))return e(n);const a=mc(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||j$)(s));return(l.successHandler||G$)(u.response,s),u},W$={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},Q$=r=>({applyToStack:e=>{e.addRelativeTo(q$(),W$)}}),rd=r=>{if(typeof r=="function")return r;const e=Promise.resolve(r);return()=>e};class Y${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 X${async sign(e,t,n){return e}}const J$=r=>function(t){return KI(t)&&t.expiration.getTime()-Date.now()<r},K$=3e5,Z$=J$(K$),KI=r=>r.expiration!==void 0,eH=(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))},tH=void 0;function rH(r){return r===void 0?!0:typeof r=="string"&&r.length<=50}function nH(r){const e=rd(r.userAgentAppId??tH),{customUserAgent:t}=r;return Object.assign(r,{customUserAgent:typeof t=="string"?[[t]]:t,userAgentAppId:async()=>{const n=await e();if(!rH(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 iH={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 aH=iH;const sH=r=>{const{partitions:e}=aH;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}},oH=/\d{12}\.ddb/;async function lH(r,e,t){if(t.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor"&&Is(r,"PROTOCOL_RPC_V2_CBOR","M"),typeof e.retryStrategy=="function"){const a=await e.retryStrategy();if(typeof a.mode=="string")switch(a.mode){case Io.ADAPTIVE:Is(r,"RETRY_MODE_ADAPTIVE","F");break;case Io.STANDARD:Is(r,"RETRY_MODE_STANDARD","E");break}}if(typeof e.accountIdEndpointMode=="function"){const a=r.endpointV2;switch(String(a?.url?.hostname).match(oH)&&Is(r,"ACCOUNT_ID_ENDPOINT","O"),await e.accountIdEndpointMode?.()){case"disabled":Is(r,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":Is(r,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":Is(r,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const i=r.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){const a=i;a.accountId&&Is(r,"RESOLVED_ACCOUNT_ID","T");for(const[s,o]of Object.entries(a.$source??{}))Is(r,s,o)}}const zE="user-agent",jv="x-amz-user-agent",$E=" ",Gv="/",uH=/[^!$%&'*+\-.^_`|~\w]/g,cH=/[^!$%&'*+\-.^_`|~\w#]/g,HE="-",fH=1024;function dH(r){let e="";for(const t in r){const n=r[t];if(e.length+n.length+1<=fH){e.length?e+=","+n:e+=n;continue}break}return e}const hH=r=>(e,t)=>async n=>{const{request:i}=n;if(!na.isInstance(i))return e(n);const{headers:a}=i,s=t?.userAgent?.map(Ep)||[],o=(await r.defaultUserAgentProvider()).map(Ep);await lH(t,r,n);const l=t;o.push(`m/${dH(Object.assign({},t.__smithy_context?.features,l.__aws_sdk_context?.features))}`);const u=r?.customUserAgent?.map(Ep)||[],c=await r.userAgentAppId();c&&o.push(Ep(["app",`${c}`]));const d=[].concat([...o,...s,...u]).join($E),f=[...o.filter(h=>h.startsWith("aws-sdk-")),...u].join($E);return r.runtime!=="browser"?(f&&(a[jv]=a[jv]?`${a[zE]} ${f}`:f),a[zE]=d):a[jv]=d,e({...n,request:i})},Ep=r=>{const e=r[0].split(Gv).map(s=>s.replace(uH,HE)).join(Gv),t=r[1]?.replace(cH,HE),n=e.indexOf(Gv),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}`}},"")},pH={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},gH=r=>({applyToStack:e=>{e.add(hH(r),pH)}}),mH=({serviceId:r,clientVersion:e})=>async t=>{const n=typeof window<"u"?window.navigator:void 0,i=n?.userAgent??"",a=n?.userAgentData?.platform??jE.os(i)??"other",s=void 0,o=n?.userAgentData?.brands??[],l=o[o.length-1],u=l?.brand??jE.browser(i)??"unknown",c=l?.version??"unknown",d=[["aws-sdk-js",e],["ua","2.1"],[`os/${a}`,s],["lang/js"],["md/browser",`${u}_${c}`]];r&&d.push([`api/${r}`,e]);const f=await t?.userAgentAppId?.();return f&&d.push([`app/${f}`]),d},jE={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"}},ZI=(r,e=!1)=>{if(e){for(const t of r.split("."))if(!ZI(t))return!1;return!0}return!(!Kg(r)||r.length<3||r.length>63||r!==r.toLowerCase()||VI(r))},GE=":",vH="/",yH=r=>{const e=r.split(GE);if(e.length<6)return null;const[t,n,i,a,s,...o]=e;if(t!=="arn"||n===""||i===""||o.join(GE)==="")return null;const l=o.map(u=>u.split(vH)).flat();return{partition:n,service:i,region:a,accountId:s,resourceId:l}},eD={isVirtualHostableS3Bucket:ZI,parseArn:yH,partition:sH};z1.aws=eD;const AH=(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)},qE=new Set,bH=(r,e=Kg)=>{if(!qE.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 qE.add(r)},tD=r=>typeof r=="string"&&(r.startsWith("fips-")||r.endsWith("-fips")),wH=r=>tD(r)?["fips-aws-global","aws-fips"].includes(r)?"us-east-1":r.replace(/fips-(dkr-|prod-)?|-fips/,""):r,CH=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=wH(n);return bH(i),i},useFipsEndpoint:async()=>{const n=typeof e=="string"?e:await e();return tD(n)?!0:typeof t!="function"?Promise.resolve(!!t):t()}})},xH=["in-region","cross-region","mobile","standard","legacy"],SH=({defaultsMode:r}={})=>AH(async()=>{const e=typeof r=="function"?await r():r;switch(e?.toLowerCase()){case"auto":return Promise.resolve(EH()?"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 ${xH.join(", ")}, got ${e}`)}}),EH=()=>{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},kH=!1,TH=!1,FH=r=>({setRegion(e){r.region=e},region(){return r.region}}),IH=r=>({region:r.region()}),WE=r=>ac.isInstance(r)?r.headers?.date??r.headers?.Date:void 0,rD=r=>new Date(Date.now()+r),DH=(r,e)=>Math.abs(rD(e).getTime()-r)>=3e5,QE=(r,e)=>{const t=Date.parse(r);return DH(t,e)?t-Date.now():e},nd=(r,e)=>{if(!e)throw new Error(`Property \`${r}\` is not resolved for AWS SDK SigV4Auth`);return e},PH=async r=>{const e=nd("context",r.context),t=nd("config",r.config),n=e.endpointV2?.properties?.authSchemes?.[0],a=await nd("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 RH{async sign(e,t,n){if(!na.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const i=await PH(n),{config:a,signer:s}=i;let{signingRegion:o,signingName:l}=i;const u=n.context;if(u?.authSchemes?.length??!1){const[d,f]=u.authSchemes;d?.name==="sigv4a"&&f?.name==="sigv4"&&(o=f?.signingRegion??o,l=f?.signingName??l)}return n._preRequestSystemClockOffset=a.systemClockOffset,await s.sign(e,{signingDate:rD(a.systemClockOffset),signingRegion:o,signingService:l})}errorHandler(e){return t=>{const n=t,i=n.ServerTime??WE(n.$response);if(i){const a=nd("config",e.config),s=e._preRequestSystemClockOffset,o=QE(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=WE(e);if(n){const i=nd("config",t.config);i.systemClockOffset=QE(n,i.systemClockOffset)}}}class OH{format(e){const t=[];for(const a of Object.keys(e)){const s=El(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=El(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(j1.fromNumber(e.value.valueOf()).bytes,1),c;case"uuid":if(!BH.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(NI(e.value.replace(/\-/g,"")),1),d}}}var YE;(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"})(YE||(YE={}));const BH=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class j1{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&&XE(t),new j1(t)}valueOf(){const e=this.bytes.slice(0),t=e[0]&128;return t&&XE(e),parseInt(yo(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function XE(r){for(let e=0;e<8;e++)r[e]^=255;for(let e=7;e>-1&&(r[e]++,r[e]===0);e--);}const MH="X-Amz-Algorithm",_H="X-Amz-Credential",nD="X-Amz-Date",NH="X-Amz-SignedHeaders",LH="X-Amz-Expires",iD="X-Amz-Signature",aD="X-Amz-Security-Token",sD="authorization",oD=nD.toLowerCase(),UH="date",VH=[sD,oD,UH],zH=iD.toLowerCase(),wA="x-amz-content-sha256",$H=aD.toLowerCase(),HH={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},jH=/^proxy-/,GH=/^sec-/,qv="AWS4-HMAC-SHA256",qH="AWS4-HMAC-SHA256-PAYLOAD",WH="UNSIGNED-PAYLOAD",QH=50,lD="aws4_request",YH=3600*24*7,XH=({query:r={}})=>{const e=[],t={};for(const n of Object.keys(r)){if(n.toLowerCase()===zH)continue;const i=wl(n);e.push(i);const a=r[n];typeof a=="string"?t[i]=`${i}=${wl(a)}`:Array.isArray(a)&&(t[i]=a.slice(0).reduce((s,o)=>s.concat([`${i}=${wl(o)}`]),[]).sort().join("&"))}return e.sort().map(n=>t[n]).filter(n=>n).join("&")},JH=r=>KH(r).toISOString().replace(/\.\d{3}Z$/,"Z"),KH=r=>typeof r=="number"?new Date(r*1e3):typeof r=="string"?Number(r)?new Date(Number(r)*1e3):new Date(r):r;class ZH{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=Ms(n),this.credentialProvider=Ms(t)}createCanonicalRequest(e,t,n){const i=Object.keys(t).sort();return`${e.method}
2879
2879
  ${this.getCanonicalPath(e)}
2880
2880
  ${XH(e)}
@@ -2887,7 +2887,7 @@ ${e}
2887
2887
  ${t}
2888
2888
  ${yo(s)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){const t=[];for(const a of e.split("/"))a?.length!==0&&a!=="."&&(a===".."?t.pop():t.push(a));const n=`${e?.startsWith("/")?"/":""}${t.join("/")}${t.length>0&&e?.endsWith("/")?"/":""}`;return wl(n).replace(/%2F/g,"/")}return e}validateResolvedCredentials(e){if(typeof e!="object"||typeof e.accessKeyId!="string"||typeof e.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}formatDate(e){const t=JH(e).replace(/[\-:]/g,"");return{longDate:t,shortDate:t.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}}const kp={},Wv=[],Qv=(r,e,t)=>`${r}/${e}/${t}/${lD}`,ej=async(r,e,t,n,i)=>{const a=await JE(r,e.secretAccessKey,e.accessKeyId),s=`${t}:${n}:${i}:${yo(a)}:${e.sessionToken}`;if(s in kp)return kp[s];for(Wv.push(s);Wv.length>QH;)delete kp[Wv.shift()];let o=`AWS4${e.secretAccessKey}`;for(const l of[t,n,i,lD])o=await JE(r,o,l);return kp[s]=o},JE=(r,e,t)=>{const n=new r(e);return n.update(kd(t)),n.digest()},KE=({headers:r},e,t)=>{const n={};for(const i of Object.keys(r).sort()){if(r[i]==null)continue;const a=i.toLowerCase();(a in HH||e?.has(a)||jH.test(a)||GH.test(a))&&(!t||t&&!t.has(a))||(n[a]=r[i].trim().replace(/\s+/g," "))}return n},Yv=async({headers:r,body:e},t)=>{for(const n of Object.keys(r))if(n.toLowerCase()===wA)return r[n];if(e==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if(typeof e=="string"||ArrayBuffer.isView(e)||cz(e)){const n=new t;return n.update(kd(e)),yo(await n.digest())}return WH},tj=(r,e)=>{r=r.toLowerCase();for(const t of Object.keys(e))if(r===t.toLowerCase())return!0;return!1},rj=(r,e={})=>{const{headers:t,query:n={}}=na.clone(r);for(const i of Object.keys(t)){const a=i.toLowerCase();(a.slice(0,6)==="x-amz-"&&!e.unhoistableHeaders?.has(a)||e.hoistableHeaders?.has(a))&&(n[i]=t[i],delete t[i])}return{...r,headers:t,query:n}},ZE=r=>{r=na.clone(r);for(const e of Object.keys(r.headers))VH.indexOf(e.toLowerCase())>-1&&delete r.headers[e];return r};class e2 extends ZH{headerFormatter=new OH;constructor({applyChecksum:e,credentials:t,region:n,service:i,sha256:a,uriEscapePath:s=!0}){super({applyChecksum:e,credentials:t,region:n,service:i,sha256:a,uriEscapePath:s})}async presign(e,t={}){const{signingDate:n=new Date,expiresIn:i=3600,unsignableHeaders:a,unhoistableHeaders:s,signableHeaders:o,hoistableHeaders:l,signingRegion:u,signingService:c}=t,d=await this.credentialProvider();this.validateResolvedCredentials(d);const f=u??await this.regionProvider(),{longDate:h,shortDate:g}=this.formatDate(n);if(i>YH)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");const v=Qv(g,f,c??this.service),y=rj(ZE(e),{unhoistableHeaders:s,hoistableHeaders:l});d.sessionToken&&(y.query[aD]=d.sessionToken),y.query[MH]=qv,y.query[_H]=`${d.accessKeyId}/${v}`,y.query[nD]=h,y.query[LH]=i.toString(10);const A=KE(y,a,o);return y.query[NH]=this.getCanonicalHeaderList(A),y.query[iD]=await this.getSignature(h,v,this.getSigningKey(d,f,g,c),this.createCanonicalRequest(y,A,await Yv(e,this.sha256))),y}async sign(e,t){return typeof e=="string"?this.signString(e,t):e.headers&&e.payload?this.signEvent(e,t):e.message?this.signMessage(e,t):this.signRequest(e,t)}async signEvent({headers:e,payload:t},{signingDate:n=new Date,priorSignature:i,signingRegion:a,signingService:s,eventStreamCredentials:o}){const l=a??await this.regionProvider(),{shortDate:u,longDate:c}=this.formatDate(n),d=Qv(u,l,s??this.service),f=await Yv({headers:{},body:t},this.sha256),h=new this.sha256;h.update(e);const g=yo(await h.digest()),v=[qH,c,d,i,g,f].join(`
2889
2889
  `);return this.signString(v,{signingDate:n,signingRegion:l,signingService:s,eventStreamCredentials:o})}async signMessage(e,{signingDate:t=new Date,signingRegion:n,signingService:i,eventStreamCredentials:a}){return this.signEvent({headers:this.headerFormatter.format(e.message.headers),payload:e.message.body},{signingDate:t,signingRegion:n,signingService:i,priorSignature:e.priorSignature,eventStreamCredentials:a}).then(o=>({message:e.message,signature:o}))}async signString(e,{signingDate:t=new Date,signingRegion:n,signingService:i,eventStreamCredentials:a}={}){const s=a??await this.credentialProvider();this.validateResolvedCredentials(s);const o=n??await this.regionProvider(),{shortDate:l}=this.formatDate(t),u=new this.sha256(await this.getSigningKey(s,o,l,i));return u.update(kd(e)),yo(await u.digest())}async signRequest(e,{signingDate:t=new Date,signableHeaders:n,unsignableHeaders:i,signingRegion:a,signingService:s}={}){const o=await this.credentialProvider();this.validateResolvedCredentials(o);const l=a??await this.regionProvider(),u=ZE(e),{longDate:c,shortDate:d}=this.formatDate(t),f=Qv(d,l,s??this.service);u.headers[oD]=c,o.sessionToken&&(u.headers[$H]=o.sessionToken);const h=await Yv(u,this.sha256);!tj(wA,u.headers)&&this.applyChecksum&&(u.headers[wA]=h);const g=KE(u,i,n),v=await this.getSignature(c,f,this.getSigningKey(o,l,d,s),this.createCanonicalRequest(u,g,h));return u.headers[sD]=`${qv} Credential=${o.accessKeyId}/${f}, SignedHeaders=${this.getCanonicalHeaderList(g)}, Signature=${v}`,u}async getSignature(e,t,n,i){const a=await this.createStringToSign(e,t,i,qv),s=new this.sha256(await n);return s.update(kd(a)),yo(await s.digest())}getSigningKey(e,t,n,i){return ej(this.sha256,e,n,t,i||this.service)}}const nj=r=>{let e=r.credentials,t=!!r.credentials,n;Object.defineProperty(r,"credentials",{set(u){u&&u!==e&&u!==n&&(t=!0),e=u;const c=ij(r,{credentials:e,credentialDefaultProvider:r.credentialDefaultProvider}),d=aj(r,c);if(t&&!d.attributed){const f=typeof e=="object"&&e!==null;n=async h=>{const v=await d(h);return f&&(!v.$source||Object.keys(v.$source).length===0)?hV(v,"CREDENTIALS_CODE","e"):v},n.memoized=d.memoized,n.configBound=d.configBound,n.attributed=!0}else n=d},get(){return n},enumerable:!0,configurable:!0}),r.credentials=e;const{signingEscapePath:i=!0,systemClockOffset:a=r.systemClockOffset||0,sha256:s}=r;let o;return r.signer?o=rd(r.signer):r.regionInfoProvider?o=()=>rd(r.region)().then(async u=>[await r.regionInfoProvider(u,{useFipsEndpoint:await r.useFipsEndpoint(),useDualstackEndpoint:await r.useDualstackEndpoint()})||{},u]).then(([u,c])=>{const{signingRegion:d,signingService:f}=u;r.signingRegion=r.signingRegion||d||c,r.signingName=r.signingName||f||r.serviceId;const h={...r,credentials:r.credentials,region:r.signingRegion,service:r.signingName,sha256:s,uriEscapePath:i},g=r.signerConstructor||e2;return new g(h)}):o=async u=>{u=Object.assign({},{name:"sigv4",signingName:r.signingName||r.defaultSigningName,signingRegion:await rd(r.region)(),properties:{}},u);const c=u.signingRegion,d=u.signingName;r.signingRegion=r.signingRegion||c,r.signingName=r.signingName||d||r.serviceId;const f={...r,credentials:r.credentials,region:r.signingRegion,service:r.signingName,sha256:s,uriEscapePath:i},h=r.signerConstructor||e2;return new h(f)},Object.assign(r,{systemClockOffset:a,signingEscapePath:i,signer:o})};function ij(r,{credentials:e,credentialDefaultProvider:t}){let n;return e?e?.memoized?n=e:n=eH(e,Z$,KI):t?n=rd(t(Object.assign({},r,{parentClientConfig:r}))):n=async()=>{throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")},n.memoized=!0,n}function aj(r,e){if(e.configBound)return e;const t=async n=>e({...n,callerClientConfig:r});return t.memoized=e.memoized,t.configBound=!0,t}const sj=async(r,e,t)=>({operation:mc(e).operation,region:await Ms(r.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function oj(r){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"cognito-idp",region:r.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}function Ur(r){return{schemeId:"smithy.api#noAuth"}}const lj=r=>{const e=[];switch(r.operation){case"AssociateSoftwareToken":{e.push(Ur());break}case"ChangePassword":{e.push(Ur());break}case"CompleteWebAuthnRegistration":{e.push(Ur());break}case"ConfirmDevice":{e.push(Ur());break}case"ConfirmForgotPassword":{e.push(Ur());break}case"ConfirmSignUp":{e.push(Ur());break}case"DeleteUser":{e.push(Ur());break}case"DeleteUserAttributes":{e.push(Ur());break}case"DeleteWebAuthnCredential":{e.push(Ur());break}case"ForgetDevice":{e.push(Ur());break}case"ForgotPassword":{e.push(Ur());break}case"GetDevice":{e.push(Ur());break}case"GetTokensFromRefreshToken":{e.push(Ur());break}case"GetUser":{e.push(Ur());break}case"GetUserAttributeVerificationCode":{e.push(Ur());break}case"GetUserAuthFactors":{e.push(Ur());break}case"GlobalSignOut":{e.push(Ur());break}case"InitiateAuth":{e.push(Ur());break}case"ListDevices":{e.push(Ur());break}case"ListWebAuthnCredentials":{e.push(Ur());break}case"ResendConfirmationCode":{e.push(Ur());break}case"RespondToAuthChallenge":{e.push(Ur());break}case"RevokeToken":{e.push(Ur());break}case"SetUserMFAPreference":{e.push(Ur());break}case"SetUserSettings":{e.push(Ur());break}case"SignUp":{e.push(Ur());break}case"StartWebAuthnRegistration":{e.push(Ur());break}case"UpdateAuthEventFeedback":{e.push(Ur());break}case"UpdateDeviceStatus":{e.push(Ur());break}case"UpdateUserAttributes":{e.push(Ur());break}case"VerifySoftwareToken":{e.push(Ur());break}case"VerifyUserAttribute":{e.push(Ur());break}default:e.push(oj(r))}return e},uj=r=>{const e=nj(r);return Object.assign(e,{authSchemePreference:Ms(r.authSchemePreference??[])})},cj=r=>Object.assign(r,{useDualstackEndpoint:r.useDualstackEndpoint??!1,useFipsEndpoint:r.useFipsEndpoint??!1,defaultSigningName:"cognito-idp"}),uD={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},fj="3.1075.0",dj={version:fj},hj=r=>new TextEncoder().encode(r);var pj=typeof Buffer<"u"&&Buffer.from?function(r){return Buffer.from(r,"utf8")}:hj;function Td(r){return r instanceof Uint8Array?r:typeof r=="string"?pj(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(r)}function CA(r){return typeof r=="string"?r.length===0:r.byteLength===0}var cD={name:"SHA-256"},t2={name:"HMAC",hash:cD},gj=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85]);const mj={};function Xp(){return typeof window<"u"?window:typeof self<"u"?self:mj}var vj=(function(){function r(e){this.toHash=new Uint8Array(0),this.secret=e,this.reset()}return r.prototype.update=function(e){if(!CA(e)){var t=Td(e),n=new Uint8Array(this.toHash.byteLength+t.byteLength);n.set(this.toHash,0),n.set(t,this.toHash.byteLength),this.toHash=n}},r.prototype.digest=function(){var e=this;return this.key?this.key.then(function(t){return Xp().crypto.subtle.sign(t2,t,e.toHash).then(function(n){return new Uint8Array(n)})}):CA(this.toHash)?Promise.resolve(gj):Promise.resolve().then(function(){return Xp().crypto.subtle.digest(cD,e.toHash)}).then(function(t){return Promise.resolve(new Uint8Array(t))})},r.prototype.reset=function(){var e=this;this.toHash=new Uint8Array(0),this.secret&&this.secret!==void 0&&(this.key=new Promise(function(t,n){Xp().crypto.subtle.importKey("raw",Td(e.secret),t2,!1,["sign"]).then(t,n)}),this.key.catch(function(){}))},r})(),ha=64,yj=32,Aj=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),bj=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],wj=Math.pow(2,53)-1,Jp=(function(){function r(){this.state=Int32Array.from(bj),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return r.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=0,n=e.byteLength;if(this.bytesHashed+=n,this.bytesHashed*8>wj)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===ha&&(this.hashBuffer(),this.bufferLength=0)},r.prototype.digest=function(){if(!this.finished){var e=this.bytesHashed*8,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(t.setUint8(this.bufferLength++,128),n%ha>=ha-8){for(var i=this.bufferLength;i<ha;i++)t.setUint8(i,0);this.hashBuffer(),this.bufferLength=0}for(var i=this.bufferLength;i<ha-8;i++)t.setUint8(i,0);t.setUint32(ha-8,Math.floor(e/4294967296),!0),t.setUint32(ha-4,e),this.hashBuffer(),this.finished=!0}for(var a=new Uint8Array(yj),i=0;i<8;i++)a[i*4]=this.state[i]>>>24&255,a[i*4+1]=this.state[i]>>>16&255,a[i*4+2]=this.state[i]>>>8&255,a[i*4+3]=this.state[i]>>>0&255;return a},r.prototype.hashBuffer=function(){for(var e=this,t=e.buffer,n=e.state,i=n[0],a=n[1],s=n[2],o=n[3],l=n[4],u=n[5],c=n[6],d=n[7],f=0;f<ha;f++){if(f<16)this.temp[f]=(t[f*4]&255)<<24|(t[f*4+1]&255)<<16|(t[f*4+2]&255)<<8|t[f*4+3]&255;else{var h=this.temp[f-2],g=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10;h=this.temp[f-15];var v=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3;this.temp[f]=(g+this.temp[f-7]|0)+(v+this.temp[f-16]|0)}var y=(((l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7))+(l&u^~l&c)|0)+(d+(Aj[f]+this.temp[f]|0)|0)|0,A=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&a^i&s^a&s)|0;d=c,c=u,u=l,l=o+y|0,o=s,s=a,a=i,i=y+A|0}n[0]+=i,n[1]+=a,n[2]+=s,n[3]+=o,n[4]+=l,n[5]+=u,n[6]+=c,n[7]+=d},r})(),Cj=(function(){function r(e){this.secret=e,this.hash=new Jp,this.reset()}return r.prototype.update=function(e){if(!(CA(e)||this.error))try{this.hash.update(Td(e))}catch(t){this.error=t}},r.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},r.prototype.digest=function(){return ts(this,void 0,void 0,function(){return rs(this,function(e){return[2,this.digestSync()]})})},r.prototype.reset=function(){if(this.hash=new Jp,this.secret){this.outer=new Jp;var e=xj(this.secret),t=new Uint8Array(ha);t.set(e);for(var n=0;n<ha;n++)e[n]^=54,t[n]^=92;this.hash.update(e),this.outer.update(t);for(var n=0;n<e.byteLength;n++)e[n]=0}},r})();function xj(r){var e=Td(r);if(e.byteLength>ha){var t=new Jp;t.update(e),e=t.digest()}var n=new Uint8Array(ha);return n.set(e),n}var Sj=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function Ej(r){if(kj(r)&&typeof r.crypto.subtle=="object"){var e=r.crypto.subtle;return Tj(e)}return!1}function kj(r){if(typeof r=="object"&&typeof r.crypto=="object"){var e=r.crypto.getRandomValues;return typeof e=="function"}return!1}function Tj(r){return r&&Sj.every(function(e){return typeof r[e]=="function"})}var Fj=(function(){function r(e){Ej(Xp())?this.hash=new vj(e):this.hash=new Cj(e)}return r.prototype.update=function(e,t){this.hash.update(Td(e))},r.prototype.digest=function(){return this.hash.digest()},r.prototype.reset=function(){this.hash.reset()},r})();function r2(r,e){return new Request(r,e)}function Ij(r=0){return new Promise((e,t)=>{r&&setTimeout(()=>{const n=new Error(`Request did not complete within ${r} ms`);n.name="TimeoutError",t(n)},r)})}const Xv={supported:void 0};class G1{config;configProvider;static create(e){return typeof e?.handle=="function"?e:new G1(e)}constructor(e){typeof e=="function"?this.configProvider=e().then(t=>t||{}):(this.config=e??{},this.configProvider=Promise.resolve(this.config)),Xv.supported===void 0&&(Xv.supported=typeof Request<"u"&&"keepalive"in r2("https://[::1]"))}destroy(){}async handle(e,{abortSignal:t,requestTimeout:n}={}){this.config||(this.config=await this.configProvider);const i=n??this.config.requestTimeout,a=this.config.keepAlive===!0,s=this.config.credentials;if(t?.aborted){const C=n2(t);return Promise.reject(C)}let o=e.path;const l=i$(e.query||{});l&&(o+=`?${l}`),e.fragment&&(o+=`#${e.fragment}`);let u="";if(e.username!=null||e.password!=null){const C=e.username??"",k=e.password??"";u=`${C}:${k}@`}const{port:c,method:d}=e,f=`${e.protocol}//${u}${e.hostname}${c?`:${c}`:""}${o}`,h=d==="GET"||d==="HEAD"?void 0:e.body,g={body:h,headers:new Headers(e.headers),method:d,credentials:s};this.config?.cache&&(g.cache=this.config.cache),h&&(g.duplex="half"),typeof AbortController<"u"&&(g.signal=t),Xv.supported&&(g.keepalive=a),typeof this.config.requestInit=="function"&&Object.assign(g,this.config.requestInit(e));let v=()=>{};const y=r2(f,g),A=[fetch(y).then(C=>{const k=C.headers,F={};for(const R of k.entries())F[R[0]]=R[1];return C.body!=null?{response:new ac({headers:F,reason:C.statusText,statusCode:C.status,body:C.body})}:C.blob().then(R=>({response:new ac({headers:F,reason:C.statusText,statusCode:C.status,body:R})}))}),Ij(i)];return t&&A.push(new Promise((C,k)=>{const F=()=>{const S=n2(t);k(S)};if(typeof t.addEventListener=="function"){const S=t;S.addEventListener("abort",F,{once:!0}),v=()=>S.removeEventListener("abort",F)}else t.onabort=F})),Promise.race(A).finally(v)}updateHttpClientConfig(e,t){this.config=void 0,this.configProvider=this.configProvider.then(n=>(n[e]=t,n))}httpHandlerConfigs(){return this.config??{}}}function n2(r){const e=r&&typeof r=="object"&&"reason"in r?r.reason:void 0;if(e){if(e instanceof Error){const i=new Error("Request aborted");return i.name="AbortError",i.cause=e,i}const n=new Error(String(e));return n.name="AbortError",n}const t=new Error("Request aborted");return t.name="AbortError",t}const Dj=async r=>typeof Blob=="function"&&r instanceof Blob||r.constructor?.name==="Blob"?Blob.prototype.arrayBuffer!==void 0?new Uint8Array(await r.arrayBuffer()):Pj(r):Rj(r);async function Pj(r){const e=await Oj(r),t=Zg(e);return new Uint8Array(t)}async function Rj(r){const e=[],t=r.getReader();let n=!1,i=0;for(;!n;){const{done:o,value:l}=await t.read();l&&(e.push(l),i+=l.length),n=o}const a=new Uint8Array(i);let s=0;for(const o of e)a.set(o,s),s+=o.length;return a}function Oj(r){return new Promise((e,t)=>{const n=new FileReader;n.onloadend=()=>{if(n.readyState!==2)return t(new Error("Reader aborted too early"));const i=n.result??"",a=i.indexOf(","),s=a>-1?a+1:i.length;e(i.substring(s))},n.onabort=()=>t(new Error("Read aborted")),n.onerror=()=>t(n.error),n.readAsDataURL(r)})}class Bj{queryCompat;errorRegistry;constructor(e=!1){this.queryCompat=e}resolveRestContentType(e,t){const n=t.getMemberSchemas(),i=Object.values(n).find(a=>!!a.getMergedTraits().httpPayload);if(i){const a=i.getMergedTraits().mediaType;return a||(i.isStringSchema()?"text/plain":i.isBlobSchema()?"application/octet-stream":e)}else if(!t.isUnitSchema()&&Object.values(n).find(s=>{const{httpQuery:o,httpQueryParams:l,httpHeader:u,httpLabel:c,httpPrefixHeaders:d}=s.getMergedTraits();return!o&&!l&&!u&&!c&&d===void 0}))return e}async getErrorSchemaOrThrowBaseException(e,t,n,i,a,s){let o=e;e.includes("#")&&([,o]=e.split("#"));const l={$metadata:a,$fault:n.statusCode<500?"client":"server"};if(!this.errorRegistry)throw new Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:s?.(this.errorRegistry,o)??this.errorRegistry.getSchema(e),errorMetadata:l}}catch{i.message=i.message??i.Message??"UnknownError";const c=this.errorRegistry,d=c.getBaseException();if(d){const g=c.getErrorCtor(d)??Error;throw this.decorateServiceException(Object.assign(new g({name:o}),l),i)}const f=i,h=f?.message??f?.Message??f?.Error?.Message??f?.Error?.message;throw this.decorateServiceException(Object.assign(new Error(h),{name:o},l),i)}}compose(e,t,n){let i=n;t.includes("#")&&([i]=t.split("#"));const a=Zi.for(i),s=Zi.for("smithy.ts.sdk.synthetic."+n);e.copyFrom(a),e.copyFrom(s),this.errorRegistry=e}decorateServiceException(e,t={}){if(this.queryCompat){const n=e.Message??t.Message,i=PE(e,t);n&&(i.message=n);const a=i.Error??{};a.Type=i.Error?.Type,a.Code=i.Error?.Code,a.Message=i.Error?.message??i.Error?.Message??n,i.Error=a;const s=i.$metadata.requestId;return s&&(i.RequestId=s),i}return PE(e,t)}setQueryCompatError(e,t){const n=t.headers?.["x-amzn-query-error"];if(e!==void 0&&n!=null){const[i,a]=n.split(";"),s=Object.keys(e),o={Code:i,Type:a};e.Code=i,e.Type=a;for(let l=0;l<s.length;l++){const u=s[l];o[u==="message"?"Message":u]=e[u]}delete o.__type,e.Error=o}}queryCompatOutput(e,t){e.Error&&(t.Error=e.Error),e.Type&&(t.Type=e.Type),e.Code&&(t.Code=e.Code)}findQueryCompatibleError(e,t){try{return e.getSchema(t)}catch{return e.find(i=>vi.of(i).getMergedTraits().awsQueryError?.[0]===t)}}}class q1{serdeContext;setSerdeContext(e){this.serdeContext=e}}class Mj{from;to;keys;constructor(e,t){this.from=e,this.to=t;const n=Object.keys(this.from),i=new Set(n);i.delete("__type"),this.keys=i}mark(e){this.keys.delete(e)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){const e=this.keys.values().next().value,t=this.from[e];this.to.$unknown=[e,t]}}}function _j(r,e,t){if(t?.source){const n=t.source;if(typeof e=="number"&&(e>Number.MAX_SAFE_INTEGER||e<Number.MIN_SAFE_INTEGER||n!==String(e)))return n.includes(".")?new is(n,"bigDecimal"):BigInt(n)}return e}const Nj=(r,e)=>AA(r,e).then(t=>(e?.utf8Encoder??em)(t)),Lj=(r,e)=>Nj(r,e).then(t=>{if(t.length)try{return JSON.parse(t)}catch(n){throw n?.name==="SyntaxError"&&Object.defineProperty(n,"$responseBodyText",{value:t}),n}return{}}),i2=(r,e)=>Object.keys(r).find(t=>t.toLowerCase()===e.toLowerCase()),Jv=r=>{let e=r;return typeof e=="number"&&(e=e.toString()),e.indexOf(",")>=0&&(e=e.split(",")[0]),e.indexOf(":")>=0&&(e=e.split(":")[0]),e.indexOf("#")>=0&&(e=e.split("#")[1]),e},Uj=(r,e,t=!1)=>Vj(r,e,t?["code","header","type"]:["type","code","header"]),Vj=({headers:r},e,t)=>{for(;t.length>0;)switch(t.shift()){case"header":const i=i2(r??{},"x-amzn-errortype");if(i!==void 0)return Jv(r[i]);break;case"code":const a=i2(e??{},"code");if(a&&e[a]!==void 0)return Jv(e[a]);break;case"type":if(e?.__type!==void 0)return Jv(e.__type);break}};class zj extends q1{settings;constructor(e){super(),this.settings=e}async read(e,t){return this._read(e,typeof t=="string"?JSON.parse(t,_j):await Lj(t,this.serdeContext))}readObject(e,t){return this._read(e,t)}_read(e,t){const n=t!==null&&typeof t=="object",i=vi.of(e);if(n){if(i.isStructSchema()){const s=t,o=i.isUnionSchema(),l={};let u;const{jsonName:c}=this.settings;c&&(u={});let d;o&&(d=new Mj(s,l));for(const[f,h]of i.structIterator()){let g=f;c&&(g=h.getMergedTraits().jsonName??g,u[g]=f),o&&d.mark(g),s[g]!=null&&(l[f]=this._read(h,s[g]))}if(o)d.writeUnknown();else if(typeof s.__type=="string")for(const f in s){const h=s[f],g=c?u[f]??f:f;g in l||(l[g]=h)}return l}if(Array.isArray(t)&&i.isListSchema()){const s=i.getValueSchema(),o=[];for(const l of t)o.push(this._read(s,l));return o}if(i.isMapSchema()){const s=i.getValueSchema(),o={};for(const l in t)o[l]=this._read(s,t[l]);return o}}if(i.isBlobSchema()&&typeof t=="string")return Zg(t);const a=i.getMergedTraits().mediaType;if(i.isStringSchema()&&typeof t=="string"&&a)return a==="application/json"||a.endsWith("+json")?ho.from(t):t;if(i.isTimestampSchema()&&t!=null)switch(YI(i,this.settings)){case 5:return XV(t);case 6:return MI(t);case 7:return ez(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(i.isBigIntegerSchema()&&(typeof t=="number"||typeof t=="string"))return BigInt(t);if(i.isBigDecimalSchema()&&t!=null){if(t instanceof is)return t;const s=t;return s.type==="bigDecimal"&&"string"in s?new is(s.string,s.type):new is(String(t),"bigDecimal")}if(i.isNumericSchema()&&typeof t=="string"){switch(t){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return t}if(i.isDocumentSchema())if(n){const s=Array.isArray(t)?[]:{};for(const o in t){const l=t[o];l instanceof is?s[o]=l:s[o]=this._read(i,l)}return s}else return structuredClone(t);return t}}const a2="Ν";class $j{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw new Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(e,t)=>{if(t instanceof is){const n=`${a2+"nv"+this.counter++}_`+t.string;return this.values.set(`"${n}"`,t.string),n}if(typeof t=="bigint"){const n=t.toString(),i=`${a2+"b"+this.counter++}_`+n;return this.values.set(`"${i}"`,n),i}return t}}replaceInJson(e){if(this.stage===0)throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return e;for(const[t,n]of this.values)e=e.replace(t,n);return e}}class Hj extends q1{settings;buffer;useReplacer=!1;rootSchema;constructor(e){super(),this.settings=e}write(e,t){this.rootSchema=vi.of(e),this.buffer=this._write(this.rootSchema,t)}flush(){const{rootSchema:e,useReplacer:t}=this;if(this.rootSchema=void 0,this.useReplacer=!1,e?.isStructSchema()||e?.isDocumentSchema()){if(!t)return JSON.stringify(this.buffer);const n=new $j;return n.replaceInJson(JSON.stringify(this.buffer,n.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(e,t){this.write(e,t),typeof this.buffer=="object"&&(this.buffer.__type=vi.of(e).getName(!0))}_write(e,t,n){const i=t!==null&&typeof t=="object",a=vi.of(e);if(i){if(a.isStructSchema()){const s=t,o={},{jsonName:l}=this.settings;let u;l&&(u={});let c=0;for(const[d,f]of a.structIterator()){const h=this._write(f,s[d],a);if(h!==void 0){let g=d;l&&(g=f.getMergedTraits().jsonName??d,u[d]=g),o[g]=h,c++}}if(a.isUnionSchema()&&c===0){const{$unknown:d}=s;if(Array.isArray(d)){const[f,h]=d;o[f]=this._write(15,h)}}else if(typeof s.__type=="string")for(const d in s){const f=s[d],h=l?u[d]??d:d;h in o||(o[h]=this._write(15,f))}return o}if(Array.isArray(t)&&a.isListSchema()){const s=a.getValueSchema(),o=[],l=!!a.getMergedTraits().sparse;for(const u of t)(l||u!=null)&&o.push(this._write(s,u));return o}if(a.isMapSchema()){const s=a.getValueSchema(),o={},l=!!a.getMergedTraits().sparse;for(const u in t){const c=t[u];(l||c!=null)&&(o[u]=this._write(s,c))}return o}if(t instanceof Uint8Array&&(a.isBlobSchema()||a.isDocumentSchema()))return a===this.rootSchema?t:(this.serdeContext?.base64Encoder??bg)(t);if(t instanceof Date&&(a.isTimestampSchema()||a.isDocumentSchema()))switch(YI(a,this.settings)){case 5:return t.toISOString().replace(".000Z","Z");case 6:return QV(t);case 7:return t.getTime()/1e3;default:return console.warn("Missing timestamp format, using epoch seconds",t),t.getTime()/1e3}t instanceof is&&(this.useReplacer=!0)}if(!(t===null&&n?.isStructSchema())){if(a.isStringSchema()){if(typeof t>"u"&&a.isIdempotencyToken())return Qz();const s=a.getMergedTraits().mediaType;return t!=null&&s&&(s==="application/json"||s.endsWith("+json"))?ho.from(t):t}if(typeof t=="number"&&a.isNumericSchema())return Math.abs(t)===1/0||isNaN(t)?String(t):t;if(typeof t=="string"&&a.isBlobSchema())return a===this.rootSchema?t:(this.serdeContext?.base64Encoder??bg)(t);if(typeof t=="bigint"&&(this.useReplacer=!0),a.isDocumentSchema())if(i){const s=Array.isArray(t)?[]:{};for(const o in t){const l=t[o];l instanceof is?(this.useReplacer=!0,s[o]=l):s[o]=this._write(a,l)}return s}else return structuredClone(t);return t}}}class jj extends q1{settings;constructor(e){super(),this.settings=e}createSerializer(){const e=new Hj(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){const e=new zj(this.settings);return e.setSerdeContext(this.serdeContext),e}}class Gj extends Jz{serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:n,awsQueryCompatible:i,jsonCodec:a}){super({defaultNamespace:e,errorTypeRegistries:t}),this.serviceTarget=n,this.codec=a??new jj({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!i,this.mixin=new Bj(this.awsQueryCompatible)}async serializeRequest(e,t,n){const i=await super.serializeRequest(e,t,n);return i.path.endsWith("/")||(i.path+="/"),i.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,i.headers["x-amz-target"]=`${this.serviceTarget}.${e.name}`,this.awsQueryCompatible&&(i.headers["x-amzn-query-mode"]="true"),(Wp(e.input)==="unit"||!i.body)&&(i.body="{}"),i}getPayloadCodec(){return this.codec}async handleError(e,t,n,i,a){const{awsQueryCompatible:s}=this;s&&this.mixin.setQueryCompatError(i,n);const o=Uj(n,i,s)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,o,this.options.defaultNamespace);const{errorSchema:l,errorMetadata:u}=await this.mixin.getErrorSchemaOrThrowBaseException(o,this.options.defaultNamespace,n,i,a,s?this.mixin.findQueryCompatibleError:void 0),c=vi.of(l),d=i.message??i.Message??"UnknownError",f=this.compositeErrorRegistry.getErrorCtor(l)??Error,h=new f({}),g={},v=this.codec.createDeserializer();for(const[y,A]of c.structIterator())i[y]!=null&&(g[y]=v.readObject(A,i[y]));throw s&&this.mixin.queryCompatOutput(i,g),this.mixin.decorateServiceException(Object.assign(h,u,{$fault:c.getMergedTraits().error,message:d},g),i)}}class qj extends Gj{constructor({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:n,awsQueryCompatible:i,jsonCodec:a}){super({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:n,awsQueryCompatible:i,jsonCodec:a})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}const Fd="ref",dl=-1,Tp=!0,s2="isSet",fD="PartitionResult",Fp="booleanEquals",Kv="getAttr",Ff="stringEquals",o2={[Fd]:"Endpoint"},Zv={[Fd]:fD},Hf={[Fd]:"Region"},Xa={},l2=[Hf],u2={conditions:[[s2,[o2]],[s2,l2],["aws.partition",l2,fD],[Fp,[{[Fd]:"UseFIPS"},Tp]],[Fp,[{fn:Kv,argv:[Zv,"supportsFIPS"]},Tp]],[Fp,[{[Fd]:"UseDualStack"},Tp]],[Fp,[{fn:Kv,argv:[Zv,"supportsDualStack"]},Tp]],[Ff,[{fn:Kv,argv:[Zv,"name"]},"aws"]],[Ff,[Hf,"us-east-1"]],[Ff,[Hf,"us-east-2"]],[Ff,[Hf,"us-west-1"]],[Ff,[Hf,"us-west-2"]]],results:[[dl],[dl,"Invalid Configuration: FIPS and custom endpoint are not supported"],[dl,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[o2,Xa],["https://cognito-idp-fips.us-east-1.amazonaws.com",Xa],["https://cognito-idp-fips.us-east-2.amazonaws.com",Xa],["https://cognito-idp-fips.us-west-1.amazonaws.com",Xa],["https://cognito-idp-fips.us-west-2.amazonaws.com",Xa],["https://cognito-idp-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Xa],[dl,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://cognito-idp-fips.{Region}.{PartitionResult#dnsSuffix}",Xa],[dl,"FIPS is enabled but this partition does not support FIPS"],["https://cognito-idp.{Region}.amazonaws.com",Xa],["https://cognito-idp.{Region}.{PartitionResult#dualStackDnsSuffix}",Xa],[dl,"DualStack is enabled but this partition does not support DualStack"],["https://cognito-idp.{Region}.{PartitionResult#dnsSuffix}",Xa],[dl,"Invalid Configuration: Missing Region"]]},Wj=2,pi=1e8,Qj=new Int32Array([-1,1,-1,0,17,3,1,4,pi+16,2,5,pi+16,3,9,6,5,7,pi+15,6,8,pi+14,7,pi+12,pi+13,4,11,10,5,pi+9,pi+11,5,12,pi+10,6,13,pi+9,8,pi+4,14,9,pi+5,15,10,pi+6,16,11,pi+7,pi+8,3,pi+1,18,5,pi+2,pi+3]),Yj=V1.from(Qj,Wj,u2.conditions,u2.results),Xj=new kz({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),Jj=(r,e={})=>Xj.get(r,()=>Gz(Yj,{endpointParams:r,logger:e.logger}));z1.aws=eD;class Ct extends _u{constructor(e){super(e),Object.setPrototypeOf(this,Ct.prototype)}}class W1 extends Ct{name="AccessDeniedException";$fault="client";constructor(e){super({name:"AccessDeniedException",$fault:"client",...e}),Object.setPrototypeOf(this,W1.prototype)}}class Q1 extends Ct{name="InternalErrorException";$fault="server";constructor(e){super({name:"InternalErrorException",$fault:"server",...e}),Object.setPrototypeOf(this,Q1.prototype)}}class Y1 extends Ct{name="InvalidParameterException";$fault="client";reasonCode;constructor(e){super({name:"InvalidParameterException",$fault:"client",...e}),Object.setPrototypeOf(this,Y1.prototype),this.reasonCode=e.reasonCode}}class X1 extends Ct{name="NotAuthorizedException";$fault="client";constructor(e){super({name:"NotAuthorizedException",$fault:"client",...e}),Object.setPrototypeOf(this,X1.prototype)}}class J1 extends Ct{name="OperationNotEnabledException";$fault="client";constructor(e){super({name:"OperationNotEnabledException",$fault:"client",...e}),Object.setPrototypeOf(this,J1.prototype)}}class K1 extends Ct{name="ResourceNotFoundException";$fault="client";constructor(e){super({name:"ResourceNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,K1.prototype)}}class Z1 extends Ct{name="TooManyRequestsException";$fault="client";constructor(e){super({name:"TooManyRequestsException",$fault:"client",...e}),Object.setPrototypeOf(this,Z1.prototype)}}class eb extends Ct{name="UserImportInProgressException";$fault="client";constructor(e){super({name:"UserImportInProgressException",$fault:"client",...e}),Object.setPrototypeOf(this,eb.prototype)}}class tb extends Ct{name="InternalServerException";$fault="server";constructor(e){super({name:"InternalServerException",$fault:"server",...e}),Object.setPrototypeOf(this,tb.prototype)}}class rb extends Ct{name="LimitExceededException";$fault="client";constructor(e){super({name:"LimitExceededException",$fault:"client",...e}),Object.setPrototypeOf(this,rb.prototype)}}class nb extends Ct{name="UserNotFoundException";$fault="client";constructor(e){super({name:"UserNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,nb.prototype)}}class ib extends Ct{name="InvalidLambdaResponseException";$fault="client";constructor(e){super({name:"InvalidLambdaResponseException",$fault:"client",...e}),Object.setPrototypeOf(this,ib.prototype)}}class ab extends Ct{name="TooManyFailedAttemptsException";$fault="client";constructor(e){super({name:"TooManyFailedAttemptsException",$fault:"client",...e}),Object.setPrototypeOf(this,ab.prototype)}}class sb extends Ct{name="UnexpectedLambdaException";$fault="client";constructor(e){super({name:"UnexpectedLambdaException",$fault:"client",...e}),Object.setPrototypeOf(this,sb.prototype)}}class ob extends Ct{name="UserLambdaValidationException";$fault="client";constructor(e){super({name:"UserLambdaValidationException",$fault:"client",...e}),Object.setPrototypeOf(this,ob.prototype)}}class lb extends Ct{name="CodeDeliveryFailureException";$fault="client";constructor(e){super({name:"CodeDeliveryFailureException",$fault:"client",...e}),Object.setPrototypeOf(this,lb.prototype)}}class ub extends Ct{name="InvalidPasswordException";$fault="client";constructor(e){super({name:"InvalidPasswordException",$fault:"client",...e}),Object.setPrototypeOf(this,ub.prototype)}}class cb extends Ct{name="InvalidSmsRoleAccessPolicyException";$fault="client";constructor(e){super({name:"InvalidSmsRoleAccessPolicyException",$fault:"client",...e}),Object.setPrototypeOf(this,cb.prototype)}}class fb extends Ct{name="InvalidSmsRoleTrustRelationshipException";$fault="client";constructor(e){super({name:"InvalidSmsRoleTrustRelationshipException",$fault:"client",...e}),Object.setPrototypeOf(this,fb.prototype)}}class db extends Ct{name="PreconditionNotMetException";$fault="client";constructor(e){super({name:"PreconditionNotMetException",$fault:"client",...e}),Object.setPrototypeOf(this,db.prototype)}}class hb extends Ct{name="UnsupportedUserStateException";$fault="client";constructor(e){super({name:"UnsupportedUserStateException",$fault:"client",...e}),Object.setPrototypeOf(this,hb.prototype)}}class pb extends Ct{name="UsernameExistsException";$fault="client";constructor(e){super({name:"UsernameExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,pb.prototype)}}class gb extends Ct{name="AliasExistsException";$fault="client";constructor(e){super({name:"AliasExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,gb.prototype)}}class mb extends Ct{name="InvalidUserPoolConfigurationException";$fault="client";constructor(e){super({name:"InvalidUserPoolConfigurationException",$fault:"client",...e}),Object.setPrototypeOf(this,mb.prototype)}}class vb extends Ct{name="InvalidEmailRoleAccessPolicyException";$fault="client";constructor(e){super({name:"InvalidEmailRoleAccessPolicyException",$fault:"client",...e}),Object.setPrototypeOf(this,vb.prototype)}}class yb extends Ct{name="MFAMethodNotFoundException";$fault="client";constructor(e){super({name:"MFAMethodNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,yb.prototype)}}class Ab extends Ct{name="PasswordResetRequiredException";$fault="client";constructor(e){super({name:"PasswordResetRequiredException",$fault:"client",...e}),Object.setPrototypeOf(this,Ab.prototype)}}class bb extends Ct{name="UnsupportedOperationException";$fault="client";constructor(e){super({name:"UnsupportedOperationException",$fault:"client",...e}),Object.setPrototypeOf(this,bb.prototype)}}class wb extends Ct{name="UserNotConfirmedException";$fault="client";constructor(e){super({name:"UserNotConfirmedException",$fault:"client",...e}),Object.setPrototypeOf(this,wb.prototype)}}class Cb extends Ct{name="UserPoolAddOnNotEnabledException";$fault="client";constructor(e){super({name:"UserPoolAddOnNotEnabledException",$fault:"client",...e}),Object.setPrototypeOf(this,Cb.prototype)}}class xb extends Ct{name="CodeMismatchException";$fault="client";constructor(e){super({name:"CodeMismatchException",$fault:"client",...e}),Object.setPrototypeOf(this,xb.prototype)}}class Sb extends Ct{name="ExpiredCodeException";$fault="client";constructor(e){super({name:"ExpiredCodeException",$fault:"client",...e}),Object.setPrototypeOf(this,Sb.prototype)}}class Eb extends Ct{name="PasswordHistoryPolicyViolationException";$fault="client";constructor(e){super({name:"PasswordHistoryPolicyViolationException",$fault:"client",...e}),Object.setPrototypeOf(this,Eb.prototype)}}class kb extends Ct{name="SoftwareTokenMFANotFoundException";$fault="client";constructor(e){super({name:"SoftwareTokenMFANotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,kb.prototype)}}class Tb extends Ct{name="ConcurrentModificationException";$fault="client";constructor(e){super({name:"ConcurrentModificationException",$fault:"client",...e}),Object.setPrototypeOf(this,Tb.prototype)}}class Fb extends Ct{name="ForbiddenException";$fault="client";constructor(e){super({name:"ForbiddenException",$fault:"client",...e}),Object.setPrototypeOf(this,Fb.prototype)}}class Ib extends Ct{name="WebAuthnChallengeNotFoundException";$fault="client";constructor(e){super({name:"WebAuthnChallengeNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,Ib.prototype)}}class Db extends Ct{name="WebAuthnClientMismatchException";$fault="client";constructor(e){super({name:"WebAuthnClientMismatchException",$fault:"client",...e}),Object.setPrototypeOf(this,Db.prototype)}}class Pb extends Ct{name="WebAuthnCredentialNotSupportedException";$fault="client";constructor(e){super({name:"WebAuthnCredentialNotSupportedException",$fault:"client",...e}),Object.setPrototypeOf(this,Pb.prototype)}}class Rb extends Ct{name="WebAuthnNotEnabledException";$fault="client";constructor(e){super({name:"WebAuthnNotEnabledException",$fault:"client",...e}),Object.setPrototypeOf(this,Rb.prototype)}}class Ob extends Ct{name="WebAuthnOriginNotAllowedException";$fault="client";constructor(e){super({name:"WebAuthnOriginNotAllowedException",$fault:"client",...e}),Object.setPrototypeOf(this,Ob.prototype)}}class Bb extends Ct{name="WebAuthnRelyingPartyMismatchException";$fault="client";constructor(e){super({name:"WebAuthnRelyingPartyMismatchException",$fault:"client",...e}),Object.setPrototypeOf(this,Bb.prototype)}}class Mb extends Ct{name="DeviceKeyExistsException";$fault="client";constructor(e){super({name:"DeviceKeyExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,Mb.prototype)}}class _b extends Ct{name="GroupExistsException";$fault="client";constructor(e){super({name:"GroupExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,_b.prototype)}}class Nb extends Ct{name="DuplicateProviderException";$fault="client";constructor(e){super({name:"DuplicateProviderException",$fault:"client",...e}),Object.setPrototypeOf(this,Nb.prototype)}}class Lb extends Ct{name="ManagedLoginBrandingExistsException";$fault="client";constructor(e){super({name:"ManagedLoginBrandingExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,Lb.prototype)}}class Ub extends Ct{name="TermsExistsException";$fault="client";constructor(e){super({name:"TermsExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,Ub.prototype)}}class Vb extends Ct{name="FeatureUnavailableInTierException";$fault="client";constructor(e){super({name:"FeatureUnavailableInTierException",$fault:"client",...e}),Object.setPrototypeOf(this,Vb.prototype)}}class zb extends Ct{name="TierChangeNotAllowedException";$fault="client";constructor(e){super({name:"TierChangeNotAllowedException",$fault:"client",...e}),Object.setPrototypeOf(this,zb.prototype)}}class $b extends Ct{name="UserPoolTaggingException";$fault="client";constructor(e){super({name:"UserPoolTaggingException",$fault:"client",...e}),Object.setPrototypeOf(this,$b.prototype)}}class Hb extends Ct{name="InvalidOAuthFlowException";$fault="client";constructor(e){super({name:"InvalidOAuthFlowException",$fault:"client",...e}),Object.setPrototypeOf(this,Hb.prototype)}}class jb extends Ct{name="ScopeDoesNotExistException";$fault="client";constructor(e){super({name:"ScopeDoesNotExistException",$fault:"client",...e}),Object.setPrototypeOf(this,jb.prototype)}}class Gb extends Ct{name="UnsupportedIdentityProviderException";$fault="client";constructor(e){super({name:"UnsupportedIdentityProviderException",$fault:"client",...e}),Object.setPrototypeOf(this,Gb.prototype)}}class qb extends Ct{name="RefreshTokenReuseException";$fault="client";constructor(e){super({name:"RefreshTokenReuseException",$fault:"client",...e}),Object.setPrototypeOf(this,qb.prototype)}}class Wb extends Ct{name="UnauthorizedException";$fault="client";constructor(e){super({name:"UnauthorizedException",$fault:"client",...e}),Object.setPrototypeOf(this,Wb.prototype)}}class Qb extends Ct{name="UnsupportedTokenTypeException";$fault="client";constructor(e){super({name:"UnsupportedTokenTypeException",$fault:"client",...e}),Object.setPrototypeOf(this,Qb.prototype)}}class Yb extends Ct{name="WebAuthnConfigurationMissingException";$fault="client";constructor(e){super({name:"WebAuthnConfigurationMissingException",$fault:"client",...e}),Object.setPrototypeOf(this,Yb.prototype)}}class Xb extends Ct{name="EnableSoftwareTokenMFAException";$fault="client";constructor(e){super({name:"EnableSoftwareTokenMFAException",$fault:"client",...e}),Object.setPrototypeOf(this,Xb.prototype)}}const Kj="AvailableChallenges",Zj="AccessDeniedException",eG="AliasExistsException",tG="AnalyticsEndpointId",rG="AuthFlow",dD="AnalyticsMetadata",nG="AnalyticsMetadataType",iG="AuthParameters",aG="AuthParametersType",hD="AuthenticationResult",sG="AuthenticationResultType",oG="AccessToken",lG="CodeDeliveryFailureException",pD="ClientId",uG="ClientIdType",gD="ClientMetadata",cG="CodeMismatchException",fG="ConcurrentModificationException",Jb="ChallengeName",mD="ChallengeParameters",dG="ChallengeResponses",hG="ChallengeResponsesType",pG="DeviceGroupKey",gG="DeviceKey",mG="DeviceKeyExistsException",vG="DuplicateProviderException",yG="ExpiredCodeException",AG="EncodedData",bG="ExpiresIn",wG="EnableSoftwareTokenMFAException",CG="ForbiddenException",xG="FeatureUnavailableInTierException",SG="GroupExistsException",EG="IpAddress",kG="InitiateAuthRequest",TG="InitiateAuthResponse",FG="InitiateAuth",IG="InternalErrorException",DG="InvalidEmailRoleAccessPolicyException",PG="InvalidLambdaResponseException",RG="InvalidOAuthFlowException",OG="InvalidParameterException",BG="InvalidPasswordException",MG="InternalServerException",_G="InvalidSmsRoleAccessPolicyException",NG="InvalidSmsRoleTrustRelationshipException",LG="IdToken",UG="InvalidUserPoolConfigurationException",VG="LimitExceededException",zG="MFAMethodNotFoundException",$G="ManagedLoginBrandingExistsException",HG="NotAuthorizedException",jG="NewDeviceMetadata",GG="NewDeviceMetadataType",qG="OperationNotEnabledException",WG="PasswordHistoryPolicyViolationException",QG="PreconditionNotMetException",YG="PasswordResetRequiredException",XG="ResourceNotFoundException",JG="RefreshToken",KG="RespondToAuthChallenge",ZG="RespondToAuthChallengeRequest",eq="RespondToAuthChallengeResponse",tq="RefreshTokenReuseException",nm="Session",rq="ScopeDoesNotExistException",nq="SessionType",iq="SoftwareTokenMFANotFoundException",aq="TierChangeNotAllowedException",sq="TermsExistsException",oq="TooManyFailedAttemptsException",lq="TooManyRequestsException",uq="TokenModelType",cq="TokenType",fq="UserContextDataType",vD="UserContextData",dq="UnauthorizedException",hq="UsernameExistsException",pq="UserImportInProgressException",gq="UnsupportedIdentityProviderException",mq="UnexpectedLambdaException",vq="UserLambdaValidationException",yq="UserNotConfirmedException",Aq="UserNotFoundException",bq="UnsupportedOperationException",wq="UserPoolAddOnNotEnabledException",Cq="UserPoolTaggingException",xq="UnsupportedTokenTypeException",Sq="UnsupportedUserStateException",Eq="WebAuthnClientMismatchException",kq="WebAuthnConfigurationMissingException",Tq="WebAuthnChallengeNotFoundException",Fq="WebAuthnCredentialNotSupportedException",Iq="WebAuthnNotEnabledException",Dq="WebAuthnOriginNotAllowedException",Pq="WebAuthnRelyingPartyMismatchException",It="client",Tt="error",Dt="httpError",Ft="message",Rq="reasonCode",yD="smithy.ts.sdk.synthetic.com.amazonaws.cognitoidentityprovider",AD="server",at="com.amazonaws.cognitoidentityprovider",bD=Zi.for(yD);var Oq=[-3,yD,"CognitoIdentityProviderServiceException",0,[],[]];bD.registerError(Oq,Ct);const kt=Zi.for(at);var Bq=[-3,at,Zj,{[Tt]:It,[Dt]:403},[Ft],[0]];kt.registerError(Bq,W1);var Mq=[-3,at,eG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(Mq,gb);var _q=[-3,at,lG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(_q,lb);var Nq=[-3,at,cG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(Nq,xb);var Lq=[-3,at,fG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(Lq,Tb);var Uq=[-3,at,mG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(Uq,Mb);var Vq=[-3,at,vG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(Vq,Nb);var zq=[-3,at,wG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(zq,Xb);var $q=[-3,at,yG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError($q,Sb);var Hq=[-3,at,xG,{[Tt]:It,[Dt]:403},[Ft],[0]];kt.registerError(Hq,Vb);var jq=[-3,at,CG,{[Tt]:It,[Dt]:403},[Ft],[0]];kt.registerError(jq,Fb);var Gq=[-3,at,SG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(Gq,_b);var qq=[-3,at,IG,{[Tt]:AD},[Ft],[0]];kt.registerError(qq,Q1);var Wq=[-3,at,MG,{[Tt]:AD},[Ft],[0]];kt.registerError(Wq,tb);var Qq=[-3,at,DG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(Qq,vb);var Yq=[-3,at,PG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(Yq,ib);var Xq=[-3,at,RG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(Xq,Hb);var Jq=[-3,at,OG,{[Tt]:It,[Dt]:400},[Ft,Rq],[0,0]];kt.registerError(Jq,Y1);var Kq=[-3,at,BG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(Kq,ub);var Zq=[-3,at,_G,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(Zq,cb);var eW=[-3,at,NG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(eW,fb);var tW=[-3,at,UG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(tW,mb);var rW=[-3,at,VG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(rW,rb);var nW=[-3,at,$G,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(nW,Lb);var iW=[-3,at,zG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(iW,yb);var aW=[-3,at,HG,{[Tt]:It,[Dt]:403},[Ft],[0]];kt.registerError(aW,X1);var sW=[-3,at,qG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(sW,J1);var oW=[-3,at,WG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(oW,Eb);var lW=[-3,at,YG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(lW,Ab);var uW=[-3,at,QG,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(uW,db);var cW=[-3,at,tq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(cW,qb);var fW=[-3,at,XG,{[Tt]:It,[Dt]:404},[Ft],[0]];kt.registerError(fW,K1);var dW=[-3,at,rq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(dW,jb);var hW=[-3,at,iq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(hW,kb);var pW=[-3,at,sq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(pW,Ub);var gW=[-3,at,aq,{[Tt]:It,[Dt]:403},[Ft],[0]];kt.registerError(gW,zb);var mW=[-3,at,oq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(mW,ab);var vW=[-3,at,lq,{[Tt]:It,[Dt]:429},[Ft],[0]];kt.registerError(vW,Z1);var yW=[-3,at,dq,{[Tt]:It,[Dt]:401},[Ft],[0]];kt.registerError(yW,Wb);var AW=[-3,at,mq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(AW,sb);var bW=[-3,at,gq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(bW,Gb);var wW=[-3,at,bq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(wW,bb);var CW=[-3,at,xq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(CW,Qb);var xW=[-3,at,Sq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(xW,hb);var SW=[-3,at,pq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(SW,eb);var EW=[-3,at,vq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(EW,ob);var kW=[-3,at,hq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(kW,pb);var TW=[-3,at,yq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(TW,wb);var FW=[-3,at,Aq,{[Tt]:It,[Dt]:404},[Ft],[0]];kt.registerError(FW,nb);var IW=[-3,at,wq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(IW,Cb);var DW=[-3,at,Cq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(DW,$b);var PW=[-3,at,Tq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(PW,Ib);var RW=[-3,at,Eq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(RW,Db);var OW=[-3,at,kq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(OW,Yb);var BW=[-3,at,Fq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(BW,Pb);var MW=[-3,at,Iq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(MW,Rb);var _W=[-3,at,Dq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(_W,Ob);var NW=[-3,at,Pq,{[Tt]:It,[Dt]:400},[Ft],[0]];kt.registerError(NW,Bb);const LW=[bD,kt];var wD=[0,at,uG,8,0],im=[0,at,nq,8,0],ey=[0,at,uq,8,0],CD=[3,at,nG,0,[tG],[0]],xD=[3,at,sG,0,[oG,bG,cq,JG,LG,jG],[[()=>ey,0],1,0,[()=>ey,0],[()=>ey,0],()=>zW]],UW=[3,at,kG,0,[rG,pD,iG,gD,dD,vD,nm],[0,[()=>wD,0],[()=>jW,0],128,()=>CD,[()=>SD,0],[()=>im,0]],2],VW=[3,at,TG,0,[Jb,nm,mD,hD,Kj],[0,[()=>im,0],128,[()=>xD,0],64]],zW=[3,at,GG,0,[gG,pG],[0,0]],$W=[3,at,ZG,0,[pD,Jb,nm,dG,dD,vD,gD],[[()=>wD,0],0,[()=>im,0],[()=>GW,0],()=>CD,[()=>SD,0],128],2],HW=[3,at,eq,0,[Jb,nm,mD,hD],[0,[()=>im,0],128,[()=>xD,0]]],SD=[3,at,fq,8,[EG,AG],[0,0]],jW=[2,at,aG,8,0,0],GW=[2,at,hG,8,0,0],qW=[9,at,FG,0,()=>UW,()=>VW],WW=[9,at,KG,0,()=>$W,()=>HW];const QW=r=>({apiVersion:"2016-04-18",base64Decoder:r?.base64Decoder??Zg,base64Encoder:r?.base64Encoder??bg,disableHostPrefix:r?.disableHostPrefix??!1,endpointProvider:r?.endpointProvider??Jj,extensions:r?.extensions??[],httpAuthSchemeProvider:r?.httpAuthSchemeProvider??lj,httpAuthSchemes:r?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new RH},{schemeId:"smithy.api#noAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new X$}],logger:r?.logger??new RI,protocol:r?.protocol??qj,protocolSettings:r?.protocolSettings??{defaultNamespace:"com.amazonaws.cognitoidentityprovider",errorTypeRegistries:LW,xmlNamespace:"http://cognito-idp.amazonaws.com/doc/2016-04-18/",version:"2016-04-18",serviceTarget:"AWSCognitoIdentityProviderService"},serviceId:r?.serviceId??"Cognito Identity Provider",urlParser:r?.urlParser??Ag,utf8Decoder:r?.utf8Decoder??El,utf8Encoder:r?.utf8Encoder??em}),YW=r=>{const e=SH(r),t=()=>e().then(TV),n=QW(r);return{...n,...r,runtime:"browser",defaultsMode:e,bodyLengthChecker:r?.bodyLengthChecker??uz,credentialDefaultProvider:r?.credentialDefaultProvider??(i=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:r?.defaultUserAgentProvider??mH({serviceId:n.serviceId,clientVersion:dj.version}),maxAttempts:r?.maxAttempts??td,region:r?.region??yV("Region is missing"),requestHandler:G1.create(r?.requestHandler??t),retryMode:r?.retryMode??(async()=>(await t()).retryMode||F$),sha256:r?.sha256??Fj,streamCollector:r?.streamCollector??Dj,useDualstackEndpoint:r?.useDualstackEndpoint??(()=>Promise.resolve(kH)),useFipsEndpoint:r?.useFipsEndpoint??(()=>Promise.resolve(TH))}},XW=r=>{const e=r.httpAuthSchemes;let t=r.httpAuthSchemeProvider,n=r.credentials;return{setHttpAuthScheme(i){const a=e.findIndex(s=>s.schemeId===i.schemeId);a===-1?e.push(i):e.splice(a,1,i)},httpAuthSchemes(){return e},setHttpAuthSchemeProvider(i){t=i},httpAuthSchemeProvider(){return t},setCredentials(i){n=i},credentials(){return n}}},JW=r=>({httpAuthSchemes:r.httpAuthSchemes(),httpAuthSchemeProvider:r.httpAuthSchemeProvider(),credentials:r.credentials()}),KW=(r,e)=>{const t=Object.assign(FH(r),RV(r),Kz(r),XW(r));return e.forEach(n=>n.configure(t)),Object.assign(r,IH(t),OV(t),Zz(t),JW(t))};class ZW extends AV{config;constructor(...[e]){const t=YW(e||{});super(t),this.initConfig=t;const n=cj(t),i=nH(n),a=D$(i),s=CH(a),o=s,l=qz(o),u=uj(l),c=KW(u,e?.extensions||[]);this.config=c,this.middlewareStack.use(SV(this.config)),this.middlewareStack.use(gH(this.config)),this.middlewareStack.use(P$(this.config)),this.middlewareStack.use(r$(this.config)),this.middlewareStack.use(B$(this.config)),this.middlewareStack.use(N$(this.config)),this.middlewareStack.use(L$(this.config)),this.middlewareStack.use(H$(this.config,{httpAuthSchemeParametersProvider:sj,identityProviderConfigProvider:async d=>new Y$({"aws.auth#sigv4":d.credentials})})),this.middlewareStack.use(Q$(this.config))}destroy(){super.destroy()}}class c2 extends L1.classBuilder().ep(uD).m(function(e,t,n,i){return[WI(n,e.getEndpointParameterInstructions())]}).s("AWSCognitoIdentityProviderService","InitiateAuth",{}).n("CognitoIdentityProviderClient","InitiateAuthCommand").sc(qW).build(){}class eQ extends L1.classBuilder().ep(uD).m(function(e,t,n,i){return[WI(n,e.getEndpointParameterInstructions())]}).s("AWSCognitoIdentityProviderService","RespondToAuthChallenge",{}).n("CognitoIdentityProviderClient","RespondToAuthChallengeCommand").sc(WW).build(){}class tQ{init(e,t,n){this.cognitoClient=new ZW({region:t}),this.spiffRegion=e,this.userPoolClientId=n}async generateCode(e){const t=await this.cognitoClient?.send(new c2({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:e}}));t?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=t.Session)}async verifyCode(e,t,n){const i=await this.cognitoClient?.send(new eQ({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:e,ANSWER:t},ClientMetadata:{partnerId:n,environment:(this.spiffRegion||"").toLowerCase()}}));return i?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=i.Session),i}async refreshTokens(){const e=localStorage.getItem("cognito-tokens");if(!e)throw new Error("Failed to find existing tokens.");const t=JSON.parse(e);return await this.cognitoClient?.send(new c2({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:t.RefreshToken||""}}))}}const If=new tQ;var rQ={defaultAmount:0,defaultCurrency:"USD",defaultPrecision:2},nQ={globalLocale:"en-US",globalFormat:"$0,0.00",globalRoundingMode:"HALF_EVEN",globalFormatRoundingMode:"HALF_AWAY_FROM_ZERO",globalExchangeRatesApi:{endpoint:void 0,headers:void 0,propertyPath:void 0}};function id(r){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?id=function(e){return typeof e}:id=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},id(r)}function f2(r){return iQ(r)||aQ(r)||sQ(r)||oQ()}function iQ(r){if(Array.isArray(r))return r}function aQ(r){if(typeof Symbol<"u"&&Symbol.iterator in Object(r))return Array.from(r)}function sQ(r,e){if(r){if(typeof r=="string")return d2(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return d2(r,e)}}function d2(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function oQ(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
2890
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var lQ={normalizePrecision:function(e){var t=e.reduce(function(n,i){return Math.max(n.getPrecision(),i.getPrecision())});return e.map(function(n){return n.getPrecision()!==t?n.convertPrecision(t):n})},minimum:function(e){var t=f2(e),n=t[0],i=t.slice(1),a=n;return i.forEach(function(s){a=a.lessThan(s)?a:s}),a},maximum:function(e){var t=f2(e),n=t[0],i=t.slice(1),a=n;return i.forEach(function(s){a=a.greaterThan(s)?a:s}),a}};function ED(r){return!isNaN(parseInt(r))&&isFinite(r)}function uQ(r){return ED(r)&&r<=100&&r>=0}function cQ(r){return r.length>0&&r.every(function(e){return e>=0})&&r.some(function(e){return e>0})}function h2(r){return r%2===0}function p2(r){return ED(r)&&!Number.isInteger(r)}function fQ(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=r.toString();if(e.indexOf("e-")>0)return parseInt(e.split("e-")[1]);var t=e.split(".")[1];return t?t.length:0}function Df(r){return Math.abs(r)%1===.5}function dQ(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise(function(t,n){var i=Object.assign(new XMLHttpRequest,{onreadystatechange:function(){i.readyState===4&&(i.status>=200&&i.status<400?t(JSON.parse(i.responseText)):n(new Error(i.statusText)))},onerror:function(){n(new Error("Network error"))}});i.open("GET",r,!0),hQ(i,e.headers),i.send()})}function hQ(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};for(var t in e)r.setRequestHeader(t,e[t]);return r}function jf(r){return typeof r>"u"}function kD(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:".",t={};return Object.entries(r).forEach(function(n){if(id(n[1])==="object"){var i=kD(n[1]);Object.entries(i).forEach(function(a){t[n[0]+e+a[0]]=a[1]})}else t[n[0]]=n[1]}),t}function pQ(r){return!!r&&(id(r)==="object"||typeof r=="function")&&typeof r.then=="function"}function TD(){var r=function(n,i){var a=function(l){return Math.pow(10,fQ(l))},s=Math.max(a(n),a(i));return Math.round(n*s)*Math.round(i*s)/(s*s)},e={HALF_ODD:function(n){var i=Math.round(n);return Df(n)&&h2(i)?i-1:i},HALF_EVEN:function(n){var i=Math.round(n);return Df(n)?h2(i)?i:i-1:i},HALF_UP:function(n){return Math.round(n)},HALF_DOWN:function(n){return Df(n)?Math.floor(n):Math.round(n)},HALF_TOWARDS_ZERO:function(n){return Df(n)?Math.sign(n)*Math.floor(Math.abs(n)):Math.round(n)},HALF_AWAY_FROM_ZERO:function(n){return Df(n)?Math.sign(n)*Math.ceil(Math.abs(n)):Math.round(n)},DOWN:function(n){return Math.floor(n)}};return{add:function(n,i){return n+i},subtract:function(n,i){return n-i},multiply:function(n,i){return p2(n)||p2(i)?r(n,i):n*i},divide:function(n,i){return n/i},modulo:function(n,i){return n%i},round:function(n){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"HALF_EVEN";return e[i](n)}}}var gQ=TD();function mQ(r){var e=/^(?:(\$|USD)?0(?:(,)0)?(\.)?(0+)?|0(?:(,)0)?(\.)?(0+)?\s?(dollar)?)$/gm.exec(r);return{getMatches:function(){return e!==null?e.slice(1).filter(function(n){return!jf(n)}):[]},getMinimumFractionDigits:function(){var n=function(a){return a==="."};return jf(this.getMatches().find(n))?0:this.getMatches()[gQ.add(this.getMatches().findIndex(n),1)].split("").length},getCurrencyDisplay:function(){var n={USD:"code",dollar:"name",$:"symbol"};return n[this.getMatches().find(function(i){return i==="USD"||i==="dollar"||i==="$"})]},getStyle:function(){return jf(this.getCurrencyDisplay(this.getMatches()))?"decimal":"currency"},getUseGrouping:function(){return!jf(this.getMatches().find(function(n){return n===","}))}}}function vQ(r){var e=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",a=arguments.length>1?arguments[1]:void 0;for(var s in a)i=i.replace("{{".concat(s,"}}"),a[s]);return i},t=function(i,a){return dQ(e(r.endpoint,{from:i,to:a}),{headers:r.headers})};return{getExchangeRate:function(i,a){return(pQ(r.endpoint)?r.endpoint:t(i,a)).then(function(s){return kD(s)[e(r.propertyPath,{from:i,to:a})]})}}}function Id(r,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Error;if(!r)throw new t(e)}function yQ(r){Id(uQ(r),"You must provide a numeric value between 0 and 100.",RangeError)}function AQ(r){Id(cQ(r),"You must provide a non-empty array of numeric values greater than 0.",TypeError)}function ty(r){Id(Number.isInteger(r),"You must provide an integer.",TypeError)}var kn=TD(),bQ=function r(e){var t=Object.assign({},{amount:r.defaultAmount,currency:r.defaultCurrency,precision:r.defaultPrecision},e),n=t.amount,i=t.currency,a=t.precision;ty(n),ty(a);var s=r.globalLocale,o=r.globalFormat,l=r.globalRoundingMode,u=r.globalFormatRoundingMode,c=Object.assign({},r.globalExchangeRatesApi),d=function(g){var v=Object.assign({},Object.assign({},{amount:n,currency:i,precision:a},g),Object.assign({},{locale:this.locale},g));return Object.assign(r({amount:v.amount,currency:v.currency,precision:v.precision}),{locale:v.locale})},f=function(g){Id(this.hasSameCurrency(g),"You must provide a Dinero instance with the same currency.",TypeError)};return{getAmount:function(){return n},getCurrency:function(){return i},getLocale:function(){return this.locale||s},setLocale:function(g){return d.call(this,{locale:g})},getPrecision:function(){return a},convertPrecision:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u;ty(g);var y=this.getPrecision(),A=g>y,C=A?kn.multiply:kn.divide,k=A?[g,y]:[y,g],F=Math.pow(10,kn.subtract.apply(kn,k));return d.call(this,{amount:kn.round(C(this.getAmount(),F),v),precision:g})},add:function(g){f.call(this,g);var v=r.normalizePrecision([this,g]);return d.call(this,{amount:kn.add(v[0].getAmount(),v[1].getAmount()),precision:v[0].getPrecision()})},subtract:function(g){f.call(this,g);var v=r.normalizePrecision([this,g]);return d.call(this,{amount:kn.subtract(v[0].getAmount(),v[1].getAmount()),precision:v[0].getPrecision()})},multiply:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return d.call(this,{amount:kn.round(kn.multiply(this.getAmount(),g),v)})},divide:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return d.call(this,{amount:kn.round(kn.divide(this.getAmount(),g),v)})},percentage:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return yQ(g),this.multiply(kn.divide(g,100),v)},allocate:function(g){var v=this;AQ(g);for(var y=g.reduce(function(F,S){return kn.add(F,S)}),A=this.getAmount(),C=g.map(function(F){var S=Math.floor(kn.divide(kn.multiply(v.getAmount(),F),y));return A=kn.subtract(A,S),d.call(v,{amount:S})}),k=0;A>0;)g[k]>0&&(C[k]=C[k].add(d.call(this,{amount:1})),A=kn.subtract(A,1)),k+=1;return C},convert:function(g){var v=this,y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},A=y.endpoint,C=A===void 0?c.endpoint:A,k=y.propertyPath,F=k===void 0?c.propertyPath||"rates.{{to}}":k,S=y.headers,R=S===void 0?c.headers:S,M=y.roundingMode,j=M===void 0?l:M,G=Object.assign({},{endpoint:C,propertyPath:F,headers:R,roundingMode:j});return vQ(G).getExchangeRate(this.getCurrency(),g).then(function(ie){return Id(!jf(ie),'No rate was found for the destination currency "'.concat(g,'".'),TypeError),d.call(v,{amount:kn.round(kn.multiply(v.getAmount(),parseFloat(ie)),G.roundingMode),currency:g})})},equalsTo:function(g){return this.hasSameAmount(g)&&this.hasSameCurrency(g)},lessThan:function(g){f.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()<v[1].getAmount()},lessThanOrEqual:function(g){f.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()<=v[1].getAmount()},greaterThan:function(g){f.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()>v[1].getAmount()},greaterThanOrEqual:function(g){f.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()>=v[1].getAmount()},isZero:function(){return this.getAmount()===0},isPositive:function(){return this.getAmount()>=0},isNegative:function(){return this.getAmount()<0},hasSubUnits:function(){return kn.modulo(this.getAmount(),Math.pow(10,a))!==0},hasCents:function(){return kn.modulo(this.getAmount(),Math.pow(10,a))!==0},hasSameCurrency:function(g){return this.getCurrency()===g.getCurrency()},hasSameAmount:function(g){var v=r.normalizePrecision([this,g]);return v[0].getAmount()===v[1].getAmount()},toFormat:function(){var g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:o,v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u,y=mQ(g);return this.toRoundedUnit(y.getMinimumFractionDigits(),v).toLocaleString(this.getLocale(),{currencyDisplay:y.getCurrencyDisplay(),useGrouping:y.getUseGrouping(),minimumFractionDigits:y.getMinimumFractionDigits(),style:y.getStyle(),currency:this.getCurrency()})},toUnit:function(){return kn.divide(this.getAmount(),Math.pow(10,a))},toRoundedUnit:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u,y=Math.pow(10,g);return kn.divide(kn.round(kn.multiply(this.toUnit(),y),v),y)},toObject:function(){return{amount:n,currency:i,precision:a}},toJSON:function(){return this.toObject()}}},wQ=Object.assign(bQ,rQ,nQ,lQ),Ja={},ry,g2;function CQ(){if(g2)return ry;g2=1;function r(t){return t}function e(t,a,s){for(var a=a||r,s=s||t,o=0,l=t.length;o<l;o+=1)if(a.call(s,t[o],o))return t[o]}return ry=e,ry}var ny={exports:{}},m2;function xQ(){if(m2)return ny.exports;m2=1;var r=ny.exports=function(e,t){if(typeof e=="function"||t)return r.by(e,t);for(var n={object:[],function:[],string:{},number:{},boolean:{},undefined:{}},i=[],a=0;a<e.length;a++){var s=e[a],o=s==="__proto__"?n.objects:n[typeof s]||n.objects;Array.isArray(o)?o.indexOf(s)<0&&(o.push(s),i.push(s)):Object.hasOwnProperty.call(o,s)||(o[s]=!0,i.push(s))}return i};return r.by=function(e,t){if(typeof e=="function"){var n=t;t=e,e=n}for(var i=[],a=0;a<e.length;a++){for(var s=e[a],o=!1,l=0;l<i.length;l++){var u=i[l];if(t.call(i,s,u)){o=!0;break}}o||i.push(s)}return i},ny.exports}var iy,v2;function SQ(){return v2||(v2=1,iy=[{code:"AED",number:"784",digits:2,currency:"UAE Dirham",countries:["United Arab Emirates (The)"]},{code:"AFN",number:"971",digits:2,currency:"Afghani",countries:["Afghanistan"]},{code:"ALL",number:"008",digits:2,currency:"Lek",countries:["Albania"]},{code:"AMD",number:"051",digits:2,currency:"Armenian Dram",countries:["Armenia"]},{code:"ANG",number:"532",digits:2,currency:"Netherlands Antillean Guilder",countries:["Curaçao","Sint Maarten (Dutch Part)"]},{code:"AOA",number:"973",digits:2,currency:"Kwanza",countries:["Angola"]},{code:"ARS",number:"032",digits:2,currency:"Argentine Peso",countries:["Argentina"]},{code:"AUD",number:"036",digits:2,currency:"Australian Dollar",countries:["Australia","Christmas Island","Cocos (Keeling) Islands (The)","Heard Island and Mcdonald Islands","Kiribati","Nauru","Norfolk Island","Tuvalu"]},{code:"AWG",number:"533",digits:2,currency:"Aruban Florin",countries:["Aruba"]},{code:"AZN",number:"944",digits:2,currency:"Azerbaijan Manat",countries:["Azerbaijan"]},{code:"BAM",number:"977",digits:2,currency:"Convertible Mark",countries:["Bosnia and Herzegovina"]},{code:"BBD",number:"052",digits:2,currency:"Barbados Dollar",countries:["Barbados"]},{code:"BDT",number:"050",digits:2,currency:"Taka",countries:["Bangladesh"]},{code:"BGN",number:"975",digits:2,currency:"Bulgarian Lev",countries:["Bulgaria"]},{code:"BHD",number:"048",digits:3,currency:"Bahraini Dinar",countries:["Bahrain"]},{code:"BIF",number:"108",digits:0,currency:"Burundi Franc",countries:["Burundi"]},{code:"BMD",number:"060",digits:2,currency:"Bermudian Dollar",countries:["Bermuda"]},{code:"BND",number:"096",digits:2,currency:"Brunei Dollar",countries:["Brunei Darussalam"]},{code:"BOB",number:"068",digits:2,currency:"Boliviano",countries:["Bolivia (Plurinational State Of)"]},{code:"BOV",number:"984",digits:2,currency:"Mvdol",countries:["Bolivia (Plurinational State Of)"]},{code:"BRL",number:"986",digits:2,currency:"Brazilian Real",countries:["Brazil"]},{code:"BSD",number:"044",digits:2,currency:"Bahamian Dollar",countries:["Bahamas (The)"]},{code:"BTN",number:"064",digits:2,currency:"Ngultrum",countries:["Bhutan"]},{code:"BWP",number:"072",digits:2,currency:"Pula",countries:["Botswana"]},{code:"BYN",number:"933",digits:2,currency:"Belarusian Ruble",countries:["Belarus"]},{code:"BZD",number:"084",digits:2,currency:"Belize Dollar",countries:["Belize"]},{code:"CAD",number:"124",digits:2,currency:"Canadian Dollar",countries:["Canada"]},{code:"CDF",number:"976",digits:2,currency:"Congolese Franc",countries:["Congo (The Democratic Republic of The)"]},{code:"CHE",number:"947",digits:2,currency:"WIR Euro",countries:["Switzerland"]},{code:"CHF",number:"756",digits:2,currency:"Swiss Franc",countries:["Liechtenstein","Switzerland"]},{code:"CHW",number:"948",digits:2,currency:"WIR Franc",countries:["Switzerland"]},{code:"CLF",number:"990",digits:4,currency:"Unidad de Fomento",countries:["Chile"]},{code:"CLP",number:"152",digits:0,currency:"Chilean Peso",countries:["Chile"]},{code:"CNY",number:"156",digits:2,currency:"Yuan Renminbi",countries:["China"]},{code:"COP",number:"170",digits:2,currency:"Colombian Peso",countries:["Colombia"]},{code:"COU",number:"970",digits:2,currency:"Unidad de Valor Real",countries:["Colombia"]},{code:"CRC",number:"188",digits:2,currency:"Costa Rican Colon",countries:["Costa Rica"]},{code:"CUC",number:"931",digits:2,currency:"Peso Convertible",countries:["Cuba"]},{code:"CUP",number:"192",digits:2,currency:"Cuban Peso",countries:["Cuba"]},{code:"CVE",number:"132",digits:2,currency:"Cabo Verde Escudo",countries:["Cabo Verde"]},{code:"CZK",number:"203",digits:2,currency:"Czech Koruna",countries:["Czechia"]},{code:"DJF",number:"262",digits:0,currency:"Djibouti Franc",countries:["Djibouti"]},{code:"DKK",number:"208",digits:2,currency:"Danish Krone",countries:["Denmark","Faroe Islands (The)","Greenland"]},{code:"DOP",number:"214",digits:2,currency:"Dominican Peso",countries:["Dominican Republic (The)"]},{code:"DZD",number:"012",digits:2,currency:"Algerian Dinar",countries:["Algeria"]},{code:"EGP",number:"818",digits:2,currency:"Egyptian Pound",countries:["Egypt"]},{code:"ERN",number:"232",digits:2,currency:"Nakfa",countries:["Eritrea"]},{code:"ETB",number:"230",digits:2,currency:"Ethiopian Birr",countries:["Ethiopia"]},{code:"EUR",number:"978",digits:2,currency:"Euro",countries:["Åland Islands","Andorra","Austria","Belgium","Croatia","Cyprus","Estonia","European Union","Finland","France","French Guiana","French Southern Territories (The)","Germany","Greece","Guadeloupe","Holy See (The)","Ireland","Italy","Latvia","Lithuania","Luxembourg","Malta","Martinique","Mayotte","Monaco","Montenegro","Netherlands (The)","Portugal","Réunion","Saint Barthélemy","Saint Martin (French Part)","Saint Pierre and Miquelon","San Marino","Slovakia","Slovenia","Spain"]},{code:"FJD",number:"242",digits:2,currency:"Fiji Dollar",countries:["Fiji"]},{code:"FKP",number:"238",digits:2,currency:"Falkland Islands Pound",countries:["Falkland Islands (The) [Malvinas]"]},{code:"GBP",number:"826",digits:2,currency:"Pound Sterling",countries:["Guernsey","Isle of Man","Jersey","United Kingdom of Great Britain and Northern Ireland (The)"]},{code:"GEL",number:"981",digits:2,currency:"Lari",countries:["Georgia"]},{code:"GHS",number:"936",digits:2,currency:"Ghana Cedi",countries:["Ghana"]},{code:"GIP",number:"292",digits:2,currency:"Gibraltar Pound",countries:["Gibraltar"]},{code:"GMD",number:"270",digits:2,currency:"Dalasi",countries:["Gambia (The)"]},{code:"GNF",number:"324",digits:0,currency:"Guinean Franc",countries:["Guinea"]},{code:"GTQ",number:"320",digits:2,currency:"Quetzal",countries:["Guatemala"]},{code:"GYD",number:"328",digits:2,currency:"Guyana Dollar",countries:["Guyana"]},{code:"HKD",number:"344",digits:2,currency:"Hong Kong Dollar",countries:["Hong Kong"]},{code:"HNL",number:"340",digits:2,currency:"Lempira",countries:["Honduras"]},{code:"HTG",number:"332",digits:2,currency:"Gourde",countries:["Haiti"]},{code:"HUF",number:"348",digits:2,currency:"Forint",countries:["Hungary"]},{code:"IDR",number:"360",digits:2,currency:"Rupiah",countries:["Indonesia"]},{code:"ILS",number:"376",digits:2,currency:"New Israeli Sheqel",countries:["Israel"]},{code:"INR",number:"356",digits:2,currency:"Indian Rupee",countries:["Bhutan","India"]},{code:"IQD",number:"368",digits:3,currency:"Iraqi Dinar",countries:["Iraq"]},{code:"IRR",number:"364",digits:2,currency:"Iranian Rial",countries:["Iran (Islamic Republic Of)"]},{code:"ISK",number:"352",digits:0,currency:"Iceland Krona",countries:["Iceland"]},{code:"JMD",number:"388",digits:2,currency:"Jamaican Dollar",countries:["Jamaica"]},{code:"JOD",number:"400",digits:3,currency:"Jordanian Dinar",countries:["Jordan"]},{code:"JPY",number:"392",digits:0,currency:"Yen",countries:["Japan"]},{code:"KES",number:"404",digits:2,currency:"Kenyan Shilling",countries:["Kenya"]},{code:"KGS",number:"417",digits:2,currency:"Som",countries:["Kyrgyzstan"]},{code:"KHR",number:"116",digits:2,currency:"Riel",countries:["Cambodia"]},{code:"KMF",number:"174",digits:0,currency:"Comorian Franc ",countries:["Comoros (The)"]},{code:"KPW",number:"408",digits:2,currency:"North Korean Won",countries:["Korea (The Democratic People’s Republic Of)"]},{code:"KRW",number:"410",digits:0,currency:"Won",countries:["Korea (The Republic Of)"]},{code:"KWD",number:"414",digits:3,currency:"Kuwaiti Dinar",countries:["Kuwait"]},{code:"KYD",number:"136",digits:2,currency:"Cayman Islands Dollar",countries:["Cayman Islands (The)"]},{code:"KZT",number:"398",digits:2,currency:"Tenge",countries:["Kazakhstan"]},{code:"LAK",number:"418",digits:2,currency:"Lao Kip",countries:["Lao People’s Democratic Republic (The)"]},{code:"LBP",number:"422",digits:2,currency:"Lebanese Pound",countries:["Lebanon"]},{code:"LKR",number:"144",digits:2,currency:"Sri Lanka Rupee",countries:["Sri Lanka"]},{code:"LRD",number:"430",digits:2,currency:"Liberian Dollar",countries:["Liberia"]},{code:"LSL",number:"426",digits:2,currency:"Loti",countries:["Lesotho"]},{code:"LYD",number:"434",digits:3,currency:"Libyan Dinar",countries:["Libya"]},{code:"MAD",number:"504",digits:2,currency:"Moroccan Dirham",countries:["Morocco","Western Sahara"]},{code:"MDL",number:"498",digits:2,currency:"Moldovan Leu",countries:["Moldova (The Republic Of)"]},{code:"MGA",number:"969",digits:2,currency:"Malagasy Ariary",countries:["Madagascar"]},{code:"MKD",number:"807",digits:2,currency:"Denar",countries:["North Macedonia"]},{code:"MMK",number:"104",digits:2,currency:"Kyat",countries:["Myanmar"]},{code:"MNT",number:"496",digits:2,currency:"Tugrik",countries:["Mongolia"]},{code:"MOP",number:"446",digits:2,currency:"Pataca",countries:["Macao"]},{code:"MRU",number:"929",digits:2,currency:"Ouguiya",countries:["Mauritania"]},{code:"MUR",number:"480",digits:2,currency:"Mauritius Rupee",countries:["Mauritius"]},{code:"MVR",number:"462",digits:2,currency:"Rufiyaa",countries:["Maldives"]},{code:"MWK",number:"454",digits:2,currency:"Malawi Kwacha",countries:["Malawi"]},{code:"MXN",number:"484",digits:2,currency:"Mexican Peso",countries:["Mexico"]},{code:"MXV",number:"979",digits:2,currency:"Mexican Unidad de Inversion (UDI)",countries:["Mexico"]},{code:"MYR",number:"458",digits:2,currency:"Malaysian Ringgit",countries:["Malaysia"]},{code:"MZN",number:"943",digits:2,currency:"Mozambique Metical",countries:["Mozambique"]},{code:"NAD",number:"516",digits:2,currency:"Namibia Dollar",countries:["Namibia"]},{code:"NGN",number:"566",digits:2,currency:"Naira",countries:["Nigeria"]},{code:"NIO",number:"558",digits:2,currency:"Cordoba Oro",countries:["Nicaragua"]},{code:"NOK",number:"578",digits:2,currency:"Norwegian Krone",countries:["Bouvet Island","Norway","Svalbard and Jan Mayen"]},{code:"NPR",number:"524",digits:2,currency:"Nepalese Rupee",countries:["Nepal"]},{code:"NZD",number:"554",digits:2,currency:"New Zealand Dollar",countries:["Cook Islands (The)","New Zealand","Niue","Pitcairn","Tokelau"]},{code:"OMR",number:"512",digits:3,currency:"Rial Omani",countries:["Oman"]},{code:"PAB",number:"590",digits:2,currency:"Balboa",countries:["Panama"]},{code:"PEN",number:"604",digits:2,currency:"Sol",countries:["Peru"]},{code:"PGK",number:"598",digits:2,currency:"Kina",countries:["Papua New Guinea"]},{code:"PHP",number:"608",digits:2,currency:"Philippine Peso",countries:["Philippines (The)"]},{code:"PKR",number:"586",digits:2,currency:"Pakistan Rupee",countries:["Pakistan"]},{code:"PLN",number:"985",digits:2,currency:"Zloty",countries:["Poland"]},{code:"PYG",number:"600",digits:0,currency:"Guarani",countries:["Paraguay"]},{code:"QAR",number:"634",digits:2,currency:"Qatari Rial",countries:["Qatar"]},{code:"RON",number:"946",digits:2,currency:"Romanian Leu",countries:["Romania"]},{code:"RSD",number:"941",digits:2,currency:"Serbian Dinar",countries:["Serbia"]},{code:"RUB",number:"643",digits:2,currency:"Russian Ruble",countries:["Russian Federation (The)"]},{code:"RWF",number:"646",digits:0,currency:"Rwanda Franc",countries:["Rwanda"]},{code:"SAR",number:"682",digits:2,currency:"Saudi Riyal",countries:["Saudi Arabia"]},{code:"SBD",number:"090",digits:2,currency:"Solomon Islands Dollar",countries:["Solomon Islands"]},{code:"SCR",number:"690",digits:2,currency:"Seychelles Rupee",countries:["Seychelles"]},{code:"SDG",number:"938",digits:2,currency:"Sudanese Pound",countries:["Sudan (The)"]},{code:"SEK",number:"752",digits:2,currency:"Swedish Krona",countries:["Sweden"]},{code:"SGD",number:"702",digits:2,currency:"Singapore Dollar",countries:["Singapore"]},{code:"SHP",number:"654",digits:2,currency:"Saint Helena Pound",countries:["Saint Helena, Ascension and Tristan Da Cunha"]},{code:"SLE",number:"925",digits:2,currency:"Leone",countries:["Sierra Leone"]},{code:"SOS",number:"706",digits:2,currency:"Somali Shilling",countries:["Somalia"]},{code:"SRD",number:"968",digits:2,currency:"Surinam Dollar",countries:["Suriname"]},{code:"SSP",number:"728",digits:2,currency:"South Sudanese Pound",countries:["South Sudan"]},{code:"STN",number:"930",digits:2,currency:"Dobra",countries:["Sao Tome and Principe"]},{code:"SVC",number:"222",digits:2,currency:"El Salvador Colon",countries:["El Salvador"]},{code:"SYP",number:"760",digits:2,currency:"Syrian Pound",countries:["Syrian Arab Republic"]},{code:"SZL",number:"748",digits:2,currency:"Lilangeni",countries:["Eswatini"]},{code:"THB",number:"764",digits:2,currency:"Baht",countries:["Thailand"]},{code:"TJS",number:"972",digits:2,currency:"Somoni",countries:["Tajikistan"]},{code:"TMT",number:"934",digits:2,currency:"Turkmenistan New Manat",countries:["Turkmenistan"]},{code:"TND",number:"788",digits:3,currency:"Tunisian Dinar",countries:["Tunisia"]},{code:"TOP",number:"776",digits:2,currency:"Pa’anga",countries:["Tonga"]},{code:"TRY",number:"949",digits:2,currency:"Turkish Lira",countries:["Türki̇ye"]},{code:"TTD",number:"780",digits:2,currency:"Trinidad and Tobago Dollar",countries:["Trinidad and Tobago"]},{code:"TWD",number:"901",digits:2,currency:"New Taiwan Dollar",countries:["Taiwan (Province of China)"]},{code:"TZS",number:"834",digits:2,currency:"Tanzanian Shilling",countries:["Tanzania, United Republic Of"]},{code:"UAH",number:"980",digits:2,currency:"Hryvnia",countries:["Ukraine"]},{code:"UGX",number:"800",digits:0,currency:"Uganda Shilling",countries:["Uganda"]},{code:"USD",number:"840",digits:2,currency:"US Dollar",countries:["American Samoa","Bonaire, Sint Eustatius and Saba","British Indian Ocean Territory (The)","Ecuador","El Salvador","Guam","Haiti","Marshall Islands (The)","Micronesia (Federated States Of)","Northern Mariana Islands (The)","Palau","Panama","Puerto Rico","Timor-Leste","Turks and Caicos Islands (The)","United States Minor Outlying Islands (The)","United States of America (The)","Virgin Islands (British)","Virgin Islands (u.s.)"]},{code:"USN",number:"997",digits:2,currency:"US Dollar (Next day)",countries:["United States of America (The)"]},{code:"UYI",number:"940",digits:0,currency:"Uruguay Peso en Unidades Indexadas (UI)",countries:["Uruguay"]},{code:"UYU",number:"858",digits:2,currency:"Peso Uruguayo",countries:["Uruguay"]},{code:"UYW",number:"927",digits:4,currency:"Unidad Previsional",countries:["Uruguay"]},{code:"UZS",number:"860",digits:2,currency:"Uzbekistan Sum",countries:["Uzbekistan"]},{code:"VED",number:"926",digits:2,currency:"Bolívar Soberano",countries:["Venezuela (Bolivarian Republic Of)"]},{code:"VES",number:"928",digits:2,currency:"Bolívar Soberano",countries:["Venezuela (Bolivarian Republic Of)"]},{code:"VND",number:"704",digits:0,currency:"Dong",countries:["Viet Nam"]},{code:"VUV",number:"548",digits:0,currency:"Vatu",countries:["Vanuatu"]},{code:"WST",number:"882",digits:2,currency:"Tala",countries:["Samoa"]},{code:"XAF",number:"950",digits:0,currency:"CFA Franc BEAC",countries:["Cameroon","Central African Republic (The)","Chad","Congo (The)","Equatorial Guinea","Gabon"]},{code:"XAG",number:"961",digits:0,currency:"Silver",countries:["Zz11_silver"]},{code:"XAU",number:"959",digits:0,currency:"Gold",countries:["Zz08_gold"]},{code:"XBA",number:"955",digits:0,currency:"Bond Markets Unit European Composite Unit (EURCO)",countries:["Zz01_bond Markets Unit European_eurco"]},{code:"XBB",number:"956",digits:0,currency:"Bond Markets Unit European Monetary Unit (E.M.U.-6)",countries:["Zz02_bond Markets Unit European_emu-6"]},{code:"XBC",number:"957",digits:0,currency:"Bond Markets Unit European Unit of Account 9 (E.U.A.-9)",countries:["Zz03_bond Markets Unit European_eua-9"]},{code:"XBD",number:"958",digits:0,currency:"Bond Markets Unit European Unit of Account 17 (E.U.A.-17)",countries:["Zz04_bond Markets Unit European_eua-17"]},{code:"XCD",number:"951",digits:2,currency:"East Caribbean Dollar",countries:["Anguilla","Antigua and Barbuda","Dominica","Grenada","Montserrat","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines"]},{code:"XDR",number:"960",digits:0,currency:"SDR (Special Drawing Right)",countries:["International Monetary Fund (Imf) "]},{code:"XOF",number:"952",digits:0,currency:"CFA Franc BCEAO",countries:["Benin","Burkina Faso","Côte D'ivoire","Guinea-Bissau","Mali","Niger (The)","Senegal","Togo"]},{code:"XPD",number:"964",digits:0,currency:"Palladium",countries:["Zz09_palladium"]},{code:"XPF",number:"953",digits:0,currency:"CFP Franc",countries:["French Polynesia","New Caledonia","Wallis and Futuna"]},{code:"XPT",number:"962",digits:0,currency:"Platinum",countries:["Zz10_platinum"]},{code:"XSU",number:"994",digits:0,currency:"Sucre",countries:['Sistema Unitario De Compensacion Regional De Pagos "Sucre"']},{code:"XTS",number:"963",digits:0,currency:"Codes specifically reserved for testing purposes",countries:["Zz06_testing_code"]},{code:"XUA",number:"965",digits:0,currency:"ADB Unit of Account",countries:["Member Countries of the African Development Bank Group"]},{code:"XXX",number:"999",digits:0,currency:"The codes assigned for transactions where no currency is involved",countries:["Zz07_no_currency"]},{code:"YER",number:"886",digits:2,currency:"Yemeni Rial",countries:["Yemen"]},{code:"ZAR",number:"710",digits:2,currency:"Rand",countries:["Lesotho","Namibia","South Africa"]},{code:"ZMW",number:"967",digits:2,currency:"Zambian Kwacha",countries:["Zambia"]},{code:"ZWG",number:"924",digits:2,currency:"Zimbabwe Gold",countries:["Zimbabwe"]}]),iy}var ay,y2;function EQ(){return y2||(y2=1,ay="2024-06-25"),ay}var A2;function kQ(){if(A2)return Ja;A2=1;var r=CQ(),e=xQ(),t=SQ(),n=EQ(),i=function(c){return c=c.toUpperCase(),r(t,function(d){return d.code===c})},a=function(c){return c=c.toLowerCase(),t.filter(function(d){return(d.countries.map(function(f){return f.toLowerCase()})||[]).indexOf(c)>-1})},s=function(c){return r(t,function(d){return d.number===String(c)})},o=function(){return t.map(function(c){return c.code})},l=function(){var c=t.map(function(d){return d.number});return c.filter(function(d){if(d)return d})},u=function(){var c=t.filter(function(d){return d.countries}).map(function(d){return d.countries});return e(Array.prototype.concat.apply([],c))};return Ja.code=i,Ja.country=a,Ja.number=s,Ja.codes=o,Ja.numbers=l,Ja.countries=u,Ja.publishDate=n,Ja.data=t,Ja}var b2=kQ();class FD{formatCurrencyForDisplay(e,t){const n={amount:t||0,currency:e,precision:this.getPrecisionForCurrency(e)};return wQ(n).toFormat(this.getSpecialFormat(e))}getPrecisionForCurrency(e){const t=e,n=b2.code(t);return n?n.digits:2}getSpecialFormat(e){const t=e;if(b2.code(t)?.code==="CLP")return"USD0,0"}}const w2=new FD;class ID{constructor(e,t,n,i){this.presentmentCurrency=void 0,this.presentmentCurrency=i,this.partnerCurrency=n,this.rateFrom=e,this.rateTo=t}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(e){return this.conversionRequired()?Math.ceil(this.subunits(this.units(e,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):e}units(e,t){return e/Math.pow(10,w2.getPrecisionForCurrency(t))}subunits(e,t){return e*Math.pow(10,w2.getPrecisionForCurrency(t))}}const TQ=async(r,e)=>{const t=await He.getShadowGraphqlClient().query({query:V3(e?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:r}});if(t.error)throw t.error;if(t.errors)throw t.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");if(!t.data.workflows||t.data.workflows.length!==r.length)throw new Error(`Unable to read workflows: ${t.errors??"Length mismatch in response"}`);const n=go(t.data.workflows);return n.forEach(i=>{i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),n},FQ=async(r,e)=>{const n=(await e).find(i=>i.id===r);if(!n)throw new Error(`Workflow not found: ${r}`);return n},Kb=async(r,e)=>{const t=r.map(o=>md.get({id:o,options:e})),n=r.filter((o,l)=>t[l]===void 0);if(n.length===0)return Promise.all(t);const i=TQ(n,e),a=n.map(o=>md.set({id:o,options:e},FQ(o,i))),s=t.filter(o=>o!==void 0);return await Promise.all(s.concat(a))},DD=async(r,e)=>(await Kb([r],e))[0],PD=async r=>{const e=await He.getShadowGraphqlClient().query({query:hT,variables:{ids:r},errorPolicy:"all",fetchPolicy:"no-cache"});return e.errors&&console.error(e.errors),e.data.integrationProducts||[]};class IQ{constructor(e){this.activeIntegration=void 0,this.updateTransactionState=async t=>{try{return He.getShadowGraphqlClient().mutate({...t,mutation:E3})}catch(n){throw console.error(n),new oo("Critical - Unable to synchronize workflow state with server.")}},this.options=e,this.options.applicationKey&&jO(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 43.1.0"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(e){Os.setHubUrl(e.hubUrl),Os.setServerUrl(e.serverUrl),Os.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&&qk(e.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&If.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getVersion(){return"43.1.0"}getAssetManager(){return Ln}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!GO())throw new Error("Application key required to use Flow Service.");return new TI}async getCurrencyContext(e){const n=(await this.getIntegration()).partner.currencyCode,a=await He.getShadowGraphqlClient().query({query:q3,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:n,to:e}}),{rateFrom:s,rateTo:o}=a.data.currencyConversion;return new ID(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=RD(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 He.getShadowGraphqlClient().query({query:Ov,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=He.getShadowGraphqlClient(),i=(await t.query({query:Ov,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;if(!i.id){const o=(await t.mutate({mutation:lV,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 If.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&&p0(s);const l=(await He.getShadowGraphqlClient().query({query:Ov,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 He.getShadowGraphqlClient().mutate({mutation:uV,variables:{emailAddress:e}}),await If.generateCode(e)}async verifyCode(e,t){const n=(await this.getIntegration()).partner.id||"",i=await If.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 He.getShadowGraphqlClient().mutate({mutation:cV,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),p0(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"),p0(""),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||gg(n.AccessToken);if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(e)||a){const s=await If.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 He.getShadowGraphqlClient().query({query:fV,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(e,t,n,i){const s=(await He.getShadowGraphqlClient().mutate({mutation:qU(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:e,initialMetadata:t?Object.entries(t).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,activationId:i},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 FE(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 y=Object.entries(localStorage).find(([C,k])=>C.startsWith("CognitoIdentityServiceProvider")&&C.endsWith("idToken"))?.[0]||"",A=localStorage.getItem(y);A&&!gg(A)&&(l.Authorization=`Bearer ${A}`)}const u={bundleOwnerId:o,...l,...i?.graphql?.additionalHeaders},c=await He.getShadowGraphqlClient().query({query:zU(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 d=c.data?.bundles[0],f=wr.getMap("bundlePartnerIds")||new Map;f.set(d.id,d.partner.id),wr.setMap("bundlePartnerIds",f);const h=new FE(this,d,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 BD(e),...i?.graphql?.additionalHeaders},l=(await He.getShadowGraphqlClient().mutate({mutation:WU(),variables:{id:e,template:t,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:n},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 He.getShadowGraphqlClient().query({query:i9(t??!1),variables:{...n,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const e=await He.getShadowGraphqlClient().query({query:$U,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 oo("No options provided!");const a=e.map((q,Y)=>({option:q,index:Y})),s=a.filter(q=>q.option.type==="transaction"),o=a.filter(q=>q.option.type==="integration"||q.option.type==="external"||q.option.type==="blank"),l=50,u=fA(s,l),c=fA(o,l);let d=0;const f=He.getShadowGraphqlClient(),h=async q=>{if(q.length===0)return[];const Y=q.map(oe=>oe.option.transactionId),J=await f.query({query:S3,variables:{ids:Y},errorPolicy:"all",fetchPolicy:"no-cache"}),se=J.data.transactions;if(d=d+se.length,i&&i(d,s.length),se.length!==q.length){const oe=J.errors?.[0]?.message||"Unknown error";throw new oo(`Not all transactions were found: ${oe}`)}return!this.activeIntegration&&se[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(se[0].integrationProduct.integration)),se.map((oe,he)=>({transaction:oe,workflowId:oe.workflowId,readOnly:q.find(ye=>ye.option.transactionId===oe.id)?.option.readOnly??!1,index:q[he].index}))},g=async q=>{if(q.length===0)return[];const Y=await f.mutate({mutation:x3,variables:{inputs:q.map(se=>({integrationProductId:se.option.type==="integration"?se.option.integrationProductId:void 0,externalIntegrationId:se.option.type==="external"?se.option.externalIntegrationId:void 0,externalProductId:se.option.type==="external"?se.option.externalProductId:void 0,workflowId:se.option.workflowId,designName:se.option.designName,claim:!0,quantity:se.option.quantity,recipient:se.option.recipient,parentTransactionId:se.option.parentTransactionId})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.getCreateTransactionContext(q,t)}),J=Y.data?.transactionCreateMany;if(!J||J.length===0){const se=Y.errors?.[0]?.message||"Unknown error";throw new oo(`Failed to create transactions: ${se}`)}return d=d+J.length,i&&i(d,s.length),J.map((se,oe)=>({transaction:se,workflowId:se.workflowId,readOnly:!1,index:q[oe].index}))},v=(await Promise.all([...u.map(h),...c.map(g)])).flat();let y=[...new Set(v.map(q=>q.transaction.integrationProductId))].filter(q=>!!q);y=y.filter(q=>!!q);let A=[...new Set(v.map(q=>q.workflowId))].filter(q=>!!q);A=A.filter(q=>!!q);const[C,k]=await Promise.all([(async()=>y.length>0?await PD(y):[])(),(async()=>A.length>0?await Kb(A,t):[])()]),F=new Map(C.map(q=>[q.id,q])),S=new Map(k.map(q=>[q.id,q])),R=v.map(async q=>{const{transaction:Y,workflowId:J,readOnly:se,index:oe}=q,he=J?S.get(J):void 0,ye=e[oe];if(Y.integrationProductId){const re=F.get(Y.integrationProductId);Y.integrationProduct=re,Y.product=re?.product,Y.integrationProduct||console.error("failed to find transaction's product")}const Ue=wr.getMap("transactionOwnerIds")||new Map;!Ue.get(Y.id)&&Y.transactionOwnerId&&(Ue.set(Y.id,Y.transactionOwnerId),wr.setMap("transactionOwnerIds",Ue));const Re=Ue.get(Y.id)||void 0,Oe=new dV({onMutate:()=>({context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}})}),ee={workflow:he,transaction:Y,singleVariantsRenderable:ye?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:se?async()=>{throw new nn("State mutation is forbidden in read only mode!")}:async re=>this.updateTransactionState({...re,context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}}),graphQlClient:()=>Oe,readOnly:se,isReloadedTransaction:ye.type==="transaction"};if(ye.type==="transaction"&&Y.workflowState){const re=JSON.parse(Y.workflowState);await sA(re),ee.reloadedState=re}else if(!se&&ye.workflowState){const re=JSON.parse(ye.workflowState);await sA(re),ee.reloadedState=re}return ee.delayWorkflowStateSync=!0,{experienceOptions:ee,index:oe,options:ye}}),j=(await Promise.all(R)).sort((q,Y)=>q.index-Y.index);let G=[],ie=[];for(const q of j){const{experienceOptions:Y,options:J}=q,se=new wI(this,Y);await se.getWorkflowManager().getInitializationPromise(),n&&n(),J.type!=="transaction"&&this.customer&&ie.push(se),G=[...G,se],se.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}if(ie.length>0){const q=this.customer.emailAddress,Y=ie.map(oe=>oe.getTransaction().id),se=(await f.mutate({mutation:_9,variables:{ids:Y,details:{emailAddress:q},type:"Owner"},errorPolicy:"all"})).data?.transactionsAddStakeholder;if(se&&se?.length>0){const oe=se[0].stakeholders?.find(he=>he.customer?.emailAddress===q);if(oe?.customer)for(const he of ie)he.assignCustomerInternal(oe.customer)}}return G}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 He.getShadowGraphqlClient().query({query:R3(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 pA(a[0])}async getIntegrationProductFromExternalIds(e,t,n){const s=(await He.getShadowGraphqlClient().query({query:O3(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 pA(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 He.getShadowGraphqlClient().query({query:D3,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 He.getShadowGraphqlClient().mutate({mutation:G3,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 RD=async(r,e)=>(await He.getShadowGraphqlClient().query({query:$3,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r},skipIntegrationCheck:!0},variables:{themeConfigurationId:e}})).data.currentIntegration,DQ=async r=>{const t=await He.getShadowGraphqlClient().query({query:I3,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(t.data.transactions.length!==0)return t.data.transactions[0]},PQ=async(r,e)=>(await He.getShadowGraphqlClient().query({query:z3,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:e}})).data?.marketplaceThemeInstallConfiguration,RQ=async r=>(await He.getShadowGraphqlClient().query({query:j3,errorPolicy:"all",variables:{id:r}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,OQ=async r=>(await He.getShadowGraphqlClient().query({query:H3,errorPolicy:"all",variables:{id:r}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function OD(){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&&!gg(i)&&(r.Authorization=`Bearer ${i}`)}return r}async function BD(r){const t=wr.getMap("bundleOwnerIds")?.get(r),n=await OD();return{bundleOwnerId:t,...n}}async function BQ(r){const t=wr.getMap("transactionOwnerIds")?.get(r),n=await OD();return{transactionOwnerId:t,...n}}const MQ=async r=>{const e=await BD(r),t=await He.getShadowGraphqlClient().mutate({mutation:h9,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}`)},_Q=async r=>{const e=await BQ(r),t=await He.getShadowGraphqlClient().mutate({mutation:p9,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 MD(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:Ip(r.x,e.width-l,0),y:Ip(r.y,e.height-u,0),zoom:o}}return{...r,x:Ip(r.x,-i,e.width),y:Ip(r.y,-a,e.height)}}function Ip(r,e,t){return Math.min(Math.max(r,e),t)}class _D{constructor(e,t){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=bI(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 Qd(o),u=this.frameData?this.frameData[s]:void 0;vd(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=Bu.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=Ug(this.imageData.svg,this.imageData.colors||{},!1);return Ng(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],d=n[o]-u*e[o];return{x:c,y:d,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 nn("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]=MD(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 nn("Frame data not set. This is a bug");if(!this.workflowManager)throw new nn("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(d=>d.id===l)?.regionIndex??u;c>=e.length&&(c=u);try{o(new On([new dL(l,t,e[c]),new hL(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]={...w1(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 NQ{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(e,t,n,i,a,s,o,l,u,c,d,f,h,g,v,y,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()}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 ND=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(ND||{}),LD=(r=>(r.Original="original",r.BackgroundRemoved="backgroundRemoved",r.Optimized="optimized",r))(LD||{});class UD extends Ui{constructor(e,t,n){super(e,t,n);const i=t.data;this.frameService=new _D(i.forceImageCover,i.initialZoomLevel),this.frameService.connectWorkflowManager(e,t.stepName)}selectVariant(e){const t=this.manager.getRegionElements(this.step.stepName);return so.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 so.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(Rg.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 Ln.removeBackgroundFromAsset(t);e&&await so.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 Ln.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 Ln.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 Ln.getLocalOrFromServer(e)}async getVectorizedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey;if(e)return Ln.getLocalOrFromServer(e)}async getEnhancedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.enhancedAssetKey;if(e)return Ln.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 so.changeColors(this.step,this.manager,e)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await ft.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?so.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const e=this.getImageData();return e?.svg?(await Pa(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}=oT(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 so.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 Ln.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 LQ=Ee`
2890
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var lQ={normalizePrecision:function(e){var t=e.reduce(function(n,i){return Math.max(n.getPrecision(),i.getPrecision())});return e.map(function(n){return n.getPrecision()!==t?n.convertPrecision(t):n})},minimum:function(e){var t=f2(e),n=t[0],i=t.slice(1),a=n;return i.forEach(function(s){a=a.lessThan(s)?a:s}),a},maximum:function(e){var t=f2(e),n=t[0],i=t.slice(1),a=n;return i.forEach(function(s){a=a.greaterThan(s)?a:s}),a}};function ED(r){return!isNaN(parseInt(r))&&isFinite(r)}function uQ(r){return ED(r)&&r<=100&&r>=0}function cQ(r){return r.length>0&&r.every(function(e){return e>=0})&&r.some(function(e){return e>0})}function h2(r){return r%2===0}function p2(r){return ED(r)&&!Number.isInteger(r)}function fQ(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=r.toString();if(e.indexOf("e-")>0)return parseInt(e.split("e-")[1]);var t=e.split(".")[1];return t?t.length:0}function Df(r){return Math.abs(r)%1===.5}function dQ(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise(function(t,n){var i=Object.assign(new XMLHttpRequest,{onreadystatechange:function(){i.readyState===4&&(i.status>=200&&i.status<400?t(JSON.parse(i.responseText)):n(new Error(i.statusText)))},onerror:function(){n(new Error("Network error"))}});i.open("GET",r,!0),hQ(i,e.headers),i.send()})}function hQ(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};for(var t in e)r.setRequestHeader(t,e[t]);return r}function jf(r){return typeof r>"u"}function kD(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:".",t={};return Object.entries(r).forEach(function(n){if(id(n[1])==="object"){var i=kD(n[1]);Object.entries(i).forEach(function(a){t[n[0]+e+a[0]]=a[1]})}else t[n[0]]=n[1]}),t}function pQ(r){return!!r&&(id(r)==="object"||typeof r=="function")&&typeof r.then=="function"}function TD(){var r=function(n,i){var a=function(l){return Math.pow(10,fQ(l))},s=Math.max(a(n),a(i));return Math.round(n*s)*Math.round(i*s)/(s*s)},e={HALF_ODD:function(n){var i=Math.round(n);return Df(n)&&h2(i)?i-1:i},HALF_EVEN:function(n){var i=Math.round(n);return Df(n)?h2(i)?i:i-1:i},HALF_UP:function(n){return Math.round(n)},HALF_DOWN:function(n){return Df(n)?Math.floor(n):Math.round(n)},HALF_TOWARDS_ZERO:function(n){return Df(n)?Math.sign(n)*Math.floor(Math.abs(n)):Math.round(n)},HALF_AWAY_FROM_ZERO:function(n){return Df(n)?Math.sign(n)*Math.ceil(Math.abs(n)):Math.round(n)},DOWN:function(n){return Math.floor(n)}};return{add:function(n,i){return n+i},subtract:function(n,i){return n-i},multiply:function(n,i){return p2(n)||p2(i)?r(n,i):n*i},divide:function(n,i){return n/i},modulo:function(n,i){return n%i},round:function(n){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"HALF_EVEN";return e[i](n)}}}var gQ=TD();function mQ(r){var e=/^(?:(\$|USD)?0(?:(,)0)?(\.)?(0+)?|0(?:(,)0)?(\.)?(0+)?\s?(dollar)?)$/gm.exec(r);return{getMatches:function(){return e!==null?e.slice(1).filter(function(n){return!jf(n)}):[]},getMinimumFractionDigits:function(){var n=function(a){return a==="."};return jf(this.getMatches().find(n))?0:this.getMatches()[gQ.add(this.getMatches().findIndex(n),1)].split("").length},getCurrencyDisplay:function(){var n={USD:"code",dollar:"name",$:"symbol"};return n[this.getMatches().find(function(i){return i==="USD"||i==="dollar"||i==="$"})]},getStyle:function(){return jf(this.getCurrencyDisplay(this.getMatches()))?"decimal":"currency"},getUseGrouping:function(){return!jf(this.getMatches().find(function(n){return n===","}))}}}function vQ(r){var e=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",a=arguments.length>1?arguments[1]:void 0;for(var s in a)i=i.replace("{{".concat(s,"}}"),a[s]);return i},t=function(i,a){return dQ(e(r.endpoint,{from:i,to:a}),{headers:r.headers})};return{getExchangeRate:function(i,a){return(pQ(r.endpoint)?r.endpoint:t(i,a)).then(function(s){return kD(s)[e(r.propertyPath,{from:i,to:a})]})}}}function Id(r,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Error;if(!r)throw new t(e)}function yQ(r){Id(uQ(r),"You must provide a numeric value between 0 and 100.",RangeError)}function AQ(r){Id(cQ(r),"You must provide a non-empty array of numeric values greater than 0.",TypeError)}function ty(r){Id(Number.isInteger(r),"You must provide an integer.",TypeError)}var kn=TD(),bQ=function r(e){var t=Object.assign({},{amount:r.defaultAmount,currency:r.defaultCurrency,precision:r.defaultPrecision},e),n=t.amount,i=t.currency,a=t.precision;ty(n),ty(a);var s=r.globalLocale,o=r.globalFormat,l=r.globalRoundingMode,u=r.globalFormatRoundingMode,c=Object.assign({},r.globalExchangeRatesApi),d=function(g){var v=Object.assign({},Object.assign({},{amount:n,currency:i,precision:a},g),Object.assign({},{locale:this.locale},g));return Object.assign(r({amount:v.amount,currency:v.currency,precision:v.precision}),{locale:v.locale})},f=function(g){Id(this.hasSameCurrency(g),"You must provide a Dinero instance with the same currency.",TypeError)};return{getAmount:function(){return n},getCurrency:function(){return i},getLocale:function(){return this.locale||s},setLocale:function(g){return d.call(this,{locale:g})},getPrecision:function(){return a},convertPrecision:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u;ty(g);var y=this.getPrecision(),A=g>y,C=A?kn.multiply:kn.divide,k=A?[g,y]:[y,g],F=Math.pow(10,kn.subtract.apply(kn,k));return d.call(this,{amount:kn.round(C(this.getAmount(),F),v),precision:g})},add:function(g){f.call(this,g);var v=r.normalizePrecision([this,g]);return d.call(this,{amount:kn.add(v[0].getAmount(),v[1].getAmount()),precision:v[0].getPrecision()})},subtract:function(g){f.call(this,g);var v=r.normalizePrecision([this,g]);return d.call(this,{amount:kn.subtract(v[0].getAmount(),v[1].getAmount()),precision:v[0].getPrecision()})},multiply:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return d.call(this,{amount:kn.round(kn.multiply(this.getAmount(),g),v)})},divide:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return d.call(this,{amount:kn.round(kn.divide(this.getAmount(),g),v)})},percentage:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return yQ(g),this.multiply(kn.divide(g,100),v)},allocate:function(g){var v=this;AQ(g);for(var y=g.reduce(function(F,S){return kn.add(F,S)}),A=this.getAmount(),C=g.map(function(F){var S=Math.floor(kn.divide(kn.multiply(v.getAmount(),F),y));return A=kn.subtract(A,S),d.call(v,{amount:S})}),k=0;A>0;)g[k]>0&&(C[k]=C[k].add(d.call(this,{amount:1})),A=kn.subtract(A,1)),k+=1;return C},convert:function(g){var v=this,y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},A=y.endpoint,C=A===void 0?c.endpoint:A,k=y.propertyPath,F=k===void 0?c.propertyPath||"rates.{{to}}":k,S=y.headers,R=S===void 0?c.headers:S,M=y.roundingMode,j=M===void 0?l:M,G=Object.assign({},{endpoint:C,propertyPath:F,headers:R,roundingMode:j});return vQ(G).getExchangeRate(this.getCurrency(),g).then(function(ie){return Id(!jf(ie),'No rate was found for the destination currency "'.concat(g,'".'),TypeError),d.call(v,{amount:kn.round(kn.multiply(v.getAmount(),parseFloat(ie)),G.roundingMode),currency:g})})},equalsTo:function(g){return this.hasSameAmount(g)&&this.hasSameCurrency(g)},lessThan:function(g){f.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()<v[1].getAmount()},lessThanOrEqual:function(g){f.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()<=v[1].getAmount()},greaterThan:function(g){f.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()>v[1].getAmount()},greaterThanOrEqual:function(g){f.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()>=v[1].getAmount()},isZero:function(){return this.getAmount()===0},isPositive:function(){return this.getAmount()>=0},isNegative:function(){return this.getAmount()<0},hasSubUnits:function(){return kn.modulo(this.getAmount(),Math.pow(10,a))!==0},hasCents:function(){return kn.modulo(this.getAmount(),Math.pow(10,a))!==0},hasSameCurrency:function(g){return this.getCurrency()===g.getCurrency()},hasSameAmount:function(g){var v=r.normalizePrecision([this,g]);return v[0].getAmount()===v[1].getAmount()},toFormat:function(){var g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:o,v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u,y=mQ(g);return this.toRoundedUnit(y.getMinimumFractionDigits(),v).toLocaleString(this.getLocale(),{currencyDisplay:y.getCurrencyDisplay(),useGrouping:y.getUseGrouping(),minimumFractionDigits:y.getMinimumFractionDigits(),style:y.getStyle(),currency:this.getCurrency()})},toUnit:function(){return kn.divide(this.getAmount(),Math.pow(10,a))},toRoundedUnit:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u,y=Math.pow(10,g);return kn.divide(kn.round(kn.multiply(this.toUnit(),y),v),y)},toObject:function(){return{amount:n,currency:i,precision:a}},toJSON:function(){return this.toObject()}}},wQ=Object.assign(bQ,rQ,nQ,lQ),Ja={},ry,g2;function CQ(){if(g2)return ry;g2=1;function r(t){return t}function e(t,a,s){for(var a=a||r,s=s||t,o=0,l=t.length;o<l;o+=1)if(a.call(s,t[o],o))return t[o]}return ry=e,ry}var ny={exports:{}},m2;function xQ(){if(m2)return ny.exports;m2=1;var r=ny.exports=function(e,t){if(typeof e=="function"||t)return r.by(e,t);for(var n={object:[],function:[],string:{},number:{},boolean:{},undefined:{}},i=[],a=0;a<e.length;a++){var s=e[a],o=s==="__proto__"?n.objects:n[typeof s]||n.objects;Array.isArray(o)?o.indexOf(s)<0&&(o.push(s),i.push(s)):Object.hasOwnProperty.call(o,s)||(o[s]=!0,i.push(s))}return i};return r.by=function(e,t){if(typeof e=="function"){var n=t;t=e,e=n}for(var i=[],a=0;a<e.length;a++){for(var s=e[a],o=!1,l=0;l<i.length;l++){var u=i[l];if(t.call(i,s,u)){o=!0;break}}o||i.push(s)}return i},ny.exports}var iy,v2;function SQ(){return v2||(v2=1,iy=[{code:"AED",number:"784",digits:2,currency:"UAE Dirham",countries:["United Arab Emirates (The)"]},{code:"AFN",number:"971",digits:2,currency:"Afghani",countries:["Afghanistan"]},{code:"ALL",number:"008",digits:2,currency:"Lek",countries:["Albania"]},{code:"AMD",number:"051",digits:2,currency:"Armenian Dram",countries:["Armenia"]},{code:"ANG",number:"532",digits:2,currency:"Netherlands Antillean Guilder",countries:["Curaçao","Sint Maarten (Dutch Part)"]},{code:"AOA",number:"973",digits:2,currency:"Kwanza",countries:["Angola"]},{code:"ARS",number:"032",digits:2,currency:"Argentine Peso",countries:["Argentina"]},{code:"AUD",number:"036",digits:2,currency:"Australian Dollar",countries:["Australia","Christmas Island","Cocos (Keeling) Islands (The)","Heard Island and Mcdonald Islands","Kiribati","Nauru","Norfolk Island","Tuvalu"]},{code:"AWG",number:"533",digits:2,currency:"Aruban Florin",countries:["Aruba"]},{code:"AZN",number:"944",digits:2,currency:"Azerbaijan Manat",countries:["Azerbaijan"]},{code:"BAM",number:"977",digits:2,currency:"Convertible Mark",countries:["Bosnia and Herzegovina"]},{code:"BBD",number:"052",digits:2,currency:"Barbados Dollar",countries:["Barbados"]},{code:"BDT",number:"050",digits:2,currency:"Taka",countries:["Bangladesh"]},{code:"BGN",number:"975",digits:2,currency:"Bulgarian Lev",countries:["Bulgaria"]},{code:"BHD",number:"048",digits:3,currency:"Bahraini Dinar",countries:["Bahrain"]},{code:"BIF",number:"108",digits:0,currency:"Burundi Franc",countries:["Burundi"]},{code:"BMD",number:"060",digits:2,currency:"Bermudian Dollar",countries:["Bermuda"]},{code:"BND",number:"096",digits:2,currency:"Brunei Dollar",countries:["Brunei Darussalam"]},{code:"BOB",number:"068",digits:2,currency:"Boliviano",countries:["Bolivia (Plurinational State Of)"]},{code:"BOV",number:"984",digits:2,currency:"Mvdol",countries:["Bolivia (Plurinational State Of)"]},{code:"BRL",number:"986",digits:2,currency:"Brazilian Real",countries:["Brazil"]},{code:"BSD",number:"044",digits:2,currency:"Bahamian Dollar",countries:["Bahamas (The)"]},{code:"BTN",number:"064",digits:2,currency:"Ngultrum",countries:["Bhutan"]},{code:"BWP",number:"072",digits:2,currency:"Pula",countries:["Botswana"]},{code:"BYN",number:"933",digits:2,currency:"Belarusian Ruble",countries:["Belarus"]},{code:"BZD",number:"084",digits:2,currency:"Belize Dollar",countries:["Belize"]},{code:"CAD",number:"124",digits:2,currency:"Canadian Dollar",countries:["Canada"]},{code:"CDF",number:"976",digits:2,currency:"Congolese Franc",countries:["Congo (The Democratic Republic of The)"]},{code:"CHE",number:"947",digits:2,currency:"WIR Euro",countries:["Switzerland"]},{code:"CHF",number:"756",digits:2,currency:"Swiss Franc",countries:["Liechtenstein","Switzerland"]},{code:"CHW",number:"948",digits:2,currency:"WIR Franc",countries:["Switzerland"]},{code:"CLF",number:"990",digits:4,currency:"Unidad de Fomento",countries:["Chile"]},{code:"CLP",number:"152",digits:0,currency:"Chilean Peso",countries:["Chile"]},{code:"CNY",number:"156",digits:2,currency:"Yuan Renminbi",countries:["China"]},{code:"COP",number:"170",digits:2,currency:"Colombian Peso",countries:["Colombia"]},{code:"COU",number:"970",digits:2,currency:"Unidad de Valor Real",countries:["Colombia"]},{code:"CRC",number:"188",digits:2,currency:"Costa Rican Colon",countries:["Costa Rica"]},{code:"CUC",number:"931",digits:2,currency:"Peso Convertible",countries:["Cuba"]},{code:"CUP",number:"192",digits:2,currency:"Cuban Peso",countries:["Cuba"]},{code:"CVE",number:"132",digits:2,currency:"Cabo Verde Escudo",countries:["Cabo Verde"]},{code:"CZK",number:"203",digits:2,currency:"Czech Koruna",countries:["Czechia"]},{code:"DJF",number:"262",digits:0,currency:"Djibouti Franc",countries:["Djibouti"]},{code:"DKK",number:"208",digits:2,currency:"Danish Krone",countries:["Denmark","Faroe Islands (The)","Greenland"]},{code:"DOP",number:"214",digits:2,currency:"Dominican Peso",countries:["Dominican Republic (The)"]},{code:"DZD",number:"012",digits:2,currency:"Algerian Dinar",countries:["Algeria"]},{code:"EGP",number:"818",digits:2,currency:"Egyptian Pound",countries:["Egypt"]},{code:"ERN",number:"232",digits:2,currency:"Nakfa",countries:["Eritrea"]},{code:"ETB",number:"230",digits:2,currency:"Ethiopian Birr",countries:["Ethiopia"]},{code:"EUR",number:"978",digits:2,currency:"Euro",countries:["Åland Islands","Andorra","Austria","Belgium","Croatia","Cyprus","Estonia","European Union","Finland","France","French Guiana","French Southern Territories (The)","Germany","Greece","Guadeloupe","Holy See (The)","Ireland","Italy","Latvia","Lithuania","Luxembourg","Malta","Martinique","Mayotte","Monaco","Montenegro","Netherlands (The)","Portugal","Réunion","Saint Barthélemy","Saint Martin (French Part)","Saint Pierre and Miquelon","San Marino","Slovakia","Slovenia","Spain"]},{code:"FJD",number:"242",digits:2,currency:"Fiji Dollar",countries:["Fiji"]},{code:"FKP",number:"238",digits:2,currency:"Falkland Islands Pound",countries:["Falkland Islands (The) [Malvinas]"]},{code:"GBP",number:"826",digits:2,currency:"Pound Sterling",countries:["Guernsey","Isle of Man","Jersey","United Kingdom of Great Britain and Northern Ireland (The)"]},{code:"GEL",number:"981",digits:2,currency:"Lari",countries:["Georgia"]},{code:"GHS",number:"936",digits:2,currency:"Ghana Cedi",countries:["Ghana"]},{code:"GIP",number:"292",digits:2,currency:"Gibraltar Pound",countries:["Gibraltar"]},{code:"GMD",number:"270",digits:2,currency:"Dalasi",countries:["Gambia (The)"]},{code:"GNF",number:"324",digits:0,currency:"Guinean Franc",countries:["Guinea"]},{code:"GTQ",number:"320",digits:2,currency:"Quetzal",countries:["Guatemala"]},{code:"GYD",number:"328",digits:2,currency:"Guyana Dollar",countries:["Guyana"]},{code:"HKD",number:"344",digits:2,currency:"Hong Kong Dollar",countries:["Hong Kong"]},{code:"HNL",number:"340",digits:2,currency:"Lempira",countries:["Honduras"]},{code:"HTG",number:"332",digits:2,currency:"Gourde",countries:["Haiti"]},{code:"HUF",number:"348",digits:2,currency:"Forint",countries:["Hungary"]},{code:"IDR",number:"360",digits:2,currency:"Rupiah",countries:["Indonesia"]},{code:"ILS",number:"376",digits:2,currency:"New Israeli Sheqel",countries:["Israel"]},{code:"INR",number:"356",digits:2,currency:"Indian Rupee",countries:["Bhutan","India"]},{code:"IQD",number:"368",digits:3,currency:"Iraqi Dinar",countries:["Iraq"]},{code:"IRR",number:"364",digits:2,currency:"Iranian Rial",countries:["Iran (Islamic Republic Of)"]},{code:"ISK",number:"352",digits:0,currency:"Iceland Krona",countries:["Iceland"]},{code:"JMD",number:"388",digits:2,currency:"Jamaican Dollar",countries:["Jamaica"]},{code:"JOD",number:"400",digits:3,currency:"Jordanian Dinar",countries:["Jordan"]},{code:"JPY",number:"392",digits:0,currency:"Yen",countries:["Japan"]},{code:"KES",number:"404",digits:2,currency:"Kenyan Shilling",countries:["Kenya"]},{code:"KGS",number:"417",digits:2,currency:"Som",countries:["Kyrgyzstan"]},{code:"KHR",number:"116",digits:2,currency:"Riel",countries:["Cambodia"]},{code:"KMF",number:"174",digits:0,currency:"Comorian Franc ",countries:["Comoros (The)"]},{code:"KPW",number:"408",digits:2,currency:"North Korean Won",countries:["Korea (The Democratic People’s Republic Of)"]},{code:"KRW",number:"410",digits:0,currency:"Won",countries:["Korea (The Republic Of)"]},{code:"KWD",number:"414",digits:3,currency:"Kuwaiti Dinar",countries:["Kuwait"]},{code:"KYD",number:"136",digits:2,currency:"Cayman Islands Dollar",countries:["Cayman Islands (The)"]},{code:"KZT",number:"398",digits:2,currency:"Tenge",countries:["Kazakhstan"]},{code:"LAK",number:"418",digits:2,currency:"Lao Kip",countries:["Lao People’s Democratic Republic (The)"]},{code:"LBP",number:"422",digits:2,currency:"Lebanese Pound",countries:["Lebanon"]},{code:"LKR",number:"144",digits:2,currency:"Sri Lanka Rupee",countries:["Sri Lanka"]},{code:"LRD",number:"430",digits:2,currency:"Liberian Dollar",countries:["Liberia"]},{code:"LSL",number:"426",digits:2,currency:"Loti",countries:["Lesotho"]},{code:"LYD",number:"434",digits:3,currency:"Libyan Dinar",countries:["Libya"]},{code:"MAD",number:"504",digits:2,currency:"Moroccan Dirham",countries:["Morocco","Western Sahara"]},{code:"MDL",number:"498",digits:2,currency:"Moldovan Leu",countries:["Moldova (The Republic Of)"]},{code:"MGA",number:"969",digits:2,currency:"Malagasy Ariary",countries:["Madagascar"]},{code:"MKD",number:"807",digits:2,currency:"Denar",countries:["North Macedonia"]},{code:"MMK",number:"104",digits:2,currency:"Kyat",countries:["Myanmar"]},{code:"MNT",number:"496",digits:2,currency:"Tugrik",countries:["Mongolia"]},{code:"MOP",number:"446",digits:2,currency:"Pataca",countries:["Macao"]},{code:"MRU",number:"929",digits:2,currency:"Ouguiya",countries:["Mauritania"]},{code:"MUR",number:"480",digits:2,currency:"Mauritius Rupee",countries:["Mauritius"]},{code:"MVR",number:"462",digits:2,currency:"Rufiyaa",countries:["Maldives"]},{code:"MWK",number:"454",digits:2,currency:"Malawi Kwacha",countries:["Malawi"]},{code:"MXN",number:"484",digits:2,currency:"Mexican Peso",countries:["Mexico"]},{code:"MXV",number:"979",digits:2,currency:"Mexican Unidad de Inversion (UDI)",countries:["Mexico"]},{code:"MYR",number:"458",digits:2,currency:"Malaysian Ringgit",countries:["Malaysia"]},{code:"MZN",number:"943",digits:2,currency:"Mozambique Metical",countries:["Mozambique"]},{code:"NAD",number:"516",digits:2,currency:"Namibia Dollar",countries:["Namibia"]},{code:"NGN",number:"566",digits:2,currency:"Naira",countries:["Nigeria"]},{code:"NIO",number:"558",digits:2,currency:"Cordoba Oro",countries:["Nicaragua"]},{code:"NOK",number:"578",digits:2,currency:"Norwegian Krone",countries:["Bouvet Island","Norway","Svalbard and Jan Mayen"]},{code:"NPR",number:"524",digits:2,currency:"Nepalese Rupee",countries:["Nepal"]},{code:"NZD",number:"554",digits:2,currency:"New Zealand Dollar",countries:["Cook Islands (The)","New Zealand","Niue","Pitcairn","Tokelau"]},{code:"OMR",number:"512",digits:3,currency:"Rial Omani",countries:["Oman"]},{code:"PAB",number:"590",digits:2,currency:"Balboa",countries:["Panama"]},{code:"PEN",number:"604",digits:2,currency:"Sol",countries:["Peru"]},{code:"PGK",number:"598",digits:2,currency:"Kina",countries:["Papua New Guinea"]},{code:"PHP",number:"608",digits:2,currency:"Philippine Peso",countries:["Philippines (The)"]},{code:"PKR",number:"586",digits:2,currency:"Pakistan Rupee",countries:["Pakistan"]},{code:"PLN",number:"985",digits:2,currency:"Zloty",countries:["Poland"]},{code:"PYG",number:"600",digits:0,currency:"Guarani",countries:["Paraguay"]},{code:"QAR",number:"634",digits:2,currency:"Qatari Rial",countries:["Qatar"]},{code:"RON",number:"946",digits:2,currency:"Romanian Leu",countries:["Romania"]},{code:"RSD",number:"941",digits:2,currency:"Serbian Dinar",countries:["Serbia"]},{code:"RUB",number:"643",digits:2,currency:"Russian Ruble",countries:["Russian Federation (The)"]},{code:"RWF",number:"646",digits:0,currency:"Rwanda Franc",countries:["Rwanda"]},{code:"SAR",number:"682",digits:2,currency:"Saudi Riyal",countries:["Saudi Arabia"]},{code:"SBD",number:"090",digits:2,currency:"Solomon Islands Dollar",countries:["Solomon Islands"]},{code:"SCR",number:"690",digits:2,currency:"Seychelles Rupee",countries:["Seychelles"]},{code:"SDG",number:"938",digits:2,currency:"Sudanese Pound",countries:["Sudan (The)"]},{code:"SEK",number:"752",digits:2,currency:"Swedish Krona",countries:["Sweden"]},{code:"SGD",number:"702",digits:2,currency:"Singapore Dollar",countries:["Singapore"]},{code:"SHP",number:"654",digits:2,currency:"Saint Helena Pound",countries:["Saint Helena, Ascension and Tristan Da Cunha"]},{code:"SLE",number:"925",digits:2,currency:"Leone",countries:["Sierra Leone"]},{code:"SOS",number:"706",digits:2,currency:"Somali Shilling",countries:["Somalia"]},{code:"SRD",number:"968",digits:2,currency:"Surinam Dollar",countries:["Suriname"]},{code:"SSP",number:"728",digits:2,currency:"South Sudanese Pound",countries:["South Sudan"]},{code:"STN",number:"930",digits:2,currency:"Dobra",countries:["Sao Tome and Principe"]},{code:"SVC",number:"222",digits:2,currency:"El Salvador Colon",countries:["El Salvador"]},{code:"SYP",number:"760",digits:2,currency:"Syrian Pound",countries:["Syrian Arab Republic"]},{code:"SZL",number:"748",digits:2,currency:"Lilangeni",countries:["Eswatini"]},{code:"THB",number:"764",digits:2,currency:"Baht",countries:["Thailand"]},{code:"TJS",number:"972",digits:2,currency:"Somoni",countries:["Tajikistan"]},{code:"TMT",number:"934",digits:2,currency:"Turkmenistan New Manat",countries:["Turkmenistan"]},{code:"TND",number:"788",digits:3,currency:"Tunisian Dinar",countries:["Tunisia"]},{code:"TOP",number:"776",digits:2,currency:"Pa’anga",countries:["Tonga"]},{code:"TRY",number:"949",digits:2,currency:"Turkish Lira",countries:["Türki̇ye"]},{code:"TTD",number:"780",digits:2,currency:"Trinidad and Tobago Dollar",countries:["Trinidad and Tobago"]},{code:"TWD",number:"901",digits:2,currency:"New Taiwan Dollar",countries:["Taiwan (Province of China)"]},{code:"TZS",number:"834",digits:2,currency:"Tanzanian Shilling",countries:["Tanzania, United Republic Of"]},{code:"UAH",number:"980",digits:2,currency:"Hryvnia",countries:["Ukraine"]},{code:"UGX",number:"800",digits:0,currency:"Uganda Shilling",countries:["Uganda"]},{code:"USD",number:"840",digits:2,currency:"US Dollar",countries:["American Samoa","Bonaire, Sint Eustatius and Saba","British Indian Ocean Territory (The)","Ecuador","El Salvador","Guam","Haiti","Marshall Islands (The)","Micronesia (Federated States Of)","Northern Mariana Islands (The)","Palau","Panama","Puerto Rico","Timor-Leste","Turks and Caicos Islands (The)","United States Minor Outlying Islands (The)","United States of America (The)","Virgin Islands (British)","Virgin Islands (u.s.)"]},{code:"USN",number:"997",digits:2,currency:"US Dollar (Next day)",countries:["United States of America (The)"]},{code:"UYI",number:"940",digits:0,currency:"Uruguay Peso en Unidades Indexadas (UI)",countries:["Uruguay"]},{code:"UYU",number:"858",digits:2,currency:"Peso Uruguayo",countries:["Uruguay"]},{code:"UYW",number:"927",digits:4,currency:"Unidad Previsional",countries:["Uruguay"]},{code:"UZS",number:"860",digits:2,currency:"Uzbekistan Sum",countries:["Uzbekistan"]},{code:"VED",number:"926",digits:2,currency:"Bolívar Soberano",countries:["Venezuela (Bolivarian Republic Of)"]},{code:"VES",number:"928",digits:2,currency:"Bolívar Soberano",countries:["Venezuela (Bolivarian Republic Of)"]},{code:"VND",number:"704",digits:0,currency:"Dong",countries:["Viet Nam"]},{code:"VUV",number:"548",digits:0,currency:"Vatu",countries:["Vanuatu"]},{code:"WST",number:"882",digits:2,currency:"Tala",countries:["Samoa"]},{code:"XAF",number:"950",digits:0,currency:"CFA Franc BEAC",countries:["Cameroon","Central African Republic (The)","Chad","Congo (The)","Equatorial Guinea","Gabon"]},{code:"XAG",number:"961",digits:0,currency:"Silver",countries:["Zz11_silver"]},{code:"XAU",number:"959",digits:0,currency:"Gold",countries:["Zz08_gold"]},{code:"XBA",number:"955",digits:0,currency:"Bond Markets Unit European Composite Unit (EURCO)",countries:["Zz01_bond Markets Unit European_eurco"]},{code:"XBB",number:"956",digits:0,currency:"Bond Markets Unit European Monetary Unit (E.M.U.-6)",countries:["Zz02_bond Markets Unit European_emu-6"]},{code:"XBC",number:"957",digits:0,currency:"Bond Markets Unit European Unit of Account 9 (E.U.A.-9)",countries:["Zz03_bond Markets Unit European_eua-9"]},{code:"XBD",number:"958",digits:0,currency:"Bond Markets Unit European Unit of Account 17 (E.U.A.-17)",countries:["Zz04_bond Markets Unit European_eua-17"]},{code:"XCD",number:"951",digits:2,currency:"East Caribbean Dollar",countries:["Anguilla","Antigua and Barbuda","Dominica","Grenada","Montserrat","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines"]},{code:"XDR",number:"960",digits:0,currency:"SDR (Special Drawing Right)",countries:["International Monetary Fund (Imf) "]},{code:"XOF",number:"952",digits:0,currency:"CFA Franc BCEAO",countries:["Benin","Burkina Faso","Côte D'ivoire","Guinea-Bissau","Mali","Niger (The)","Senegal","Togo"]},{code:"XPD",number:"964",digits:0,currency:"Palladium",countries:["Zz09_palladium"]},{code:"XPF",number:"953",digits:0,currency:"CFP Franc",countries:["French Polynesia","New Caledonia","Wallis and Futuna"]},{code:"XPT",number:"962",digits:0,currency:"Platinum",countries:["Zz10_platinum"]},{code:"XSU",number:"994",digits:0,currency:"Sucre",countries:['Sistema Unitario De Compensacion Regional De Pagos "Sucre"']},{code:"XTS",number:"963",digits:0,currency:"Codes specifically reserved for testing purposes",countries:["Zz06_testing_code"]},{code:"XUA",number:"965",digits:0,currency:"ADB Unit of Account",countries:["Member Countries of the African Development Bank Group"]},{code:"XXX",number:"999",digits:0,currency:"The codes assigned for transactions where no currency is involved",countries:["Zz07_no_currency"]},{code:"YER",number:"886",digits:2,currency:"Yemeni Rial",countries:["Yemen"]},{code:"ZAR",number:"710",digits:2,currency:"Rand",countries:["Lesotho","Namibia","South Africa"]},{code:"ZMW",number:"967",digits:2,currency:"Zambian Kwacha",countries:["Zambia"]},{code:"ZWG",number:"924",digits:2,currency:"Zimbabwe Gold",countries:["Zimbabwe"]}]),iy}var ay,y2;function EQ(){return y2||(y2=1,ay="2024-06-25"),ay}var A2;function kQ(){if(A2)return Ja;A2=1;var r=CQ(),e=xQ(),t=SQ(),n=EQ(),i=function(c){return c=c.toUpperCase(),r(t,function(d){return d.code===c})},a=function(c){return c=c.toLowerCase(),t.filter(function(d){return(d.countries.map(function(f){return f.toLowerCase()})||[]).indexOf(c)>-1})},s=function(c){return r(t,function(d){return d.number===String(c)})},o=function(){return t.map(function(c){return c.code})},l=function(){var c=t.map(function(d){return d.number});return c.filter(function(d){if(d)return d})},u=function(){var c=t.filter(function(d){return d.countries}).map(function(d){return d.countries});return e(Array.prototype.concat.apply([],c))};return Ja.code=i,Ja.country=a,Ja.number=s,Ja.codes=o,Ja.numbers=l,Ja.countries=u,Ja.publishDate=n,Ja.data=t,Ja}var b2=kQ();class FD{formatCurrencyForDisplay(e,t){const n={amount:t||0,currency:e,precision:this.getPrecisionForCurrency(e)};return wQ(n).toFormat(this.getSpecialFormat(e))}getPrecisionForCurrency(e){const t=e,n=b2.code(t);return n?n.digits:2}getSpecialFormat(e){const t=e;if(b2.code(t)?.code==="CLP")return"USD0,0"}}const w2=new FD;class ID{constructor(e,t,n,i){this.presentmentCurrency=void 0,this.presentmentCurrency=i,this.partnerCurrency=n,this.rateFrom=e,this.rateTo=t}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(e){return this.conversionRequired()?Math.ceil(this.subunits(this.units(e,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):e}units(e,t){return e/Math.pow(10,w2.getPrecisionForCurrency(t))}subunits(e,t){return e*Math.pow(10,w2.getPrecisionForCurrency(t))}}const TQ=async(r,e)=>{const t=await He.getShadowGraphqlClient().query({query:V3(e?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:r}});if(t.error)throw t.error;if(t.errors)throw t.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");if(!t.data.workflows||t.data.workflows.length!==r.length)throw new Error(`Unable to read workflows: ${t.errors??"Length mismatch in response"}`);const n=go(t.data.workflows);return n.forEach(i=>{i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),n},FQ=async(r,e)=>{const n=(await e).find(i=>i.id===r);if(!n)throw new Error(`Workflow not found: ${r}`);return n},Kb=async(r,e)=>{const t=r.map(o=>md.get({id:o,options:e})),n=r.filter((o,l)=>t[l]===void 0);if(n.length===0)return Promise.all(t);const i=TQ(n,e),a=n.map(o=>md.set({id:o,options:e},FQ(o,i))),s=t.filter(o=>o!==void 0);return await Promise.all(s.concat(a))},DD=async(r,e)=>(await Kb([r],e))[0],PD=async r=>{const e=await He.getShadowGraphqlClient().query({query:hT,variables:{ids:r},errorPolicy:"all",fetchPolicy:"no-cache"});return e.errors&&console.error(e.errors),e.data.integrationProducts||[]};class IQ{constructor(e){this.activeIntegration=void 0,this.updateTransactionState=async t=>{try{return He.getShadowGraphqlClient().mutate({...t,mutation:E3})}catch(n){throw console.error(n),new oo("Critical - Unable to synchronize workflow state with server.")}},this.options=e,this.options.applicationKey&&jO(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 43.1.1-alpha.0"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(e){Os.setHubUrl(e.hubUrl),Os.setServerUrl(e.serverUrl),Os.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&&qk(e.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&If.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getVersion(){return"43.1.1-alpha.0"}getAssetManager(){return Ln}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!GO())throw new Error("Application key required to use Flow Service.");return new TI}async getCurrencyContext(e){const n=(await this.getIntegration()).partner.currencyCode,a=await He.getShadowGraphqlClient().query({query:q3,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:n,to:e}}),{rateFrom:s,rateTo:o}=a.data.currencyConversion;return new ID(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=RD(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 He.getShadowGraphqlClient().query({query:Ov,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=He.getShadowGraphqlClient(),i=(await t.query({query:Ov,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;if(!i.id){const o=(await t.mutate({mutation:lV,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 If.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&&p0(s);const l=(await He.getShadowGraphqlClient().query({query:Ov,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 He.getShadowGraphqlClient().mutate({mutation:uV,variables:{emailAddress:e}}),await If.generateCode(e)}async verifyCode(e,t){const n=(await this.getIntegration()).partner.id||"",i=await If.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 He.getShadowGraphqlClient().mutate({mutation:cV,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),p0(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"),p0(""),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||gg(n.AccessToken);if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(e)||a){const s=await If.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 He.getShadowGraphqlClient().query({query:fV,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(e,t,n,i){const s=(await He.getShadowGraphqlClient().mutate({mutation:qU(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:e,initialMetadata:t?Object.entries(t).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,activationId:i},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 FE(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 y=Object.entries(localStorage).find(([C,k])=>C.startsWith("CognitoIdentityServiceProvider")&&C.endsWith("idToken"))?.[0]||"",A=localStorage.getItem(y);A&&!gg(A)&&(l.Authorization=`Bearer ${A}`)}const u={bundleOwnerId:o,...l,...i?.graphql?.additionalHeaders},c=await He.getShadowGraphqlClient().query({query:zU(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 d=c.data?.bundles[0],f=wr.getMap("bundlePartnerIds")||new Map;f.set(d.id,d.partner.id),wr.setMap("bundlePartnerIds",f);const h=new FE(this,d,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 BD(e),...i?.graphql?.additionalHeaders},l=(await He.getShadowGraphqlClient().mutate({mutation:WU(),variables:{id:e,template:t,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:n},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 He.getShadowGraphqlClient().query({query:i9(t??!1),variables:{...n,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const e=await He.getShadowGraphqlClient().query({query:$U,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 oo("No options provided!");const a=e.map((q,Y)=>({option:q,index:Y})),s=a.filter(q=>q.option.type==="transaction"),o=a.filter(q=>q.option.type==="integration"||q.option.type==="external"||q.option.type==="blank"),l=50,u=fA(s,l),c=fA(o,l);let d=0;const f=He.getShadowGraphqlClient(),h=async q=>{if(q.length===0)return[];const Y=q.map(oe=>oe.option.transactionId),J=await f.query({query:S3,variables:{ids:Y},errorPolicy:"all",fetchPolicy:"no-cache"}),se=J.data.transactions;if(d=d+se.length,i&&i(d,s.length),se.length!==q.length){const oe=J.errors?.[0]?.message||"Unknown error";throw new oo(`Not all transactions were found: ${oe}`)}return!this.activeIntegration&&se[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(se[0].integrationProduct.integration)),se.map((oe,he)=>({transaction:oe,workflowId:oe.workflowId,readOnly:q.find(ye=>ye.option.transactionId===oe.id)?.option.readOnly??!1,index:q[he].index}))},g=async q=>{if(q.length===0)return[];const Y=await f.mutate({mutation:x3,variables:{inputs:q.map(se=>({integrationProductId:se.option.type==="integration"?se.option.integrationProductId:void 0,externalIntegrationId:se.option.type==="external"?se.option.externalIntegrationId:void 0,externalProductId:se.option.type==="external"?se.option.externalProductId:void 0,workflowId:se.option.workflowId,designName:se.option.designName,claim:!0,quantity:se.option.quantity,recipient:se.option.recipient,parentTransactionId:se.option.parentTransactionId})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.getCreateTransactionContext(q,t)}),J=Y.data?.transactionCreateMany;if(!J||J.length===0){const se=Y.errors?.[0]?.message||"Unknown error";throw new oo(`Failed to create transactions: ${se}`)}return d=d+J.length,i&&i(d,s.length),J.map((se,oe)=>({transaction:se,workflowId:se.workflowId,readOnly:!1,index:q[oe].index}))},v=(await Promise.all([...u.map(h),...c.map(g)])).flat();let y=[...new Set(v.map(q=>q.transaction.integrationProductId))].filter(q=>!!q);y=y.filter(q=>!!q);let A=[...new Set(v.map(q=>q.workflowId))].filter(q=>!!q);A=A.filter(q=>!!q);const[C,k]=await Promise.all([(async()=>y.length>0?await PD(y):[])(),(async()=>A.length>0?await Kb(A,t):[])()]),F=new Map(C.map(q=>[q.id,q])),S=new Map(k.map(q=>[q.id,q])),R=v.map(async q=>{const{transaction:Y,workflowId:J,readOnly:se,index:oe}=q,he=J?S.get(J):void 0,ye=e[oe];if(Y.integrationProductId){const re=F.get(Y.integrationProductId);Y.integrationProduct=re,Y.product=re?.product,Y.integrationProduct||console.error("failed to find transaction's product")}const Ue=wr.getMap("transactionOwnerIds")||new Map;!Ue.get(Y.id)&&Y.transactionOwnerId&&(Ue.set(Y.id,Y.transactionOwnerId),wr.setMap("transactionOwnerIds",Ue));const Re=Ue.get(Y.id)||void 0,Oe=new dV({onMutate:()=>({context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}})}),ee={workflow:he,transaction:Y,singleVariantsRenderable:ye?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:se?async()=>{throw new nn("State mutation is forbidden in read only mode!")}:async re=>this.updateTransactionState({...re,context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}}),graphQlClient:()=>Oe,readOnly:se,isReloadedTransaction:ye.type==="transaction"};if(ye.type==="transaction"&&Y.workflowState){const re=JSON.parse(Y.workflowState);await sA(re),ee.reloadedState=re}else if(!se&&ye.workflowState){const re=JSON.parse(ye.workflowState);await sA(re),ee.reloadedState=re}return ee.delayWorkflowStateSync=!0,{experienceOptions:ee,index:oe,options:ye}}),j=(await Promise.all(R)).sort((q,Y)=>q.index-Y.index);let G=[],ie=[];for(const q of j){const{experienceOptions:Y,options:J}=q,se=new wI(this,Y);await se.getWorkflowManager().getInitializationPromise(),n&&n(),J.type!=="transaction"&&this.customer&&ie.push(se),G=[...G,se],se.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}if(ie.length>0){const q=this.customer.emailAddress,Y=ie.map(oe=>oe.getTransaction().id),se=(await f.mutate({mutation:_9,variables:{ids:Y,details:{emailAddress:q},type:"Owner"},errorPolicy:"all"})).data?.transactionsAddStakeholder;if(se&&se?.length>0){const oe=se[0].stakeholders?.find(he=>he.customer?.emailAddress===q);if(oe?.customer)for(const he of ie)he.assignCustomerInternal(oe.customer)}}return G}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 He.getShadowGraphqlClient().query({query:R3(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 pA(a[0])}async getIntegrationProductFromExternalIds(e,t,n){const s=(await He.getShadowGraphqlClient().query({query:O3(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 pA(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 He.getShadowGraphqlClient().query({query:D3,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 He.getShadowGraphqlClient().mutate({mutation:G3,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 RD=async(r,e)=>(await He.getShadowGraphqlClient().query({query:$3,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r},skipIntegrationCheck:!0},variables:{themeConfigurationId:e}})).data.currentIntegration,DQ=async r=>{const t=await He.getShadowGraphqlClient().query({query:I3,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(t.data.transactions.length!==0)return t.data.transactions[0]},PQ=async(r,e)=>(await He.getShadowGraphqlClient().query({query:z3,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:e}})).data?.marketplaceThemeInstallConfiguration,RQ=async r=>(await He.getShadowGraphqlClient().query({query:j3,errorPolicy:"all",variables:{id:r}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,OQ=async r=>(await He.getShadowGraphqlClient().query({query:H3,errorPolicy:"all",variables:{id:r}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function OD(){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&&!gg(i)&&(r.Authorization=`Bearer ${i}`)}return r}async function BD(r){const t=wr.getMap("bundleOwnerIds")?.get(r),n=await OD();return{bundleOwnerId:t,...n}}async function BQ(r){const t=wr.getMap("transactionOwnerIds")?.get(r),n=await OD();return{transactionOwnerId:t,...n}}const MQ=async r=>{const e=await BD(r),t=await He.getShadowGraphqlClient().mutate({mutation:h9,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}`)},_Q=async r=>{const e=await BQ(r),t=await He.getShadowGraphqlClient().mutate({mutation:p9,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 MD(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:Ip(r.x,e.width-l,0),y:Ip(r.y,e.height-u,0),zoom:o}}return{...r,x:Ip(r.x,-i,e.width),y:Ip(r.y,-a,e.height)}}function Ip(r,e,t){return Math.min(Math.max(r,e),t)}class _D{constructor(e,t){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=bI(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 Qd(o),u=this.frameData?this.frameData[s]:void 0;vd(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=Bu.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=Ug(this.imageData.svg,this.imageData.colors||{},!1);return Ng(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],d=n[o]-u*e[o];return{x:c,y:d,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 nn("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]=MD(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 nn("Frame data not set. This is a bug");if(!this.workflowManager)throw new nn("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(d=>d.id===l)?.regionIndex??u;c>=e.length&&(c=u);try{o(new On([new dL(l,t,e[c]),new hL(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]={...w1(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 NQ{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(e,t,n,i,a,s,o,l,u,c,d,f,h,g,v,y,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()}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 ND=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(ND||{}),LD=(r=>(r.Original="original",r.BackgroundRemoved="backgroundRemoved",r.Optimized="optimized",r))(LD||{});class UD extends Ui{constructor(e,t,n){super(e,t,n);const i=t.data;this.frameService=new _D(i.forceImageCover,i.initialZoomLevel),this.frameService.connectWorkflowManager(e,t.stepName)}selectVariant(e){const t=this.manager.getRegionElements(this.step.stepName);return so.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 so.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(Rg.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 Ln.removeBackgroundFromAsset(t);e&&await so.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 Ln.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 Ln.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 Ln.getLocalOrFromServer(e)}async getVectorizedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey;if(e)return Ln.getLocalOrFromServer(e)}async getEnhancedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.enhancedAssetKey;if(e)return Ln.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 so.changeColors(this.step,this.manager,e)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await ft.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?so.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const e=this.getImageData();return e?.svg?(await Pa(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}=oT(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 so.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 Ln.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 LQ=Ee`
2891
2891
  query GetLoggedInCustomer($email: String!) {
2892
2892
  customer(emailAddress: $email) {
2893
2893
  id
@@ -3099,4 +3099,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
3099
3099
  }
3100
3100
  }
3101
3101
  `,mY=async r=>(await He.getShadowGraphqlClient().query({query:gY,variables:{ids:r}})).data.integrationProducts;exports.AddonHandle=Rg;exports.AddressValidationJobStatus=$D;exports.AddressValidationResultConfirmationLevel=zD;exports.AddressValidationStatus=Pg;exports.ArrayInput=oV;exports.AspectType=Hn;exports.AssetNotFoundError=xo;exports.AssetType=dd;exports.BringForwardCommand=yL;exports.BringToBackCommand=vL;exports.BringToFrontCommand=mL;exports.BundleDesignCreationCartAddMode=Ok;exports.CanvasCommand=Fn;exports.CollectionProduct=Vf;exports.ColorOptionGlobalPropertyHandle=dA;exports.CommandContext=VF;exports.ConversionDataType=Yf;exports.CreateElementCommand=ii;exports.CreateLayoutCommand=S1;exports.CurrencyContext=ID;exports.CurrencyService=FD;exports.DeleteElementCommand=Rl;exports.DigitalContentStepHandle=gI;exports.FileUploadGlobalPropertyHandle=CI;exports.FlowExecutionNodeResult=zf;exports.FlowExecutionResult=FI;exports.FlowService=TI;exports.FontAlignmentCommand=qF;exports.FontColorCommand=jF;exports.FontSizeCommand=GF;exports.FontSourceCommand=oA;exports.FrameService=_D;exports.FrameStep=ND;exports.FrameStepHandle=UD;exports.GlobalPropertyHandle=Jg;exports.GroupCommand=On;exports.IllustrationStepHandle=oI;exports.ImageState=LD;exports.InformationMessageType=Yd;exports.InformationStepHandle=pI;exports.IntegrationProduct=pA;exports.IntegrationType=Mk;exports.LayoutElementFactory=lL;exports.LayoutElementType=er;exports.LayoutNotFoundError=Ai;exports.LayoutRenderingPurpose=Ju;exports.MaterialStepHandle=lI;exports.MisconfigurationError=ss;exports.MockWorkflowManager=NQ;exports.ModelStepHandle=uI;exports.ModuleStepHandle=mI;exports.MoveCommand=uL;exports.ObjectInput=_1;exports.ObjectInputType=II;exports.OptionGlobalPropertyHandle=O1;exports.OptionNotFoundError=hd;exports.ParseError=yl;exports.PictureStepHandle=cI;exports.ProductCameraRig=_k;exports.ProductCollection=B1;exports.ProductCollectionProductSortKey=kI;exports.ProductStepHandle=vI;exports.ProductWorkflow=Hu;exports.PromiseQueue=Gg;exports.QuestionStepHandle=fI;exports.QueueablePromise=jg;exports.ResizeCommand=fL;exports.ResourceNotFoundError=Ku;exports.RotateCommand=cL;exports.ScaleAxis=gi;exports.SendBackwardsCommand=AL;exports.ShapeStepHandle=dI;exports.ShareActionType=Bk;exports.SpiffCommerceClient=IQ;exports.StakeholderType=jA;exports.StepAspectType=Rk;exports.StepHandle=Ui;exports.StepType=Xe;exports.TextAlgorithm=Tl;exports.TextChangeCommand=WF;exports.TextGlobalPropertyHandle=xI;exports.TextInput=sV;exports.TextStepHandle=hI;exports.UnhandledBehaviorError=nn;exports.UnitOfMeasurement=Nk;exports.UpdateImageSourceCommand=pL;exports.Variant=Fa;exports.WorkflowExperienceEventType=mg;exports.WorkflowExperienceImpl=wI;exports.__values=JD;exports.amtChannelsForAspect=SI;exports.assetConfigurationDeleteMutation=Y3;exports.assetConfigurationUpdateMutation=Q3;exports.assetConfigurationsQuery=W3;exports.assetService=Ln;exports.browserColorToHex=nT;exports.bundleEmailMutation=g9;exports.cmPerPixel=V_;exports.currentDirection=N_;exports.dataUrlFromExternalUrl=RO;exports.deleteBundle=MQ;exports.designService=qp;exports.determineCorrectFontSizeAndLines=Zf;exports.digitalContentStepService=k1;exports.domParser=us;exports.duplicateBundle=QQ;exports.duplicateTransaction=YQ;exports.fetchAsString=ra;exports.findAngle=D_;exports.findElement=Un;exports.findPmsColors=JB;exports.frameDataCache=Bu;exports.frameStepService=so;exports.fromHex=NI;exports.fromUtf8=El;exports.generate=Ar;exports.generateCommands=iI;exports.generateSVGWithUnknownColors=Pa;exports.generateStateFromDesignInputSteps=MU;exports.getAddressValidationJobs=cY;exports.getAssetsForProductImagesQuery=X3;exports.getAttributesFromArrayBuffer=_d;exports.getAxisAlignedBoundingBox=I_;exports.getBoundedOffsets=MD;exports.getBundleIdForTransaction=_Q;exports.getBundleThemeConfiguration=RQ;exports.getCustomer=XQ;exports.getCustomerBundles=JQ;exports.getElementVertices=L_;exports.getFrameData=Qd;exports.getGlobalPropertyStateForBundle=UU;exports.getIntegration=RD;exports.getIntegrationProducts=mY;exports.getNEPoint=M_;exports.getNWPoint=B_;exports.getOrderedTransactions=eY;exports.getOverrideThemeConfiguration=PQ;exports.getPointOfRotation=O_;exports.getProductCollections=eV;exports.getSEPoint=__;exports.getSvgElement=Qg;exports.getTemplateBundles=rY;exports.getTemplateTransactions=tY;exports.getTransaction=DQ;exports.getTransactionThemeConfiguration=OQ;exports.getTransactionsForBundle=KQ;exports.getTransformedAssetURL=Vg;exports.getTrueCoordinates=R_;exports.getUnorderedTransactions=ZQ;exports.getValidationJobsForWorkflowExperiences=uY;exports.getWorkflow=DD;exports.getWorkflows=Kb;exports.graphQlManager=He;exports.illustrationStepService=Kf;exports.isCloseToValue=P_;exports.loadFont=Pl;exports.matchHexToPms=QB;exports.materialStepService=T1;exports.mergeColorClasses=oT;exports.metafieldManager=vg;exports.mmPerPixel=U_;exports.modelStepService=F1;exports.modifySVGColors=Ug;exports.moduleStepService=I1;exports.nameBundle=qQ;exports.nameTransaction=WQ;exports.optionService=ft;exports.outlineFontsInSvg=v7;exports.overrideWorkflowExperienceRecipientAddress=hY;exports.patternImageDataCache=Ps;exports.persistenceService=wr;exports.pictureStepService=D1;exports.pmsToRgb=WB;exports.promiseCache=md;exports.questionStepService=P1;exports.registerFetchImplementation=TO;exports.registerWindowImplementation=kO;exports.rehydrateSerializedLayout=sA;exports.rgbToPms=rT;exports.rotateAroundPoint=Lf;exports.sanitizeSvgTree=Lg;exports.setBearerAuthenticationToken=qk;exports.setCanvasModule=qA;exports.shapeStepService=Mu;exports.shortenUrl=ZF;exports.skipWorkflowExperienceRecipientAddress=pY;exports.spiffCoreConfiguration=Os;exports.stepAspectValuesToDesignInputSteps=BU;exports.svgColorValueToDefinition=$y;exports.svgStringDimensions=x1;exports.svgToDataUrl=Ng;exports.textStepService=li;exports.toHex=yo;exports.toUtf8=em;exports.toast=tI;exports.validateWorkflowExperienceRecipient=fY;exports.validateWorkflowExperienceRecipients=dY;exports.xmlSerializer=Do;
3102
- //# sourceMappingURL=index-C4tbQZou.cjs.map
3102
+ //# sourceMappingURL=index-C2QUoMnb.cjs.map