@cline/core 0.0.95 → 0.2.0-nightly.1793312794

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.
Files changed (175) hide show
  1. package/dist/ClineCore.d.ts +6 -1
  2. package/dist/account/rpc.d.ts +3 -1
  3. package/dist/account/types.d.ts +2 -0
  4. package/dist/artifacts/cloud/fetch.d.ts +8 -0
  5. package/dist/artifacts/cloud/publish.d.ts +6 -0
  6. package/dist/artifacts/publish.d.ts +30 -0
  7. package/dist/cline-core/runtime-services.d.ts +4 -2
  8. package/dist/cloud/computer-use-prompt.d.ts +9 -0
  9. package/dist/cloud/controller.d.ts +26 -4
  10. package/dist/cloud/hub-client.d.ts +53 -0
  11. package/dist/cloud/hub-protocol.d.ts +32 -0
  12. package/dist/cloud/index.d.ts +5 -0
  13. package/dist/cloud/index.js +34 -17
  14. package/dist/cloud/types.d.ts +4 -1
  15. package/dist/extensions/context/compaction-shared.d.ts +1 -0
  16. package/dist/extensions/context/compaction.d.ts +7 -0
  17. package/dist/extensions/context/summarize-conversation.d.ts +7 -0
  18. package/dist/extensions/context/summary-generation.d.ts +14 -0
  19. package/dist/extensions/mcp/apps.d.ts +16 -0
  20. package/dist/extensions/mcp/client.d.ts +1 -0
  21. package/dist/extensions/mcp/index.d.ts +5 -1
  22. package/dist/extensions/mcp/manager.d.ts +2 -1
  23. package/dist/extensions/mcp/session-apps.d.ts +28 -0
  24. package/dist/extensions/mcp/types.d.ts +22 -0
  25. package/dist/extensions/plugin/plugin-command-origin.d.ts +8 -0
  26. package/dist/extensions/plugin/plugin-registry.d.ts +1 -0
  27. package/dist/extensions/plugin/plugin-runtime.d.ts +7 -0
  28. package/dist/hub/client/index.d.ts +6 -0
  29. package/dist/hub/client/managed-hub-build-watcher.d.ts +2 -0
  30. package/dist/hub/client/plugin-commands.d.ts +4 -0
  31. package/dist/hub/client/session-client.d.ts +2 -0
  32. package/dist/hub/daemon/entry.js +248 -229
  33. package/dist/hub/daemon/index.d.ts +2 -0
  34. package/dist/hub/index.d.ts +1 -0
  35. package/dist/hub/index.js +238 -219
  36. package/dist/hub/runtime-host/hub-runtime-host.d.ts +6 -0
  37. package/dist/hub/server/cloud-session-service.d.ts +52 -0
  38. package/dist/hub/server/handlers/capability-handlers.d.ts +18 -1
  39. package/dist/hub/server/handlers/context.d.ts +13 -2
  40. package/dist/hub/server/handlers/mcp-apps-handlers.d.ts +5 -0
  41. package/dist/hub/server/handlers/session-handlers.d.ts +4 -0
  42. package/dist/hub/server/hub-server-options.d.ts +3 -0
  43. package/dist/hub/server/hub-server-transport.d.ts +2 -0
  44. package/dist/index.d.ts +10 -5
  45. package/dist/index.js +284 -258
  46. package/dist/plugin-runtime/node_modules/@cline/agents/dist/index.js +76 -0
  47. package/dist/plugin-runtime/node_modules/@cline/agents/package.json +1 -0
  48. package/dist/plugin-runtime/node_modules/@cline/core/dist/ai-sdk-bdvd54cj.js +1 -0
  49. package/dist/plugin-runtime/node_modules/@cline/core/dist/anthropic-d88t4w67.js +1 -0
  50. package/dist/plugin-runtime/node_modules/@cline/core/dist/bedrock-4rh6dw0e.js +1 -0
  51. package/dist/plugin-runtime/node_modules/@cline/core/dist/cline-dex049wz.js +1 -0
  52. package/dist/plugin-runtime/node_modules/@cline/core/dist/cloud/index.js +38 -0
  53. package/dist/plugin-runtime/node_modules/@cline/core/dist/community-adrseffv.js +1 -0
  54. package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-embedding-model-strategy-SAVQFBF4-vf44v1q1.js +1 -0
  55. package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-language-model-strategy-BPQO66W7-np6pavev.js +1 -0
  56. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-1xg0n8py.js +1 -0
  57. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-2h2811k3.js +1 -0
  58. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-918h9zb6.js +2 -0
  59. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-9g9qz8kw.js +2 -0
  60. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-8p52y0t4.js +1 -0
  61. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-cr4wnstr.js +1 -0
  62. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-aa72jh2v.js +1 -0
  63. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-k2y10eep.js +1 -0
  64. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-1hvm2h6v.js +1 -0
  65. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-7nqbajdc.js +1 -0
  66. package/dist/plugin-runtime/node_modules/@cline/core/dist/google-nqn5r579.js +1 -0
  67. package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/daemon/entry.js +1166 -0
  68. package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/index.js +1153 -0
  69. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-0ahmqye5.js +2 -0
  70. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-1jwj53tz.js +2 -0
  71. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-3qy7846d.js +14 -0
  72. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-418gvd4a.js +2 -0
  73. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4etvmc8g.js +2 -0
  74. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4pm9q9we.js +1 -0
  75. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4tgv599k.js +2 -0
  76. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-5hwscy9s.js +15 -0
  77. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-6dpcn5cw.js +9 -0
  78. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-7ycwqbm0.js +1 -0
  79. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-8qjtgvqw.js +9 -0
  80. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-8zb5grad.js +1210 -0
  81. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-94jdgxt6.js +2 -0
  82. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-9g67p34k.js +2 -0
  83. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-a9d2sjh0.js +85 -0
  84. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-agemt17a.js +3 -0
  85. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bhf7enwn.js +1 -0
  86. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bnwxdgvg.js +1 -0
  87. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-brjxtvsh.js +4 -0
  88. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bvb7f701.js +1 -0
  89. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bwet95hr.js +2 -0
  90. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-cadyf2yp.js +14 -0
  91. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-cxfnnrmh.js +9 -0
  92. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-cyyvppz9.js +6 -0
  93. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-d4pbedxj.js +137 -0
  94. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ddwn220p.js +12 -0
  95. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-edf1hmcw.js +62 -0
  96. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ejyd73x5.js +1 -0
  97. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-f25bf131.js +4 -0
  98. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-f4rfmj6q.js +3 -0
  99. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-fet3kwk6.js +1 -0
  100. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ffna8yzn.js +121 -0
  101. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-g2y6ptdc.js +213 -0
  102. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ge184xvn.js +6 -0
  103. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-gevnedsc.js +13 -0
  104. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-hkmarmve.js +190 -0
  105. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-kqacxn3s.js +39 -0
  106. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m3gtj35r.js +14 -0
  107. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-neczvge6.js +21 -0
  108. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-p5k5hnam.js +75 -0
  109. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-sdvqs19c.js +20 -0
  110. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-t75m2pgm.js +146 -0
  111. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v4-qqb2kabr.js +1 -0
  112. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v6mehmme.js +12 -0
  113. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v80fh3x3.js +16 -0
  114. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-vd605jwp.js +2 -0
  115. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-vryppqt1.js +1 -0
  116. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-w55v4n1n.js +2 -0
  117. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-w9n2kgjk.js +140 -0
  118. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-yjbp9r76.js +142 -0
  119. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ztb3cjfh.js +3 -0
  120. package/dist/plugin-runtime/node_modules/@cline/core/dist/index.js +1 -0
  121. package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-static-kj4rdeey.js +473 -0
  122. package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-y9tt7gmq.js +1 -0
  123. package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-stream-telemetry-bg81k3qh.js +1 -0
  124. package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-telemetry-tkbfbx5w.js +1 -0
  125. package/dist/plugin-runtime/node_modules/@cline/core/dist/mistral-mkw95amh.js +1 -0
  126. package/dist/plugin-runtime/node_modules/@cline/core/dist/multipart-parser-9z19cm6q.js +2 -0
  127. package/dist/plugin-runtime/node_modules/@cline/core/dist/ollama-sjp09b7p.js +1 -0
  128. package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-1eyn4hw0.js +1 -0
  129. package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-compatible-f99c7syq.js +1 -0
  130. package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-embedding-model-strategy-GT27AFII-19936r1a.js +1 -0
  131. package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-language-model-strategy-YEQPUCOT-eavx3zc3.js +1 -0
  132. package/dist/plugin-runtime/node_modules/@cline/core/dist/services/feature-flags/posthog.js +2 -0
  133. package/dist/plugin-runtime/node_modules/@cline/core/dist/services/telemetry/index.js +1 -0
  134. package/dist/plugin-runtime/node_modules/@cline/core/dist/token-04d0mwe8.js +1 -0
  135. package/dist/plugin-runtime/node_modules/@cline/core/dist/token-util-mt7pvm61.js +1 -0
  136. package/dist/plugin-runtime/node_modules/@cline/core/dist/vertex-6armtc3s.js +1 -0
  137. package/dist/plugin-runtime/node_modules/@cline/core/package.json +1 -0
  138. package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.browser.js +16 -0
  139. package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.js +1 -0
  140. package/dist/plugin-runtime/node_modules/@cline/llms/package.json +1 -0
  141. package/dist/plugin-runtime/node_modules/@cline/sdk/dist/index.js +1 -0
  142. package/dist/plugin-runtime/node_modules/@cline/sdk/package.json +1 -0
  143. package/dist/plugin-runtime/node_modules/@cline/shared/dist/automation/index.js +57 -0
  144. package/dist/plugin-runtime/node_modules/@cline/shared/dist/db/index.js +127 -0
  145. package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.browser.js +110 -0
  146. package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.js +1 -0
  147. package/dist/plugin-runtime/node_modules/@cline/shared/dist/node.js +1 -0
  148. package/dist/plugin-runtime/node_modules/@cline/shared/dist/remote-config/index.js +68 -0
  149. package/dist/plugin-runtime/node_modules/@cline/shared/dist/storage/index.js +1 -0
  150. package/dist/plugin-runtime/node_modules/@cline/shared/dist/types/index.js +1 -0
  151. package/dist/plugin-runtime/node_modules/@cline/shared/package.json +1 -0
  152. package/dist/plugin-runtime/package.json +1 -0
  153. package/dist/{extensions → plugin-runtime}/plugin-sandbox-bootstrap.js +129 -129
  154. package/dist/remote/remote-environments.d.ts +1 -0
  155. package/dist/runtime/config/agent-runtime-config-builder.d.ts +2 -0
  156. package/dist/runtime/host/local-runtime-host.d.ts +10 -0
  157. package/dist/runtime/host/runtime-host.d.ts +6 -0
  158. package/dist/runtime/orchestration/runtime-oauth-token-manager.d.ts +3 -0
  159. package/dist/runtime/orchestration/session-runtime-orchestrator.d.ts +10 -1
  160. package/dist/runtime/orchestration/session-runtime.d.ts +2 -0
  161. package/dist/runtime/tools/subprocess-sandbox.d.ts +22 -0
  162. package/dist/services/cloud-handoff/git-preparation.d.ts +22 -0
  163. package/dist/services/global-settings.d.ts +6 -0
  164. package/dist/services/llms/cline-recommended-models.d.ts +2 -0
  165. package/dist/services/local-runtime-bootstrap.d.ts +1 -0
  166. package/dist/services/plugin-command-api.d.ts +47 -0
  167. package/dist/services/plugin-commands.d.ts +25 -27
  168. package/dist/services/skills-cli.d.ts +2 -0
  169. package/dist/services/telemetry/core-events.d.ts +26 -0
  170. package/dist/services/telemetry/index.js +1 -1
  171. package/dist/services/telemetry/run-health.d.ts +40 -0
  172. package/dist/services/telemetry/stall-signals.d.ts +12 -0
  173. package/dist/types/config.d.ts +1 -0
  174. package/dist/types/session.d.ts +7 -0
  175. package/package.json +6 -5
@@ -0,0 +1,75 @@
1
+ import{wy,Ty,Hm,Oi}from"./index-ztb3cjfh.js";import{Ym,Ns,F,pt,b,H,Q,I,it,j,At,Kt,yi,Pi,Di,Ee,fe,Ae,C,kl,Ls,dt,so,Pe,ut,nn,u,Ur,l,De,yt,T,O,M,ee,oe,E,te,jw,Ye}from"./index-w9n2kgjk.js";import{v,i,c,e,n,r,L,m,o,t,p,d,s,a,Fe}from"./index-edf1hmcw.js";var Jt=i(function(ox){var la;(function(f){f.HEADER="header",f.QUERY="query"})(la||(la={}));var fa;(function(f){f.HEADER="header",f.QUERY="query"})(fa||(fa={}));var ha;(function(f){f.HTTP="http",f.HTTPS="https"})(ha||(ha={}));var On;(function(f){f.MD5="md5",f.CRC32="crc32",f.CRC32C="crc32c",f.SHA1="sha1",f.SHA256="sha256"})(On||(On={}));var ex=(f)=>{let h=[];if(f.sha256!==void 0)h.push({algorithmId:()=>On.SHA256,checksumConstructor:()=>f.sha256});if(f.md5!=null)h.push({algorithmId:()=>On.MD5,checksumConstructor:()=>f.md5});return{addChecksumAlgorithm(g){h.push(g)},checksumAlgorithms(){return h}}},tx=(f)=>{let h={};return f.checksumAlgorithms().forEach((g)=>{h[g.algorithmId()]=g.checksumConstructor()}),h},rx=(f)=>ex(f),nx=(f)=>tx(f),pa;(function(f){f[f.HEADER=0]="HEADER",f[f.TRAILER=1]="TRAILER"})(pa||(pa={}));var sx="__smithy_context",ma;(function(f){f.PROFILE="profile",f.SSO_SESSION="sso-session",f.SERVICES="services"})(ma||(ma={}));var ga;(function(f){f.HTTP_0_9="http/0.9",f.HTTP_1_0="http/1.0",f.TDS_8_0="tds/8.0"})(ga||(ga={}));ox.AlgorithmId=On;ox.EndpointURLScheme=ha;ox.FieldPosition=pa;ox.HttpApiKeyAuthLocation=fa;ox.HttpAuthLocation=la;ox.IniSectionType=ma;ox.RequestHandlerProtocol=ga;ox.SMITHY_CONTEXT_KEY=sx;ox.getDefaultClientConfiguration=rx;ox.resolveDefaultRuntimeConfig=nx});var at=i(function(xx){var{SMITHY_CONTEXT_KEY:cl}=Jt(),gx=(f)=>f[cl]||(f[cl]={});function ul(f,h){return Object.prototype.hasOwnProperty.call(f,h)}class $s{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(f){this.method=f.method||"GET",this.hostname=f.hostname||"localhost",this.port=f.port,this.query=f.query||{},this.headers=f.headers||{},this.body=f.body,this.protocol=f.protocol?f.protocol.slice(-1)!==":"?`${f.protocol}:`:f.protocol:"https:",this.path=f.path?f.path.charAt(0)!=="/"?`/${f.path}`:f.path:"/",this.username=f.username,this.password=f.password,this.fragment=f.fragment}static clone(f){let h=new $s({...f,headers:{...f.headers}});if(h.query)h.query=yx(h.query);return h}static isInstance(f){if(!f)return!1;let h=f;return"method"in h&&"protocol"in h&&"hostname"in h&&"path"in h&&typeof h.query==="object"&&typeof h.headers==="object"}clone(){return $s.clone(this)}}function yx(f){return Object.keys(f).reduce((h,g)=>{let y=f[g];return{...h,[g]:Array.isArray(y)?[...y]:y}},{})}class dl{statusCode;reason;headers;body;constructor(f){this.statusCode=f.statusCode,this.reason=f.reason,this.headers=f.headers||{},this.body=f.body}static isInstance(f){if(!f)return!1;let h=f;return typeof h.statusCode==="number"&&typeof h.headers==="object"}}var Sx=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),ll=(f,h=!1)=>{if(!h)return Sx.test(f);let g=f.split(".");for(let y of g)if(!ll(y))return!1;return!0};function wx(f){return/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(f)}var Ex=(f)=>{if(typeof f==="function")return f;let h=Promise.resolve(f);return()=>h};function fl(f){let h={};if(f=f.replace(/^\?/,""),f)for(let g of f.split("&")){let[y,w=null]=g.split("=");if(y=decodeURIComponent(y),w)w=decodeURIComponent(w);if(!(y in h))h[y]=w;else if(Array.isArray(h[y]))h[y].push(w);else h[y]=[h[y],w]}return h}var Bs=(f)=>{if(typeof f==="string")return Bs(new URL(f));let{hostname:h,pathname:g,port:y,protocol:w,search:S}=f,x;if(S)x=fl(S);return{hostname:h,port:y?parseInt(y):void 0,protocol:w,path:g,query:x}},bx=(f)=>{if(typeof f==="object"){if("url"in f){let h=Bs(f.url);if(f.headers){h.headers={};for(let g in f.headers){if(!ul(f.headers,g))continue;h.headers[g.toLowerCase()]=f.headers[g].join(", ")}}return h}return f}return Bs(f)};xx.HttpRequest=$s;xx.HttpResponse=dl;xx.getSmithyContext=gx;xx.hasOwn=ul;xx.isValidHostLabel=ll;xx.isValidHostname=wx;xx.normalizeProvider=Ex;xx.parseQueryString=fl;xx.parseUrl=Bs;xx.toEndpointV1=bx});var Rt=i(function(Wx){var{getSmithyContext:hl,HttpResponse:Px,toEndpointV1:Mx}=at(),zs=(f)=>{if(typeof f==="function")return f();return f},wa=(f,h,g,y,w)=>({name:h,namespace:f,traits:g,input:y,output:w}),Dx=(f)=>(h,g)=>async(y)=>{let{response:w}=await h(y),{operationSchema:S}=hl(g),[,x,_,A,P,D]=S??[];try{let U=await f.protocol.deserializeResponse(wa(x,_,A,P,D),{...f,...g},w);return{response:w,output:U}}catch(U){if(Object.defineProperty(U,"$response",{value:w,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in U)){try{U.message+=`
2
+ Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(z){if(!g.logger||g.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else g.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof U.$responseBodyText<"u"){if(U.$response)U.$response.body=U.$responseBodyText}try{if(Px.isInstance(w)){let{headers:z={},statusCode:k}=w,R=Object.entries(z);U.$metadata={httpStatusCode:k,requestId:ya(/^x-[\w-]+-request-?id$/,R),extendedRequestId:ya(/^x-[\w-]+-id-2$/,R),cfId:ya(/^x-[\w-]+-cf-id$/,R)}}}catch(z){}}throw U}},ya=(f,h)=>(h.find(([g])=>g.match(f))||[void 0,void 0])[1],Ux=(f)=>(h,g)=>async(y)=>{let{operationSchema:w}=hl(g),[,S,x,_,A,P]=w??[],D=g.endpointV2?async()=>Mx(g.endpointV2):f.endpoint,U=await f.protocol.serializeRequest(wa(S,x,_,A,P),y.input,{...f,...g,endpoint:D});return h({...y,request:U})},pl={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},ml={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function Fx(f){return{applyToStack:(h)=>{h.add(Ux(f),ml),h.add(Dx(f),pl),f.protocol.setSerdeContext(f)}}}class rt{name;namespace;traits;static assign(f,h){return Object.assign(f,h)}static[Symbol.hasInstance](f){let h=this.prototype.isPrototypeOf(f);if(!h&&typeof f==="object"&&f!==null)return f.symbol===this.symbol;return h}getName(){return this.namespace+"#"+this.name}}class Vs extends rt{static symbol=Symbol.for("@smithy/lis");valueSchema;symbol=Vs.symbol}var $x=(f,h,g,y)=>rt.assign(new Vs,{name:h,namespace:f,traits:g,valueSchema:y});class Ws extends rt{static symbol=Symbol.for("@smithy/map");keySchema;valueSchema;symbol=Ws.symbol}var Bx=(f,h,g,y,w)=>rt.assign(new Ws,{name:h,namespace:f,traits:g,keySchema:y,valueSchema:w});class Gs extends rt{static symbol=Symbol.for("@smithy/ope");input;output;symbol=Gs.symbol}var Lx=(f,h,g,y,w)=>rt.assign(new Gs,{name:h,namespace:f,traits:g,input:y,output:w});class Un extends rt{static symbol=Symbol.for("@smithy/str");memberNames;memberList;symbol=Un.symbol}var zx=(f,h,g,y,w)=>rt.assign(new Un,{name:h,namespace:f,traits:g,memberNames:y,memberList:w});class Ks extends Un{static symbol=Symbol.for("@smithy/err");ctor;symbol=Ks.symbol}var Hx=(f,h,g,y,w,S)=>rt.assign(new Ks,{name:h,namespace:f,traits:g,memberNames:y,memberList:w,ctor:null}),Hs=[];function Dn(f){if(typeof f==="object")return f;if(f=f|0,Hs[f])return Hs[f];let h={},g=0;for(let y of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])if((f>>g++&1)===1)h[y]=1;return Hs[f]=h}var Pn={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},qs=[],js={};class $t{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=$t.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(f,h){this.ref=f,this.memberName=h;let g=[],y=f,w=f;this._isMemberSchema=!1;while(Sa(y))g.push(y[1]),y=y[0],w=zs(y),this._isMemberSchema=!0;if(g.length>0){this.memberTraits={};for(let S=g.length-1;S>=0;--S){let x=g[S];Object.assign(this.memberTraits,Dn(x))}}else this.memberTraits=0;if(w instanceof $t){let S=this.memberTraits;Object.assign(this,w),this.memberTraits=Object.assign({},S,w.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=h??w.memberName;return}if(this.schema=zs(w),gl(this.schema))this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3];else this.name=this.memberName??String(w),this.traits=0;if(this._isMemberSchema&&!h)throw Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](f){let h=this.prototype.isPrototypeOf(f);if(!h&&typeof f==="object"&&f!==null)return f.symbol===this.symbol;return h}static of(f){let h=typeof f==="function"||typeof f==="object"&&f!==null;if(typeof f==="number"){if(qs[f])return qs[f]}else if(typeof f==="string"){if(js[f])return js[f]}else if(h){if(f[Pn.ns])return f[Pn.ns]}let g=zs(f);if(g instanceof $t)return g;if(Sa(g)){let[w,S]=g;if(w instanceof $t)return Object.assign(w.getMergedTraits(),Dn(S)),w;throw Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(f,null,2)}.`)}let y=new $t(g);if(h)return f[Pn.ns]=y;if(typeof g==="string")return js[g]=y;if(typeof g==="number")return qs[g]=y;return y}getSchema(){let f=this.schema;if(Array.isArray(f)&&f[0]===0)return f[4];return f}getName(f=!1){let{name:h}=this;return!f&&h&&h.includes("#")?h.split("#")[1]:h||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){let f=this.getSchema();return typeof f==="number"?f>=64&&f<128:f[0]===1}isMapSchema(){let f=this.getSchema();return typeof f==="number"?f>=128&&f<=255:f[0]===2}isStructSchema(){let f=this.getSchema();if(typeof f!=="object")return!1;let h=f[0];return h===3||h===-3||h===4}isUnionSchema(){let f=this.getSchema();if(typeof f!=="object")return!1;return f[0]===4}isBlobSchema(){let f=this.getSchema();return f===21||f===42}isTimestampSchema(){let f=this.getSchema();return typeof f==="number"&&f>=4&&f<=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(){let{streaming:f}=this.getMergedTraits();return!!f||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return Dn(this.memberTraits)}getOwnTraits(){return Dn(this.traits)}getKeySchema(){let[f,h]=[this.isDocumentSchema(),this.isMapSchema()];if(!f&&!h)throw Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);let g=this.getSchema(),y=f?15:g[4]??0;return Mn([y,0],"key")}getValueSchema(){let f=this.getSchema(),[h,g,y]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],w=typeof f==="number"?63&f:f&&typeof f==="object"&&(g||y)?f[3+f[0]]:h?15:void 0;if(w!=null)return Mn([w,0],g?"value":"member");throw Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(f){let h=this.getSchema();if(this.isStructSchema()&&h[4].includes(f)){let g=h[4].indexOf(f),y=h[5][g];return Mn(Sa(y)?y:[y,0],f)}if(this.isDocumentSchema())return Mn([15,0],f);throw Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${f}.`)}getMemberSchemas(){let f={};try{for(let[h,g]of this.structIterator())f[h]=g}catch(h){}return f}getEventStreamMember(){if(this.isStructSchema()){for(let[f,h]of this.structIterator())if(h.isStreaming()&&h.isStructSchema())return f}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw Error("@smithy/core/schema - cannot iterate non-struct schema.");let f=this.getSchema(),h=f[4].length,g=f[Pn.it];if(g&&h===g.length){yield*g;return}g=Array(h);for(let y=0;y<h;++y){let w=f[4][y],S=Mn([f[5][y],0],w);yield g[y]=[w,S]}f[Pn.it]=g}}function Mn(f,h){if(f instanceof $t)return Object.assign(f,{memberName:h,_isMemberSchema:!0});return new $t(f,h)}var Sa=(f)=>Array.isArray(f)&&f.length===2,gl=(f)=>Array.isArray(f)&&f.length>=5;class Fn extends rt{static symbol=Symbol.for("@smithy/sim");schemaRef;symbol=Fn.symbol}var qx=(f,h,g,y)=>rt.assign(new Fn,{name:h,namespace:f,traits:y,schemaRef:g}),jx=(f,h,g,y)=>rt.assign(new Fn,{name:h,namespace:f,traits:g,schemaRef:y}),Vx={BLOB:21,STREAMING_BLOB:42,BOOLEAN:2,STRING:0,NUMERIC:1,BIG_INTEGER:17,BIG_DECIMAL:19,DOCUMENT:15,TIMESTAMP_DEFAULT:4,TIMESTAMP_DATE_TIME:5,TIMESTAMP_HTTP_DATE:6,TIMESTAMP_EPOCH_SECONDS:7,LIST_MODIFIER:64,MAP_MODIFIER:128};class Ft{namespace;schemas;exceptions;static registries=new Map;constructor(f,h=new Map,g=new Map){if(this.namespace=f,this.schemas=h,this.exceptions=g,!Ft.registries.has(f))Ft.registries.set(f,this)}static for(f){return Ft.registries.get(f)??new Ft(f)}copyFrom(f){let{schemas:h,exceptions:g}=this;for(let[y,w]of f.schemas)if(!h.has(y))h.set(y,w);for(let[y,w]of f.exceptions)if(!g.has(y))g.set(y,w)}register(f,h){let g=this.normalizeShapeId(f);for(let y of[this,Ft.for(g.split("#")[0])])if(!y.schemas.has(g))y.schemas.set(g,h)}getSchema(f){let h=this.normalizeShapeId(f);if(!this.schemas.has(h)){if(!f.includes("#")){let g="#"+f,y=[];for(let[w,S]of this.schemas.entries())if(w.endsWith(g))y.push(S);if(y.length===1)return y[0]}throw Error(`@smithy/core/schema - schema not found for ${h}`)}return this.schemas.get(h)}registerError(f,h){let g=f,y=g[1],w=y+"#"+g[2];if(!h.hasOwnProperty?.("shapeId"))h.shapeId=w;for(let S of[this,Ft.for(y)])if(!S.schemas.has(w)&&!S.exceptions.has(g))S.schemas.set(w,g),S.exceptions.set(g,h)}getErrorCtor(f){let h=f;if(this.exceptions.has(h))return this.exceptions.get(h);return Ft.for(h[1]).exceptions.get(h)}getBaseException(){for(let f of this.exceptions.keys())if(Array.isArray(f)){let[,h,g]=f,y=h+"#"+g;if(y.startsWith("smithy.ts.sdk.synthetic.")&&y.endsWith("ServiceException"))return f}return}find(f){for(let h of this.schemas.values())if(f(h))return h;return}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(f){if(f.includes("#"))return f;return this.namespace+"#"+f}}Wx.ErrorSchema=Ks;Wx.ListSchema=Vs;Wx.MapSchema=Ws;Wx.NormalizedSchema=$t;Wx.OperationSchema=Gs;Wx.SCHEMA=Vx;Wx.Schema=rt;Wx.SimpleSchema=Fn;Wx.StructureSchema=Un;Wx.TypeRegistry=Ft;Wx.deref=zs;Wx.deserializerMiddlewareOption=pl;Wx.error=Hx;Wx.getSchemaSerdePlugin=Fx;Wx.isStaticSchema=gl;Wx.list=$x;Wx.map=Bx;Wx.op=Lx;Wx.operation=wa;Wx.serializerMiddlewareOption=ml;Wx.sim=qx;Wx.simAdapter=jx;Wx.simpleSchemaCacheN=qs;Wx.simpleSchemaCacheS=js;Wx.struct=zx;Wx.traitsCache=Hs;Wx.translateTraits=Dn});var ct=i(function(X_){var{hasOwn:Ln}=at(),{getSmithyContext:E_,normalizeProvider:b_}=at();X_.getSmithyContext=E_;X_.normalizeProvider=b_;var{SMITHY_CONTEXT_KEY:yl,AlgorithmId:$n}=Jt();X_.AlgorithmId=$n;var{NormalizedSchema:ba}=Rt(),gr=(f,h)=>{let g=[];if(f)g.push(f);if(h)for(let y of h)g.push(y);return g},Qt=(f,h)=>`${f||"anonymous"}${h&&h.length>0?` (a.k.a. ${h.join(",")})`:""}`,Bn=()=>{let f=[],h=[],g=!1,y=new Set,w=(U)=>U.sort((B,z)=>Sl[z.step]-Sl[B.step]||wl[z.priority||"normal"]-wl[B.priority||"normal"]),S=(U)=>{let B=!1,z=(k)=>{let R=gr(k.name,k.aliases);if(R.includes(U)){B=!0;for(let N of R)y.delete(N);return!1}return!0};return f=f.filter(z),h=h.filter(z),B},x=(U)=>{let B=!1,z=(k)=>{if(k.middleware===U){B=!0;for(let R of gr(k.name,k.aliases))y.delete(R);return!1}return!0};return f=f.filter(z),h=h.filter(z),B},_=(U)=>(f.forEach((B)=>{U.add(B.middleware,{...B})}),h.forEach((B)=>{U.addRelativeTo(B.middleware,{...B})}),U.identifyOnResolve?.(D.identifyOnResolve()),U),A=(U)=>{let B=[];return U.before.forEach((z)=>{if(z.before.length===0&&z.after.length===0)B.push(z);else B.push(...A(z))}),B.push(U),U.after.reverse().forEach((z)=>{if(z.before.length===0&&z.after.length===0)B.push(z);else B.push(...A(z))}),B},P=(U=!1)=>{let B=[],z=[],k={};return f.forEach((N)=>{let q={...N,before:[],after:[]};for(let V of gr(q.name,q.aliases))k[V]=q;B.push(q)}),h.forEach((N)=>{let q={...N,before:[],after:[]};for(let V of gr(q.name,q.aliases))k[V]=q;z.push(q)}),z.forEach((N)=>{if(N.toMiddleware){let q=k[N.toMiddleware];if(q===void 0){if(U)return;throw Error(`${N.toMiddleware} is not found when adding ${Qt(N.name,N.aliases)} middleware ${N.relation} ${N.toMiddleware}`)}if(N.relation==="after")q.after.push(N);if(N.relation==="before")q.before.push(N)}}),w(B).map(A).reduce((N,q)=>(N.push(...q),N),[])},D={add:(U,B={})=>{let{name:z,override:k,aliases:R}=B,N={step:"initialize",priority:"normal",middleware:U,...B},q=gr(z,R);if(q.length>0){if(q.some((V)=>y.has(V))){if(!k)throw Error(`Duplicate middleware name '${Qt(z,R)}'`);for(let V of q){let W=f.findIndex((K)=>K.name===V||K.aliases?.some((J)=>J===V));if(W===-1)continue;let G=f[W];if(G.step!==N.step||N.priority!==G.priority)throw Error(`"${Qt(G.name,G.aliases)}" middleware with ${G.priority} priority in ${G.step} step cannot be overridden by "${Qt(z,R)}" middleware with ${N.priority} priority in ${N.step} step.`);f.splice(W,1)}}for(let V of q)y.add(V)}f.push(N)},addRelativeTo:(U,B)=>{let{name:z,override:k,aliases:R}=B,N={middleware:U,...B},q=gr(z,R);if(q.length>0){if(q.some((V)=>y.has(V))){if(!k)throw Error(`Duplicate middleware name '${Qt(z,R)}'`);for(let V of q){let W=h.findIndex((K)=>K.name===V||K.aliases?.some((J)=>J===V));if(W===-1)continue;let G=h[W];if(G.toMiddleware!==N.toMiddleware||G.relation!==N.relation)throw Error(`"${Qt(G.name,G.aliases)}" middleware ${G.relation} "${G.toMiddleware}" middleware cannot be overridden by "${Qt(z,R)}" middleware ${N.relation} "${N.toMiddleware}" middleware.`);h.splice(W,1)}}for(let V of q)y.add(V)}h.push(N)},clone:()=>_(Bn()),use:(U)=>{U.applyToStack(D)},remove:(U)=>{if(typeof U==="string")return S(U);else return x(U)},removeByTag:(U)=>{let B=!1,z=(k)=>{let{tags:R,name:N,aliases:q}=k;if(R&&R.includes(U)){let V=gr(N,q);for(let W of V)y.delete(W);return B=!0,!1}return!0};return f=f.filter(z),h=h.filter(z),B},concat:(U)=>{let B=_(Bn());return B.use(U),B.identifyOnResolve(g||B.identifyOnResolve()||(U.identifyOnResolve?.()??!1)),B},applyToStack:_,identify:()=>P(!0).map((U)=>{let B=U.step??U.relation+" "+U.toMiddleware;return Qt(U.name,U.aliases)+" - "+B}),identifyOnResolve(U){if(typeof U==="boolean")g=U;return g},resolve:(U,B)=>{for(let z of P().map((k)=>k.middleware).reverse())U=z(U,B);if(g)console.log(D.identify());return U}};return D},Sl={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},wl={high:3,normal:2,low:1},x_=(f)=>()=>{throw Error(f)},__=(f)=>()=>Promise.reject(f),Js=()=>{let f=new WeakSet;return(h,g)=>{if(typeof g==="object"&&g!==null){if(f.has(g))return"[Circular]";f.add(g)}return g}},T_=(f)=>new Promise((h)=>setTimeout(h,f*1000)),_l={minDelay:2,maxDelay:120},vt;(function(f){f.ABORTED="ABORTED",f.FAILURE="FAILURE",f.SUCCESS="SUCCESS",f.RETRY="RETRY",f.TIMEOUT="TIMEOUT"})(vt||(vt={}));var A_=(f)=>{if(f.state===vt.ABORTED){let h=Error(`${JSON.stringify({...f,reason:"Request was aborted"},Js())}`);throw h.name="AbortError",h}else if(f.state===vt.TIMEOUT){let h=Error(`${JSON.stringify({...f,reason:"Waiter has timed out"},Js())}`);throw h.name="TimeoutError",h}else if(f.state!==vt.SUCCESS)throw Error(`${JSON.stringify(f,Js())}`);return f},I_=async({minDelay:f,maxDelay:h,maxWaitTime:g,abortController:y,client:w,abortSignal:S},x,_)=>{let A={},[P,D]=[f*1000,h*1000],U=0,B=Date.now()+g*1000,z=Date.now()+60000,k=!1;while(!0){if(U>0){let q=v_(P,D,U,B);if(y?.signal?.aborted||S?.aborted)return A["AbortController signal aborted."]|=0,A["AbortController signal aborted."]+=1,{state:vt.ABORTED,observedResponses:A};if(Date.now()+q>B)return{state:vt.TIMEOUT,observedResponses:A};await T_(q/1000)}let{state:R,reason:N}=await _(w,x);if(N){let q=R_(N);A[q]|=0,A[q]+=1}if(R!==vt.RETRY)return{state:R,reason:N,final:N,observedResponses:A};if(U+=1,!k&&Date.now()>=z)C_(A,w),k=!0}},C_=(f={},h)=>{let g=Object.keys(f),y=0;for(let x of g){let _=f[x]|0;if(x.startsWith("403:"))y+=_}let w=h?.config?.logger,S=typeof w?.warn==="function"&&!w.constructor?.name?.includes?.("NoOpLogger")?w:console;if(y>=3||g[g.length-1]?.startsWith("403:"))S.warn("@smithy/util-waiter WARN - 403 status code encountered during waiter polling.")},R_=(f)=>{let h=f?.$response?.statusCode??f?.$metadata?.httpStatusCode;if(f?.$responseBodyText)return`${h?h+": ":""}Deserialization error for body: ${f.$responseBodyText}`;if(h){if(f?.$response||f?.message)return`${h??"Unknown"}: ${f?.message}`;return`${h}: OK`}return String(f?.message??JSON.stringify(f,Js())??"Unknown")},v_=(f,h,g,y)=>{let w=Math.log(h/f)/Math.log(2)+1;if(g>w)return h;let S=f*2**(g-1),x=Math.min(S,h),_=k_(f,x);if(Date.now()+_>y){let A=y-Date.now();return Math.max(0,A-500)}return _},k_=(f,h)=>f+Math.random()*(h-f),N_=(f)=>{if(f.maxWaitTime<=0)throw Error("WaiterConfiguration.maxWaitTime must be greater than 0");else if(f.minDelay<=0)throw Error("WaiterConfiguration.minDelay must be greater than 0");else if(f.maxDelay<=0)throw Error("WaiterConfiguration.maxDelay must be greater than 0");else if(f.maxWaitTime<=f.minDelay)throw Error(`WaiterConfiguration.maxWaitTime [${f.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${f.minDelay}] for this waiter`);else if(f.maxDelay<f.minDelay)throw Error(`WaiterConfiguration.maxDelay [${f.maxDelay}] must be greater than WaiterConfiguration.minDelay [${f.minDelay}] for this waiter`)},El=(f)=>{let h,g=new Promise((y)=>{if(h=()=>y({state:vt.ABORTED}),typeof f.addEventListener==="function")f.addEventListener("abort",h);else f.onabort=h});return{clearListener(){if(typeof f.removeEventListener==="function")f.removeEventListener("abort",h)},aborted:g}},O_=async(f,h,g)=>{let y={..._l,...f};N_(y);let w=[I_(y,h,g)],S=[];if(f.abortSignal){let{aborted:x,clearListener:_}=El(f.abortSignal);S.push(_),w.push(x)}if(f.abortController?.signal){let{aborted:x,clearListener:_}=El(f.abortController.signal);S.push(_),w.push(x)}return Promise.race(w).then((x)=>{for(let _ of S)_();return x})};class Al{config;middlewareStack=Bn();initConfig;handlers;constructor(f){this.config=f;let{protocol:h,protocolSettings:g}=f;if(g){if(typeof h==="function")f.protocol=new h(g)}}send(f,h,g){let y=typeof h!=="function"?h:void 0,w=typeof h==="function"?h:g,S=y===void 0&&this.config.cacheMiddleware===!0,x;if(S){if(!this.handlers)this.handlers=new WeakMap;let _=this.handlers;if(_.has(f.constructor))x=_.get(f.constructor);else x=f.resolveMiddleware(this.middlewareStack,this.config,y),_.set(f.constructor,x)}else delete this.handlers,x=f.resolveMiddleware(this.middlewareStack,this.config,y);if(w)x(f).then((_)=>w(null,_.output),(_)=>w(_)).catch(()=>{});else return x(f).then((_)=>_.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}var Ea="***SensitiveInformation***";function Qs(f,h){if(h==null)return h;let g=ba.of(f);if(g.getMergedTraits().sensitive)return Ea;if(g.isListSchema()){if(!!g.getValueSchema().getMergedTraits().sensitive)return Ea}else if(g.isMapSchema()){if(!!g.getKeySchema().getMergedTraits().sensitive||!!g.getValueSchema().getMergedTraits().sensitive)return Ea}else if(g.isStructSchema()&&typeof h==="object"){let y=h,w={};for(let[S,x]of g.structIterator())if(y[S]!=null)w[S]=Qs(x,y[S]);return w}return h}var bl=Symbol.for("@smithy/op-event-stream");class Xs{middlewareStack=Bn();schema;static classBuilder(){return new Il}resolveMiddlewareWithContext(f,h,g,{middlewareFn:y,clientName:w,commandName:S,inputFilterSensitiveLog:x,outputFilterSensitiveLog:_,smithyContext:A,additionalContext:P,CommandCtor:D}){for(let G of y.bind(this)(D,f,h,g))this.middlewareStack.use(G);let U=f.concat(this.middlewareStack),{logger:B}=h,z=P[yl],k={logger:B,clientName:w,commandName:S,inputFilterSensitiveLog:x,outputFilterSensitiveLog:_,...P,[yl]:{...z,commandInstance:this,...A,...g?.metricsRecorder===void 0?{}:{metricsRecorder:g.metricsRecorder}}},{requestHandler:R}=h,N=g??{};if(N.metricsRecorder)N={...N},delete N.metricsRecorder;let q,V=this.schema,W=V?.[bl];if(W!==void 0)q=W;else if(V){if(Array.isArray(V)&&V[0]===9){let[,,,,G,K]=V;q=V[bl]=Boolean(ba.of(G).getEventStreamMember()||ba.of(K).getEventStreamMember())}}if(q)N={isEventStream:q,...N};return U.resolve((G)=>R.handle(G.request,N),k)}}class Il{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(f){this._init=f}ep(f){return this._ep=f,this}m(f){return this._middlewareFn=f,this}s(f,h,g={}){return this._smithyContext={service:f,operation:h,...g},this}c(f={}){return this._additionalContext=f,this}n(f,h){return this._clientName=f,this._commandName=h,this}f(f=(g)=>g,h=(g)=>g){return this._inputFilterSensitiveLog=f,this._outputFilterSensitiveLog=h,this}ser(f){return this._serializer=f,this}de(f){return this._deserializer=f,this}sc(f){return this._operationSchema=f,this._smithyContext.operationSchema=f,this}build(){let f=this,h;return h=class extends Xs{input;static getEndpointParameterInstructions(){return f._ep}constructor(...[g]){super();this.input=g??{},f._init(this),this.schema=f._operationSchema}resolveMiddleware(g,y,w){let S=f._operationSchema,x=S?.[4]??S?.input,_=S?.[5]??S?.output;return this.resolveMiddlewareWithContext(g,y,w,{CommandCtor:h,middlewareFn:f._middlewareFn,clientName:f._clientName,commandName:f._commandName,inputFilterSensitiveLog:f._inputFilterSensitiveLog??(S?Qs.bind(null,x):(A)=>A),outputFilterSensitiveLog:f._outputFilterSensitiveLog??(S?Qs.bind(null,_):(A)=>A),smithyContext:f._smithyContext,additionalContext:f._additionalContext})}serialize=f._serializer;deserialize=f._deserializer}}}var P_="***SensitiveInformation***",M_=(f,h,g)=>{for(let[S,x]of Object.entries(f)){let _=async function(P,D,U){let B=new x(P);if(typeof D==="function")this.send(B,D);else if(typeof U==="function"){if(typeof D!=="object")throw Error(`Expected http options but got ${typeof D}`);this.send(B,D||{},U)}else return this.send(B,D)},A=(S[0].toLowerCase()+S.slice(1)).replace(/Command$/,"");h.prototype[A]=_}let{paginators:y={},waiters:w={}}=g??{};for(let[S,x]of Object.entries(y))if(h.prototype[S]===void 0)h.prototype[S]=function(_={},A,...P){return x({...A,client:this},_,...P)};for(let[S,x]of Object.entries(w))if(h.prototype[S]===void 0)h.prototype[S]=async function(_={},A,...P){let D=A;if(typeof A==="number")D={maxWaitTime:A};return x({...D,client:this},_,...P)}};class yr extends Error{static shapeId="smithy.ts.sdk.synthetic.nonamespace.client#ServiceException";$fault;$response;$retryable;$metadata;constructor(f){super(f.message);Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=f.name,this.$fault=f.$fault,this.$metadata=f.$metadata}static isInstance(f){if(!f)return!1;let h=f;return yr.prototype.isPrototypeOf(h)||Boolean(h.$fault)&&Boolean(h.$metadata)&&(h.$fault==="client"||h.$fault==="server")}static[Symbol.hasInstance](f){if(!f)return!1;let h=f;if(this===yr)return yr.isInstance(f);if(yr.isInstance(f)){if(this.prototype.isPrototypeOf(f))return!0;let g=Object.prototype.hasOwnProperty.call(this,"shapeId")?this.shapeId:void 0,y=!1;if(g){let S=Object.getPrototypeOf(h);while(S&&S!==Object.prototype){let x=S.constructor,_=x!==yr&&Object.prototype.hasOwnProperty.call(x,"shapeId")?x?.shapeId:void 0;if(_){if(y=!0,_===g)return!0}S=Object.getPrototypeOf(S)}}if(g&&y)return!1;let w=this.name;if(w&&w.length>=6){if(h.name===w)return!0;let S=Object.getPrototypeOf(h);while(S&&S!==Object.prototype){let x=S.constructor?.name;if(x&&x!=="Error"&&x===w)return!0;S=Object.getPrototypeOf(S)}}}return!1}}var Cl=(f,h={})=>{Object.entries(h).filter(([,y])=>y!==void 0).forEach(([y,w])=>{if(f[y]==null||f[y]==="")f[y]=w});let g=f.message||f.Message||"UnknownError";return f.message=g,delete f.Message,f},Rl=({output:f,parsedBody:h,exceptionCtor:g,errorCode:y})=>{let w=U_(f),S=w.httpStatusCode?w.httpStatusCode+"":void 0,x=new g({name:h?.code||h?.Code||y||S||"UnknownError",$fault:"client",$metadata:w});throw Cl(x,h)},D_=(f)=>({output:h,parsedBody:g,errorCode:y})=>{Rl({output:h,parsedBody:g,exceptionCtor:f,errorCode:y})},U_=(f)=>({httpStatusCode:f.statusCode,requestId:f.headers["x-amzn-requestid"]??f.headers["x-amzn-request-id"]??f.headers["x-amz-request-id"],extendedRequestId:f.headers["x-amz-id-2"],cfId:f.headers["x-amz-cf-id"]}),F_=(f)=>{switch(f){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:30000};default:return{}}},xl=!1,$_=(f)=>{if(f&&!xl&&parseInt(f.substring(1,f.indexOf(".")))<16)xl=!0},vl=Object.values($n),Nl=(f)=>{let h=[];for(let g in $n){if(!Ln($n,g))continue;let y=$n[g];if(f[y]===void 0)continue;h.push({algorithmId:()=>y,checksumConstructor:()=>f[y]})}for(let[g,y]of Object.entries(f.checksumAlgorithms??{}))h.push({algorithmId:()=>g,checksumConstructor:()=>y});return{addChecksumAlgorithm(g){f.checksumAlgorithms=f.checksumAlgorithms??{};let y=g.algorithmId(),w=g.checksumConstructor();if(vl.includes(y))f.checksumAlgorithms[y.toUpperCase()]=w;else f.checksumAlgorithms[y]=w;h.push(g)},checksumAlgorithms(){return h}}},Ol=(f)=>{let h={};return f.checksumAlgorithms().forEach((g)=>{let y=g.algorithmId();if(vl.includes(y))h[y]=g.checksumConstructor()}),h},Pl=(f)=>({setRetryStrategy(h){f.retryStrategy=h},retryStrategy(){return f.retryStrategy}}),Ml=(f)=>{let h={};return h.retryStrategy=f.retryStrategy(),h},Dl=(f)=>Object.assign(Nl(f),Pl(f)),B_=Dl,L_=(f)=>Object.assign(Ol(f),Ml(f)),z_=(f)=>Array.isArray(f)?f:[f],Ul=(f)=>{for(let g in f){if(!Ln(f,g))continue;if(f[g]["#text"]!==void 0)f[g]=f[g]["#text"];else if(typeof f[g]==="object"&&f[g]!==null)f[g]=Ul(f[g])}return f},H_=(f)=>f!=null;class Fl{trace(){}debug(){}info(){}warn(){}error(){}}function $l(f,h,g){let y,w,S;if(typeof h>"u"&&typeof g>"u")y={},S=f;else if(y=f,typeof h==="function")return w=h,S=g,V_(y,w,S);else S=h;for(let x in S){if(!Ln(S,x))continue;if(!Array.isArray(S[x])){y[x]=S[x];continue}Bl(y,null,S,x)}return y}var q_=(f)=>{let h={};for(let[g,y]of Object.entries(f||{}))h[g]=[,y];return h},j_=(f,h)=>{let g={};for(let y in h){if(!Ln(h,y))continue;Bl(g,f,h,y)}return g},V_=(f,h,g)=>$l(f,Object.entries(g).reduce((y,[w,S])=>{if(Array.isArray(S))y[w]=S;else if(typeof S==="function")y[w]=[h,S()];else y[w]=[h,S];return y},{})),Bl=(f,h,g,y)=>{if(h!==null){let x=g[y];if(typeof x==="function")x=[,x];let[_=W_,A=G_,P=y]=x;if(typeof _==="function"&&_(h[P])||typeof _!=="function"&&!!_)f[y]=A(h[P]);return}let[w,S]=g[y];if(typeof S==="function"){let x,_=w===void 0&&(x=S())!=null,A=typeof w==="function"&&!!w(void 0)||typeof w!=="function"&&!!w;if(_)f[y]=x;else if(A)f[y]=S()}else{let x=w===void 0&&S!=null,_=typeof w==="function"&&!!w(S)||typeof w!=="function"&&!!w;if(x||_)f[y]=S}},W_=(f)=>f!=null,G_=(f)=>f,K_=(f)=>{if(f!==f)return"NaN";switch(f){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return f}},J_=(f)=>f.toISOString().replace(".000Z","Z"),xa=(f)=>{if(f==null)return{};if(Array.isArray(f))return f.filter((h)=>h!=null).map(xa);if(typeof f==="object"){let h={};for(let g in f){if(!Ln(f,g))continue;if(f[g]==null)continue;h[g]=xa(f[g])}return h}return f};function Q_(f,h,g,y){return function(S,x,_,A,P={}){let D=Object.assign({},f,S);return Xs.classBuilder().ep(D).m(function(U,B,z,k){let R=x.call(this,U,B,z,k);return R.unshift(y(z,U.getEndpointParameterInstructions())),R}).s(h,_,P).n(g,_.charAt(0).toUpperCase()+_.slice(1)+"Command").sc(A).build()}}X_.Client=Al;X_.Command=Xs;X_.NoOpLogger=Fl;X_.SENSITIVE_STRING=P_;X_.ServiceException=yr;X_.WaiterState=vt;X_._json=xa;X_.checkExceptions=A_;X_.constructStack=Bn;X_.convertMap=q_;X_.createAggregatedClient=M_;X_.createWaiter=O_;X_.decorateServiceException=Cl;X_.emitWarningIfUnsupportedVersion=$_;X_.getArrayIfSingleItem=z_;X_.getChecksumConfiguration=Nl;X_.getDefaultClientConfiguration=B_;X_.getDefaultExtensionConfiguration=Dl;X_.getRetryConfiguration=Pl;X_.getValueFromTextNode=Ul;X_.invalidFunction=x_;X_.invalidProvider=__;X_.isSerializableHeaderValue=H_;X_.loadConfigsForDefaultMode=F_;X_.makeBuilder=Q_;X_.map=$l;X_.resolveChecksumRuntimeConfig=Ol;X_.resolveDefaultRuntimeConfig=L_;X_.resolveRetryRuntimeConfig=Ml;X_.schemaLogFilter=Qs;X_.serializeDateTime=J_;X_.serializeFloat=K_;X_.take=j_;X_.throwDefaultError=Rl;X_.waiterServiceDefaults=_l;X_.withBaseException=D_});var Ce=i(function(FA){var{homedir:FT}=c("node:os"),{sep:$T,join:zn}=c("node:path"),{createHash:BT}=c("node:crypto"),{readFile:Kl}=c("node:fs/promises"),{IniSectionType:Ys}=Jt(),{normalizeProvider:Zs}=ct(),{isValidHostLabel:LT}=at();class Gr extends Error{name="ProviderError";tryNextLink;constructor(f,h=!0){let g,y=!0;if(typeof h==="boolean")g=void 0,y=h;else if(h!=null&&typeof h==="object")g=h.logger,y=h.tryNextLink??!0;super(f);this.tryNextLink=y,Object.setPrototypeOf(this,Gr.prototype),g?.debug?.(`@smithy/property-provider ${y?"->":"(!)"} ${f}`)}static from(f,h=!0){return Object.assign(new this(f.message,h),f)}}class Hn extends Gr{name="CredentialsProviderError";constructor(f,h=!0){super(f,h);Object.setPrototypeOf(this,Hn.prototype)}}class Ca extends Gr{name="TokenProviderError";constructor(f,h=!0){super(f,h);Object.setPrototypeOf(this,Ca.prototype)}}var Jl=(...f)=>async()=>{if(f.length===0)throw new Gr("No providers in chain");let h;for(let g of f)try{return await g()}catch(y){if(h=y,y?.tryNextLink)continue;throw y}throw h},Ql=(f)=>()=>Promise.resolve(f),Ra=(f,h,g)=>{let y,w,S,x=!1,_=async()=>{if(!w)w=f();try{y=await w,S=!0,x=!1}finally{w=void 0}return y};if(h===void 0)return async(A)=>{if(!S||A?.forceRefresh)y=await _();return y};return async(A)=>{if(!S||A?.forceRefresh)y=await _();if(x)return y;if(g&&!g(y))return x=!0,y;if(h(y))return await _(),y;return y}},Bt=(f,h,g)=>{if(!(h in f))return;if(f[h]==="true")return!0;if(f[h]==="false")return!1;throw Error(`Cannot load ${g} "${h}". Expected "true" or "false", got ${f[h]}.`)},zT=(f,h,g)=>{if(!(h in f))return;let y=parseInt(f[h],10);if(Number.isNaN(y))throw TypeError(`Cannot load ${g} '${h}'. Expected number, got '${f[h]}'.`);return y},wt;(function(f){f.ENV="env",f.CONFIG="shared config entry"})(wt||(wt={}));var _a={},HT=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},qn=()=>{let{HOME:f,USERPROFILE:h,HOMEPATH:g,HOMEDRIVE:y=`C:${$T}`}=process.env;if(f)return f;if(h)return h;if(g)return`${y}${g}`;let w=HT();if(!_a[w])_a[w]=FT();return _a[w]},Xl="AWS_PROFILE",Yl="default",Zl=(f)=>f.profile||process.env[Xl]||Yl,ef=(f)=>{let g=BT("sha1").update(f).digest("hex");return zn(qn(),".aws","sso","cache",`${g}.json`)},eo={},qT=async(f)=>{if(eo[f])return eo[f];let h=ef(f),g=await Kl(h,"utf8");return JSON.parse(g)},Sr=".",jT=(f)=>Object.entries(f).filter(([h])=>{let g=h.indexOf(Sr);if(g===-1)return!1;return Object.values(Ys).includes(h.substring(0,g))}).reduce((h,[g,y])=>{let w=g.indexOf(Sr),S=g.substring(0,w)===Ys.PROFILE?g.substring(w+1):g;return h[S]=y,h},{...f.default&&{default:f.default}}),VT="AWS_CONFIG_FILE",tf=()=>process.env[VT]||zn(qn(),".aws","config"),WT="AWS_SHARED_CREDENTIALS_FILE",GT=()=>process.env[WT]||zn(qn(),".aws","credentials"),KT=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,JT=["__proto__","profile __proto__"],Aa=(f)=>{let h={},g,y;for(let w of f.split(/\r?\n/)){let S=w.split(/(^|\s)[;#]/)[0].trim();if(S[0]==="["&&S[S.length-1]==="]"){g=void 0,y=void 0;let _=S.substring(1,S.length-1),A=KT.exec(_);if(A){let[,P,,D]=A;if(Object.values(Ys).includes(P))g=[P,D].join(Sr)}else g=_;if(JT.includes(_))throw Error(`Found invalid profile name "${_}"`)}else if(g){let _=S.indexOf("=");if(![0,-1].includes(_)){let[A,P]=[S.substring(0,_).trim(),S.substring(_+1).trim()];if(P==="")y=A;else{if(y&&w.trimStart()===w)y=void 0;h[g]=h[g]||{};let D=y?[y,A].join(Sr):A;h[g][D]=P}}}}return h},Ta={},to={},ro=(f,h)=>{if(to[f]!==void 0)return to[f];if(!Ta[f]||h?.ignoreCache)Ta[f]=Kl(f,"utf8");return Ta[f]},Ll=()=>({}),va=async(f={})=>{let{filepath:h=GT(),configFilepath:g=tf()}=f,y=qn(),w="~/",S=h;if(h.startsWith("~/"))S=zn(y,h.slice(2));let x=g;if(g.startsWith("~/"))x=zn(y,g.slice(2));let _=await Promise.all([ro(x,{ignoreCache:f.ignoreCache}).then(Aa).then(jT).catch(Ll),ro(S,{ignoreCache:f.ignoreCache}).then(Aa).catch(Ll)]);return{configFile:_[0],credentialsFile:_[1]}},QT=(f)=>Object.entries(f).filter(([h])=>h.startsWith(Ys.SSO_SESSION+Sr)).reduce((h,[g,y])=>({...h,[g.substring(g.indexOf(Sr)+1)]:y}),{}),XT=()=>({}),YT=async(f={})=>ro(f.configFilepath??tf()).then(Aa).then(QT).catch(XT),ZT=(...f)=>{let h={};for(let g of f)for(let[y,w]of Object.entries(g))if(h[y]!==void 0)Object.assign(h[y],w);else h[y]=w;return h},eA=async(f)=>{let h=await va(f);return ZT(h.configFile,h.credentialsFile)},tA={getFileRecord(){return to},interceptFile(f,h){to[f]=Promise.resolve(h)},getTokenRecord(){return eo},interceptToken(f,h){eo[f]=h}};function rf(f){try{let h=new Set(Array.from(f.match(/([A-Z_]){3,}/g)??[]));return h.delete("CONFIG"),h.delete("CONFIG_PREFIX_SEPARATOR"),h.delete("ENV"),[...h].join(", ")}catch(h){return f}}var rA=(f,h)=>async()=>{try{let g=f(process.env,h);if(g===void 0)throw Error();return g}catch(g){throw new Hn(g.message||`Not found in ENV: ${rf(f.toString())}`,{logger:h?.logger})}},nA=(f,{preferredFile:h="config",...g}={})=>async()=>{let y=Zl(g),{configFile:w,credentialsFile:S}=await va(g),x=S[y]||{},_=w[y]||{},A=h==="config"?{...x,..._}:{..._,...x};try{let D=f(A,h==="config"?w:S);if(D===void 0)throw Error();return D}catch(P){throw new Hn(P.message||`Not found in config files w/ profile [${y}]: ${rf(f.toString())}`,{logger:g.logger})}},sA=(f)=>typeof f==="function",nf=(f)=>sA(f)?async()=>await f():Ql(f),Ia=({environmentVariableSelector:f,configFileSelector:h,default:g},y={})=>{let{signingName:w,logger:S}=y;return Ra(Jl(rA(f,{signingName:w,logger:S}),nA(h,y),nf(g)))},ka="AWS_USE_DUALSTACK_ENDPOINT",Na="use_dualstack_endpoint",oA=!1,iA={environmentVariableSelector:(f)=>Bt(f,ka,wt.ENV),configFileSelector:(f)=>Bt(f,Na,wt.CONFIG),default:!1},aA={environmentVariableSelector:(f)=>Bt(f,ka,wt.ENV),configFileSelector:(f)=>Bt(f,Na,wt.CONFIG),default:void 0},Oa="AWS_USE_FIPS_ENDPOINT",Pa="use_fips_endpoint",cA=!1,uA={environmentVariableSelector:(f)=>Bt(f,Oa,wt.ENV),configFileSelector:(f)=>Bt(f,Pa,wt.CONFIG),default:!1},dA={environmentVariableSelector:(f)=>Bt(f,Oa,wt.ENV),configFileSelector:(f)=>Bt(f,Pa,wt.CONFIG),default:void 0},lA=(f)=>{let{tls:h,endpoint:g,urlParser:y,useDualstackEndpoint:w}=f;return Object.assign(f,{tls:h??!0,endpoint:Zs(typeof g==="string"?y(g):g),isCustomEndpoint:!0,useDualstackEndpoint:Zs(w??!1)})},fA=async(f)=>{let{tls:h=!0}=f,g=await f.region();if(!new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/).test(g))throw Error("Invalid region in client config");let w=await f.useDualstackEndpoint(),S=await f.useFipsEndpoint(),{hostname:x}=await f.regionInfoProvider(g,{useDualstackEndpoint:w,useFipsEndpoint:S})??{};if(!x)throw Error("Cannot resolve hostname from client config");return f.urlParser(`${h?"https:":"http:"}//${x}`)},hA=(f)=>{let h=Zs(f.useDualstackEndpoint??!1),{endpoint:g,useFipsEndpoint:y,urlParser:w,tls:S}=f;return Object.assign(f,{tls:S??!0,endpoint:g?Zs(typeof g==="string"?w(g):g):()=>fA({...f,useDualstackEndpoint:h,useFipsEndpoint:y}),isCustomEndpoint:!!g,useDualstackEndpoint:h})},pA="AWS_EXECUTION_ENV",zl="AWS_REGION",Hl="AWS_DEFAULT_REGION",mA="AWS_EC2_METADATA_DISABLED",gA=["in-region","cross-region","mobile","standard","legacy"],yA="/latest/meta-data/placement/region",SA="/latest/api/token",wA="x-aws-ec2-metadata-token",EA="x-aws-ec2-metadata-token-ttl-seconds",ql=1000,bA=60000,sf=0,of=async()=>{if(process.env[mA])return;if(Date.now()<sf)return;try{let f=xA(),h=(await Vl({...f,path:SA,method:"PUT",headers:{[EA]:"21600"}})).toString();return(await Vl({...f,path:yA,method:"GET",headers:{[wA]:h}})).toString().trim()||jl()}catch{return jl()}},jl=()=>{sf=Date.now()+bA;return},xA=()=>{let f=process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT;if(f){let h=new URL(f);return{hostname:h.hostname.replace(/^\[(.+)]$/,"$1"),port:h.port?Number(h.port):void 0}}if(process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE==="IPv6")return{hostname:"fd00:ec2::254"};return{hostname:"169.254.169.254"}},Vl=async(f)=>{let{request:h}=c("node:http");return new Promise((g,y)=>{let w=h({hostname:f.hostname,port:f.port,path:f.path,method:f.method,headers:f.headers,timeout:ql,signal:AbortSignal.timeout(ql)});w.on("error",(S)=>{y(S),w.destroy()}),w.on("timeout",()=>{y(Error("TimeoutError from instance metadata service")),w.destroy()}),w.on("response",(S)=>{let{statusCode:x=400}=S;if(x<200||x>=300){y(Object.assign(Error("Error response received from instance metadata service"),{statusCode:x})),w.destroy();return}let _=[];S.on("data",(A)=>_.push(A)),S.on("end",()=>{g(Buffer.concat(_)),w.destroy()})}),w.end()})},af="AWS_REGION",cf="region",uf={environmentVariableSelector:(f)=>f[af],configFileSelector:(f)=>f[cf],default:async()=>{let f=await of();if(f)return f;throw Error("Region is missing")}},_A={preferredFile:"credentials"},Wl=new Set,TA=(f,h=LT)=>{if(!Wl.has(f)&&!h(f))if(f==="*")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 Error(`Region not accepted: region="${f}" is not a valid hostname component.`);else Wl.add(f)},df=(f)=>typeof f==="string"&&(f.startsWith("fips-")||f.endsWith("-fips")),AA=(f)=>df(f)?["fips-aws-global","aws-fips"].includes(f)?"us-east-1":f.replace(/fips-(dkr-|prod-)?|-fips/,""):f,IA=(f)=>{let{region:h,useFipsEndpoint:g}=f;if(!h)throw Error("Region is missing");return Object.assign(f,{region:async()=>{let y=typeof h==="function"?await h():h,w=AA(y);return TA(w),w},useFipsEndpoint:async()=>{let y=typeof h==="string"?h:await h();if(df(y))return!0;return typeof g!=="function"?Promise.resolve(!!g):g()}})},Gl=(f=[],{useFipsEndpoint:h,useDualstackEndpoint:g})=>f.find(({tags:y})=>h===y.includes("fips")&&g===y.includes("dualstack"))?.hostname,CA=(f,{regionHostname:h,partitionHostname:g})=>h?h:g?g.replace("{region}",f):void 0,RA=(f,{partitionHash:h})=>Object.keys(h||{}).find((g)=>h[g].regions.includes(f))??"aws",vA=(f,{signingRegion:h,regionRegex:g,useFipsEndpoint:y})=>{if(h)return h;else if(y){let w=g.replace("\\\\","\\").replace(/^\^/g,"\\.").replace(/\$$/g,"\\."),S=f.match(w);if(S)return S[0].slice(1,-1)}},kA=(f,{useFipsEndpoint:h=!1,useDualstackEndpoint:g=!1,signingService:y,regionHash:w,partitionHash:S})=>{let x=RA(f,{partitionHash:S}),_=f in w?f:S[x]?.endpoint??f,A={useFipsEndpoint:h,useDualstackEndpoint:g},P=Gl(w[_]?.variants,A),D=Gl(S[x]?.variants,A),U=CA(_,{regionHostname:P,partitionHostname:D});if(U===void 0)throw Error(`Endpoint resolution failed for: ${{resolvedRegion:_,useFipsEndpoint:h,useDualstackEndpoint:g}}`);let B=vA(U,{signingRegion:w[_]?.signingRegion,regionRegex:S[x].regionRegex,useFipsEndpoint:h});return{partition:x,signingService:y,hostname:U,...B&&{signingRegion:B},...w[_]?.signingService&&{signingService:w[_].signingService}}},NA="AWS_DEFAULTS_MODE",OA="defaults_mode",PA={environmentVariableSelector:(f)=>f[NA],configFileSelector:(f)=>f[OA],default:"legacy"},MA=({region:f=Ia(uf),defaultsMode:h=Ia(PA)}={})=>Ra(async()=>{let g=typeof h==="function"?await h():h;switch(g?.toLowerCase()){case"auto":return DA(f);case"in-region":case"cross-region":case"mobile":case"standard":case"legacy":return Promise.resolve(g?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw Error(`Invalid parameter for "defaultsMode", expect ${gA.join(", ")}, got ${g}`)}}),DA=async(f)=>{if(f){let h=typeof f==="function"?await f():f,g=await UA();if(!g)return"standard";if(h===g)return"in-region";else return"cross-region"}return"standard"},UA=async()=>{if(process.env[pA]&&(process.env[zl]||process.env[Hl]))return process.env[zl]??process.env[Hl];return of()};FA.CONFIG_PREFIX_SEPARATOR=Sr;FA.CONFIG_USE_DUALSTACK_ENDPOINT=Na;FA.CONFIG_USE_FIPS_ENDPOINT=Pa;FA.CredentialsProviderError=Hn;FA.DEFAULT_PROFILE=Yl;FA.DEFAULT_USE_DUALSTACK_ENDPOINT=oA;FA.DEFAULT_USE_FIPS_ENDPOINT=cA;FA.ENV_PROFILE=Xl;FA.ENV_USE_DUALSTACK_ENDPOINT=ka;FA.ENV_USE_FIPS_ENDPOINT=Oa;FA.NODE_REGION_CONFIG_FILE_OPTIONS=_A;FA.NODE_REGION_CONFIG_OPTIONS=uf;FA.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS=iA;FA.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS=uA;FA.ProviderError=Gr;FA.REGION_ENV_NAME=af;FA.REGION_INI_NAME=cf;FA.SelectorType=wt;FA.TokenProviderError=Ca;FA.booleanSelector=Bt;FA.chain=Jl;FA.externalDataInterceptor=tA;FA.fromStatic=nf;FA.fromValue=Ql;FA.getHomeDir=qn;FA.getProfileName=Zl;FA.getRegionInfo=kA;FA.getSSOTokenFilepath=ef;FA.getSSOTokenFromFile=qT;FA.loadConfig=Ia;FA.loadSharedConfigFiles=va;FA.loadSsoSessionData=YT;FA.memoize=Ra;FA.nodeDualstackConfigSelectors=aA;FA.nodeFipsConfigSelectors=dA;FA.numberSelector=zT;FA.parseKnownFiles=eA;FA.readFile=ro;FA.resolveCustomEndpointsConfig=lA;FA.resolveDefaultsModeConfig=MA;FA.resolveEndpointsConfig=hA;FA.resolveRegionConfig=IA});var Yt=i(function(hI){var{CONFIG_PREFIX_SEPARATOR:lf,booleanSelector:ff,SelectorType:hf,loadConfig:pf}=Ce(),{toEndpointV1:no,getSmithyContext:I0,normalizeProvider:Ma,isValidHostLabel:yf,hasOwn:C0}=at();hI.isValidHostLabel=yf;hI.middlewareEndpointToEndpointV1=no;hI.toEndpointV1=no;var{EndpointURLScheme:Fa}=Jt(),mf="AWS_ENDPOINT_URL",gf="endpoint_url",R0=(f)=>({environmentVariableSelector:(h)=>{let g=f.split(" ").map((S)=>S.toUpperCase()),y=h[[mf,...g].join("_")];if(y)return y;let w=h[mf];if(w)return w;return},configFileSelector:(h,g)=>{if(h.services){let w=["services",h.services].join(lf);if(!g||!g[w])throw Error(`The services section "${h.services}" specified in the profile is not present in the shared configuration file.`);let S=g[w],x=f.split(" ").map((A)=>A.toLowerCase()),_=S[[x.join("_"),gf].join(lf)];if(_)return _}let y=h[gf];if(y)return y;return},default:void 0}),v0="AWS_IGNORE_CONFIGURED_ENDPOINT_URLS",k0="ignore_configured_endpoint_urls",N0={environmentVariableSelector:(f)=>ff(f,v0,hf.ENV),configFileSelector:(f)=>ff(f,k0,hf.CONFIG),default:!1},oo=async(f)=>{if(await pf(N0)())return;return pf(R0(f??""))()},O0=async(f)=>{let h=f?.Bucket||"";if(typeof f.Bucket==="string")f.Bucket=h.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(F0(h)){if(f.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!U0(h)||h.indexOf(".")!==-1&&!String(f.Endpoint).startsWith("http:")||h.toLowerCase()!==h||h.length<3)f.ForcePathStyle=!0;if(f.DisableMultiRegionAccessPoints)f.disableMultiRegionAccessPoints=!0,f.DisableMRAP=!0;return f},P0=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,M0=/(\d+\.){3}\d+/,D0=/\.\./,U0=(f)=>P0.test(f)&&!M0.test(f)&&!D0.test(f),F0=(f)=>{let[h,g,y,,,w]=f.split(":"),S=h==="arn"&&f.split(":").length>=6,x=Boolean(S&&g&&y&&w);if(S&&!x)throw Error(`Invalid ARN: ${f} was an invalid ARN.`);return x},$0=(f,h,g,y=!1)=>{let w=async()=>{let S;if(y)S=g.clientContextParams?.[f]??g[f]??g[h];else S=g[f]??g[h];if(typeof S==="function")return S();return S};if(f==="credentialScope"||h==="CredentialScope")return async()=>{let S=typeof g.credentials==="function"?await g.credentials():g.credentials;return S?.credentialScope??S?.CredentialScope};if(f==="accountId"||h==="AccountId")return async()=>{let S=typeof g.credentials==="function"?await g.credentials():g.credentials;return S?.accountId??S?.AccountId};if(f==="endpoint"||h==="endpoint")return async()=>{if(g.isCustomEndpoint===!1)return;let S=await w();if(S&&typeof S==="object"){if("url"in S)return S.url.href;if("hostname"in S){let{protocol:x,hostname:_,port:A,path:P}=S;return`${x}//${_}${A?":"+A:""}${P}`}}return S};return w};function Sf(f){return async(h,g,y,w)=>{if(!y.isCustomEndpoint&&!y.ignoreConfiguredEndpointUrls){let _;if(y.serviceConfiguredEndpoint)_=await y.serviceConfiguredEndpoint();else _=await f(y.serviceId);if(_)y.endpoint=()=>Promise.resolve(no(_)),y.isCustomEndpoint=!0,w?.logger?.debug?.(`@smithy/core/endpoints - resolved endpoint from config: ${_}`)}let S=await wf(h,g,y);if(typeof y.endpointProvider!=="function")throw Error("config.endpointProvider is not set.");let x=y.endpointProvider(S,w);if(y.isCustomEndpoint&&y.endpoint){let _=await y.endpoint();if(_?.headers){x.headers??={};for(let[A,P]of Object.entries(_.headers))x.headers[A]=Array.isArray(P)?P:[P]}}return x}}var wf=async(f,h,g)=>{let y={},w=h?.getEndpointParameterInstructions?.()||{};for(let[S,x]of Object.entries(w))switch(x.type){case"staticContextParams":y[S]=x.value;break;case"contextParams":y[S]=f[x.name];break;case"clientContextParams":case"builtInParams":y[S]=await $0(x.name,S,g,x.type!=="builtInParams")();break;case"operationContextParams":y[S]=x.get(f);break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(x))}if(Object.keys(w).length===0)Object.assign(y,g);if(String(g.serviceId).toLowerCase()==="s3")await O0(y);return y};function B0(f,h,g){if(!f.__smithy_context)f.__smithy_context={features:{}};else if(!f.__smithy_context.features)f.__smithy_context.features={};f.__smithy_context.features[h]=g}function Ef(f){let h=Sf(f);return({config:g,instructions:y})=>(w,S)=>async(x)=>{if(g.isCustomEndpoint)B0(S,"ENDPOINT_OVERRIDE","N");let _=await h(x.input,{getEndpointParameterInstructions(){return y}},{...g},S);S.endpointV2=_,S.authSchemes=_.properties?.authSchemes;let A=S.authSchemes?.[0];if(A){S.signing_region=A.signingRegion,S.signing_service=A.signingName;let D=I0(S)?.selectedHttpAuthScheme?.httpAuthOption;if(D)D.signingProperties=Object.assign(D.signingProperties||{},{signing_region:A.signingRegion,signingRegion:A.signingRegion,signing_service:A.signingName,signingName:A.signingName,signingRegionSet:A.signingRegionSet},A.properties)}return w({...x})}}var L0={name:"serializerMiddleware"},bf={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:L0.name};function z0(f){let h=Ef(f);return(g,y)=>({applyToStack:(w)=>{w.addRelativeTo(h({config:g,instructions:y}),bf)}})}function H0(f){return(h)=>{let g=h.tls??!0,{endpoint:y,useDualstackEndpoint:w,useFipsEndpoint:S}=h,x=y!=null?async()=>no(await Ma(y)()):void 0,A=Object.assign(h,{endpoint:x,tls:g,isCustomEndpoint:!!y,useDualstackEndpoint:Ma(w??!1),useFipsEndpoint:Ma(S??!1),ignoreConfiguredEndpointUrls:!!h.ignoreConfiguredEndpointUrls}),P=void 0;return A.serviceConfiguredEndpoint=async()=>{if(h.serviceId&&!P)P=f(h.serviceId);return P},A}}class $a{nodes;root;conditions;results;constructor(f,h,g,y){this.nodes=f,this.root=h,this.conditions=g,this.results=y}static from(f,h,g,y){return new $a(f,h,g,y)}}class xf{capacity;data=new Map;parameters=[];constructor({size:f,params:h}){if(this.capacity=f??50,h)this.parameters=h}get(f,h){let g=this.hash(f);if(g===!1)return h();if(!this.data.has(g)){if(this.data.size>this.capacity+10){let y=this.data.keys(),w=0;while(!0){let{value:S,done:x}=y.next();if(this.data.delete(S),x||++w>10)break}}this.data.set(g,h())}return this.data.get(g)}size(){return this.data.size}hash(f){let h="",{parameters:g}=this;if(g.length===0)return!1;for(let y of g){let w=f[y],S=w==null?"\x00":String(w);if(S.includes("|;"))return!1;h+=S+"|;"}return h}}class Le extends Error{constructor(f){super(f);this.name="EndpointError"}}var jn="endpoints";function Xt(f){if(typeof f!=="object"||f==null)return f;if("ref"in f)return`$${Xt(f.ref)}`;if("fn"in f)return`${f.fn}(${(f.argv||[]).map(Xt).join(", ")})`;return JSON.stringify(f,null,2)}var _f={},q0=(f,h)=>f===h;function j0(...f){for(let h of f)if(h!=null)return h;return}var V0=(f)=>{let h=f.split("."),g=[];for(let y of h){let w=y.indexOf("[");if(w!==-1){if(y.indexOf("]")!==y.length-1)throw new Le(`Path: '${f}' does not end with ']'`);let S=y.slice(w+1,-1);if(Number.isNaN(parseInt(S)))throw new Le(`Invalid array index: '${S}' in path: '${f}'`);if(w!==0)g.push(y.slice(0,w));g.push(S)}else g.push(y)}return g},Tf=(f,h)=>V0(h).reduce((g,y)=>{if(typeof g!=="object")throw new Le(`Index '${y}' in '${h}' not found in '${JSON.stringify(f)}'`);else if(Array.isArray(g)){let w=parseInt(y);return g[w<0?g.length+w:w]}return g[y]},f),W0=(f)=>f!=null;function G0(f,h,g){return f?h:g}var K0=(f)=>!f,J0=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}$"),Af=(f)=>J0.test(f)||f.startsWith("[")&&f.endsWith("]"),Da={[Fa.HTTP]:80,[Fa.HTTPS]:443},Q0=(f)=>{let h=(()=>{try{if(f instanceof URL)return f;if(typeof f==="object"&&"hostname"in f){let{hostname:B,port:z,protocol:k="",path:R="",query:N={}}=f,q=new URL(`${k}//${B}${z?`:${z}`:""}${R}`);return q.search=Object.entries(N).map(([V,W])=>`${V}=${W}`).join("&"),q}return new URL(f)}catch(B){return null}})();if(!h)return console.error(`Unable to parse ${JSON.stringify(f)} as a whatwg URL.`),null;let g=h.href,{host:y,hostname:w,pathname:S,protocol:x,search:_}=h;if(_)return null;let A=x.slice(0,-1);if(!Object.values(Fa).includes(A))return null;let P=Af(w),D=g.includes(`${y}:${Da[A]}`)||typeof f==="string"&&f.includes(`${y}:${Da[A]}`),U=`${y}${D?`:${Da[A]}`:""}`;return{scheme:A,authority:U,path:S,normalizedPath:S.endsWith("/")?S:`${S}/`,isIp:P}};function X0(f,h,g){if(g===1)return[f];if(f==="")return[""];let y=f.split(h);if(g===0)return y;return y.slice(0,g-1).concat(y.slice(1).join(h))}var Y0=(f,h)=>f===h,Z0=(f,h,g,y)=>{if(f==null||h>=g||f.length<g||/[^\u0000-\u007f]/.test(f))return null;if(!y)return f.substring(h,g);return f.substring(f.length-g,f.length-h)},eI=(f)=>encodeURIComponent(f).replace(/[!*'()]/g,(h)=>`%${h.charCodeAt(0).toString(16).toUpperCase()}`),tI={booleanEquals:q0,coalesce:j0,getAttr:Tf,isSet:W0,isValidHostLabel:yf,ite:G0,not:K0,parseURL:Q0,split:X0,stringEquals:Y0,substring:Z0,uriEncode:eI},If=(f,h)=>{let g=[],{referenceRecord:y,endpointParams:w}=h,S=0;while(S<f.length){let x=f.indexOf("{",S);if(x===-1){g.push(f.slice(S));break}g.push(f.slice(S,x));let _=f.indexOf("}",x);if(_===-1){g.push(f.slice(x));break}if(f[x+1]==="{"&&f[_+1]==="}")g.push(f.slice(x+1,_)),S=_+2;let A=f.substring(x+1,_);if(A.includes("#")){let[P,D]=A.split("#");g.push(Tf(y[P]??w[P],D))}else g.push(y[A]??w[A]);S=_+1}return g.join("")},rI=({ref:f},h)=>h.referenceRecord[f]??h.endpointParams[f],Vn=(f,h,g)=>{if(typeof f==="string")return If(f,g);else if(f.fn)return Rf.callFunction(f,g);else if(f.ref)return rI(f,g);throw new Le(`'${h}': ${String(f)} is not a string, function or reference.`)},Cf=({fn:f,argv:h},g)=>{let y=Array(h.length);for(let x=0;x<y.length;++x){let _=h[x];if(typeof _==="boolean"||typeof _==="number")y[x]=_;else y[x]=Rf.evaluateExpression(_,"arg",g)}let w=f.indexOf(".");if(w!==-1){let _=_f[f.slice(0,w)]?.[f.slice(w+1)];if(typeof _==="function")return _(...y)}let S=tI[f];if(typeof S==="function")return S(...y);throw Error(`function ${f} not loaded in endpointFunctions.`)},Rf={evaluateExpression:Vn,callFunction:Cf},vf=(f,h)=>{let{assign:g}=f;if(g&&g in h.referenceRecord)throw new Le(`'${g}' is already defined in Reference Record.`);let y=Cf(f,h);h.logger?.debug?.(`${jn} evaluateCondition: ${Xt(f)} = ${Xt(y)}`);let w=y===""?!0:!!y;if(g!=null)return{result:w,toAssign:{name:g,value:y}};return{result:w}},kf=(f,h)=>Object.entries(f??{}).reduce((g,[y,w])=>(g[y]=w.map((S)=>{let x=Vn(S,"Header value entry",h);if(typeof x!=="string")throw new Le(`Header '${y}' value '${x}' is not a string`);return x}),g),{}),Ba=(f,h)=>Object.entries(f).reduce((g,[y,w])=>(g[y]=Of.getEndpointProperty(w,h),g),{}),Nf=(f,h)=>{if(Array.isArray(f))return f.map((g)=>Nf(g,h));switch(typeof f){case"string":return If(f,h);case"object":if(f===null)throw new Le(`Unexpected endpoint property: ${f}`);return Of.getEndpointProperties(f,h);case"boolean":return f;default:throw new Le(`Unexpected endpoint property type: ${typeof f}`)}},Of={getEndpointProperty:Nf,getEndpointProperties:Ba},Pf=(f,h)=>{let g=Vn(f,"Endpoint URL",h);if(typeof g==="string")try{return new URL(g)}catch(y){throw console.error(`Failed to construct URL with ${g}`,y),y}throw new Le(`Endpoint URL must be a string, got ${typeof g}`)},Ua=1e8,nI=(f,h)=>{let{nodes:g,root:y,results:w,conditions:S}=f,x=y,_={},A={referenceRecord:_,endpointParams:h.endpointParams,logger:h.logger};while(x!==1&&x!==-1&&x<Ua){let P=3*(Math.abs(x)-1),[D,U,B]=[g[P],g[P+1],g[P+2]],[z,k,R]=S[D],N=vf({fn:z,assign:R,argv:k},A);if(N.toAssign){let{name:q,value:V}=N.toAssign;_[q]=V}x=x>=0===N.result?U:B}if(x>=Ua){let P=w[x-Ua];if(P[0]===-1){let[,z]=P;throw new Le(Vn(z,"Error",A))}let[D,U,B]=P;return{url:Pf(D,A),properties:Ba(U,A),headers:kf(B??{},A)}}throw new Le("No matching endpoint.")},La=(f=[],h)=>{let g={},y={...h,referenceRecord:{...h.referenceRecord}},w=!1;for(let S of f){let{result:x,toAssign:_}=vf(S,y);if(!x)return{result:x};if(_)w=!0,g[_.name]=_.value,y.referenceRecord[_.name]=_.value,h.logger?.debug?.(`${jn} assign: ${_.name} := ${Xt(_.value)}`)}if(w)return{result:!0,referenceRecord:g};return{result:!0}},sI=(f,h)=>{let{conditions:g,endpoint:y}=f,{result:w,referenceRecord:S}=La(g,h);if(!w)return;let x=S?{...h,referenceRecord:{...h.referenceRecord,...S}}:h,{url:_,properties:A,headers:P}=y;h.logger?.debug?.(`${jn} Resolving endpoint from template: ${Xt(y)}`);let D={url:Pf(_,x)};if(P!=null)D.headers=kf(P,x);if(A!=null)D.properties=Ba(A,x);return D},oI=(f,h)=>{let{conditions:g,error:y}=f,{result:w,referenceRecord:S}=La(g,h);if(!w)return;let x=S?{...h,referenceRecord:{...h.referenceRecord,...S}}:h;throw new Le(Vn(y,"Error",x))},Mf=(f,h)=>{for(let g of f)if(g.type==="endpoint"){let y=sI(g,h);if(y)return y}else if(g.type==="error")oI(g,h);else if(g.type==="tree"){let y=Df.evaluateTreeRule(g,h);if(y)return y}else throw new Le(`Unknown endpoint rule: ${g}`);throw new Le("Rules evaluation failed")},iI=(f,h)=>{let{conditions:g,rules:y}=f,{result:w,referenceRecord:S}=La(g,h);if(!w)return;let x=S?{...h,referenceRecord:{...h.referenceRecord,...S}}:h;return Df.evaluateRules(y,x)},Df={evaluateRules:Mf,evaluateTreeRule:iI},aI=(f,h)=>{let{endpointParams:g,logger:y}=h,{parameters:w,rules:S}=f;h.logger?.debug?.(`${jn} Initial EndpointParams: ${Xt(g)}`);for(let _ in w){if(!C0(w,_))continue;let A=w[_],P=g[_];if(P==null&&A.default!=null){g[_]=A.default;continue}if(A.required&&P==null)throw new Le(`Missing required parameter: '${_}'`)}let x=Mf(S,{endpointParams:g,logger:y,referenceRecord:{}});return h.logger?.debug?.(`${jn} Resolved endpoint: ${Xt(x)}`),x},cI=(f)=>{let{endpoint:h}=f;if(h===void 0)f.endpoint=async()=>{throw Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint.")};return f},uI=Sf(oo),dI=H0(oo),lI=Ef(oo),fI=z0(oo);hI.BinaryDecisionDiagram=$a;hI.EndpointCache=xf;hI.EndpointError=Le;hI.customEndpointFunctions=_f;hI.decideEndpoint=nI;hI.endpointMiddleware=lI;hI.endpointMiddlewareOptions=bf;hI.getEndpointFromInstructions=uI;hI.getEndpointPlugin=fI;hI.isIpAddress=Af;hI.resolveEndpoint=aI;hI.resolveEndpointConfig=dI;hI.resolveEndpointRequiredConfig=cI;hI.resolveParams=wf});var Ke=i(function(iR){var{createHmac:NI,createHash:OI,getRandomValues:PI}=c("node:crypto"),{hasOwn:qf,HttpResponse:MI}=at();iR.hasOwn=qf;var{ReadStream:DI,lstatSync:UI,fstatSync:FI}=c("node:fs"),{toEndpointV1:$I}=Yt(),{Readable:Kr,Writable:jf,PassThrough:Uf}=c("node:stream"),Vf=(f)=>typeof ArrayBuffer==="function"&&f instanceof ArrayBuffer||Object.prototype.toString.call(f)==="[object ArrayBuffer]",Qr=(f,h=0,g=f.byteLength-h)=>{if(!Vf(f))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof f} (${f})`);return Buffer.from(f,h,g)},uo=(f,h)=>{if(typeof f!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof f} (${f})`);return h?Buffer.from(f,h):Buffer.from(f)},BI=/^[A-Za-z0-9+/]*={0,2}$/,Wf=(f)=>{if(f.length*3%4!==0)throw TypeError("Incorrect padding on base64 string.");if(!BI.exec(f))throw TypeError("Invalid base64 string.");let h=uo(f,"base64");return new Uint8Array(h.buffer,h.byteOffset,h.byteLength)},lo=(f)=>{let h=uo(f,"utf8");return new Uint8Array(h.buffer,h.byteOffset,h.byteLength/Uint8Array.BYTES_PER_ELEMENT)},Ka=(f)=>{let h;if(typeof f==="string")h=lo(f);else h=f;if(typeof h!=="object"||typeof h.byteOffset!=="number"||typeof h.byteLength!=="number")throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return Qr(h.buffer,h.byteOffset,h.byteLength).toString("base64")};function LI(f,h,g,y){return class w extends Uint8Array{static fromString(S,x="utf-8"){if(typeof S==="string"){if(x==="base64")return w.mutate(y(S));return w.mutate(h(S))}throw Error(`Unsupported conversion from ${typeof S} to Uint8ArrayBlobAdapter.`)}static mutate(S){return Object.setPrototypeOf(S,w.prototype),S}transformToString(S="utf-8"){if(S==="base64")return g(this);return f(this)}}}var Gf=(f)=>{if(typeof f==="string")return f;if(typeof f!=="object"||typeof f.byteOffset!=="number"||typeof f.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return Qr(f.buffer,f.byteOffset,f.byteLength).toString("utf8")},Ge=Array.from({length:256},(f,h)=>h.toString(16).padStart(2,"0"));function zI(f){if(typeof crypto<"u"&&typeof crypto.randomUUID==="function")return()=>crypto.randomUUID();return()=>{let h=new Uint8Array(16);return f(h),h[6]=h[6]&15|64,h[8]=h[8]&63|128,Ge[h[0]]+Ge[h[1]]+Ge[h[2]]+Ge[h[3]]+"-"+Ge[h[4]]+Ge[h[5]]+"-"+Ge[h[6]]+Ge[h[7]]+"-"+Ge[h[8]]+Ge[h[9]]+"-"+Ge[h[10]]+Ge[h[11]]+Ge[h[12]]+Ge[h[13]]+Ge[h[14]]+Ge[h[15]]}}var HI=(f,h,g=(y)=>y)=>f,qI=(f)=>{switch(f){case"true":return!0;case"false":return!1;default:throw Error(`Unable to parse boolean value "${f}"`)}},jI=(f)=>{if(f===null||f===void 0)return;if(typeof f==="number"){if(f===0||f===1)Jn.warn(ao(`Expected boolean, got ${typeof f}: ${f}`));if(f===0)return!1;if(f===1)return!0}if(typeof f==="string"){let h=f.toLowerCase();if(h==="false"||h==="true")Jn.warn(ao(`Expected boolean, got ${typeof f}: ${f}`));if(h==="false")return!1;if(h==="true")return!0}if(typeof f==="boolean")return f;throw TypeError(`Expected boolean, got ${typeof f}: ${f}`)},Gn=(f)=>{if(f===null||f===void 0)return;if(typeof f==="string"){let h=parseFloat(f);if(!Number.isNaN(h)){if(String(h)!==String(f))Jn.warn(ao(`Expected number but observed string: ${f}`));return h}}if(typeof f==="number")return f;throw TypeError(`Expected number, got ${typeof f}: ${f}`)},VI=Math.ceil(340282346638528860000000000000000000000),io=(f)=>{let h=Gn(f);if(h!==void 0&&!Number.isNaN(h)&&h!==1/0&&h!==-1/0){if(Math.abs(h)>VI)throw TypeError(`Expected 32-bit float, got ${f}`)}return h},Kn=(f)=>{if(f===null||f===void 0)return;if(Number.isInteger(f)&&!Number.isNaN(f))return f;throw TypeError(`Expected integer, got ${typeof f}: ${f}`)},WI=Kn,ja=(f)=>Ja(f,32),Va=(f)=>Ja(f,16),Wa=(f)=>Ja(f,8),Ja=(f,h)=>{let g=Kn(f);if(g!==void 0&&GI(g,h)!==g)throw TypeError(`Expected ${h}-bit integer, got ${f}`);return g},GI=(f,h)=>{switch(h){case 32:return Int32Array.of(f)[0];case 16:return Int16Array.of(f)[0];case 8:return Int8Array.of(f)[0]}},KI=(f,h)=>{if(f===null||f===void 0){if(h)throw TypeError(`Expected a non-null value for ${h}`);throw TypeError("Expected a non-null value")}return f},Kf=(f)=>{if(f===null||f===void 0)return;if(typeof f==="object"&&!Array.isArray(f))return f;let h=Array.isArray(f)?"array":typeof f;throw TypeError(`Expected object, got ${h}: ${f}`)},JI=(f)=>{if(f===null||f===void 0)return;if(typeof f==="string")return f;if(["boolean","number","bigint"].includes(typeof f))return Jn.warn(ao(`Expected string, got ${typeof f}: ${f}`)),String(f);throw TypeError(`Expected string, got ${typeof f}: ${f}`)},QI=(f)=>{if(f===null||f===void 0)return;let h=Kf(f),g=[];for(let y in h){if(!qf(h,y))continue;if(h[y]!=null)g.push(y)}if(g.length===0)throw TypeError("Unions must have exactly one non-null member. None were found.");if(g.length>1)throw TypeError(`Unions must have exactly one non-null member. Keys ${g} were not null.`);return h},Qa=(f)=>{if(typeof f=="string")return Gn(Zr(f));return Gn(f)},XI=Qa,Jf=(f)=>{if(typeof f=="string")return io(Zr(f));return io(f)},YI=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,Zr=(f)=>{let h=f.match(YI);if(h===null||h[0].length!==f.length)throw TypeError("Expected real number, got implicit NaN");return parseFloat(f)},Xa=(f)=>{if(typeof f=="string")return Qf(f);return Gn(f)},ZI=Xa,eC=Xa,tC=(f)=>{if(typeof f=="string")return Qf(f);return io(f)},Qf=(f)=>{switch(f){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;default:throw Error(`Unable to parse float value: ${f}`)}},Xf=(f)=>{if(typeof f==="string")return Kn(Zr(f));return Kn(f)},rC=Xf,nC=(f)=>{if(typeof f==="string")return ja(Zr(f));return ja(f)},Xr=(f)=>{if(typeof f==="string")return Va(Zr(f));return Va(f)},Yf=(f)=>{if(typeof f==="string")return Wa(Zr(f));return Wa(f)},ao=(f)=>String(TypeError(f).stack||f).split(`
3
+ `).slice(0,5).filter((h)=>!h.includes("stackTraceWarning")).join(`
4
+ `),Jn={warn:console.warn},sC=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Ya=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function oC(f){let h=f.getUTCFullYear(),g=f.getUTCMonth(),y=f.getUTCDay(),w=f.getUTCDate(),S=f.getUTCHours(),x=f.getUTCMinutes(),_=f.getUTCSeconds(),A=w<10?`0${w}`:`${w}`,P=S<10?`0${S}`:`${S}`,D=x<10?`0${x}`:`${x}`,U=_<10?`0${_}`:`${_}`;return`${sC[y]}, ${A} ${Ya[g]} ${h} ${P}:${D}:${U} GMT`}var iC=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),aC=(f)=>{if(f===null||f===void 0)return;if(typeof f!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let h=iC.exec(f);if(!h)throw TypeError("Invalid RFC-3339 date-time value");let[g,y,w,S,x,_,A,P]=h,D=Xr(Yr(y)),U=kt(w,"month",1,12),B=kt(S,"day",1,31);return Wn(D,U,B,{hours:x,minutes:_,seconds:A,fractionalMilliseconds:P})},cC=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}:\d{2})|[zZ])$/),uC=(f)=>{if(f===null||f===void 0)return;if(typeof f!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let h=cC.exec(f);if(!h)throw TypeError("Invalid RFC-3339 date-time value");let[g,y,w,S,x,_,A,P,D]=h,U=Xr(Yr(y)),B=kt(w,"month",1,12),z=kt(S,"day",1,31),k=Wn(U,B,z,{hours:x,minutes:_,seconds:A,fractionalMilliseconds:P});if(D.toUpperCase()!="Z")k.setTime(k.getTime()-xC(D));return k},dC=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$/),lC=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$/),fC=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})$/),hC=(f)=>{if(f===null||f===void 0)return;if(typeof f!=="string")throw TypeError("RFC-7231 date-times must be expressed as strings");let h=dC.exec(f);if(h){let[g,y,w,S,x,_,A,P]=h;return Wn(Xr(Yr(S)),za(w),kt(y,"day",1,31),{hours:x,minutes:_,seconds:A,fractionalMilliseconds:P})}if(h=lC.exec(f),h){let[g,y,w,S,x,_,A,P]=h;return yC(Wn(mC(S),za(w),kt(y,"day",1,31),{hours:x,minutes:_,seconds:A,fractionalMilliseconds:P}))}if(h=fC.exec(f),h){let[g,y,w,S,x,_,A,P]=h;return Wn(Xr(Yr(P)),za(y),kt(w.trimLeft(),"day",1,31),{hours:S,minutes:x,seconds:_,fractionalMilliseconds:A})}throw TypeError("Invalid RFC-7231 date-time value")},pC=(f)=>{if(f===null||f===void 0)return;let h;if(typeof f==="number")h=f;else if(typeof f==="string")h=Qa(f);else if(typeof f==="object"&&f.tag===1)h=f.value;else throw TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(h)||h===1/0||h===-1/0)throw TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(h*1000))},Wn=(f,h,g,y)=>{let w=h-1;return wC(f,w,g),new Date(Date.UTC(f,w,g,kt(y.hours,"hour",0,23),kt(y.minutes,"minute",0,59),kt(y.seconds,"seconds",0,60),bC(y.fractionalMilliseconds)))},mC=(f)=>{let h=new Date().getUTCFullYear(),g=Math.floor(h/100)*100+Xr(Yr(f));if(g<h)return g+100;return g},gC=1576800000000,yC=(f)=>{if(f.getTime()-new Date().getTime()>gC)return new Date(Date.UTC(f.getUTCFullYear()-100,f.getUTCMonth(),f.getUTCDate(),f.getUTCHours(),f.getUTCMinutes(),f.getUTCSeconds(),f.getUTCMilliseconds()));return f},za=(f)=>{let h=Ya.indexOf(f);if(h<0)throw TypeError(`Invalid month: ${f}`);return h+1},SC=[31,28,31,30,31,30,31,31,30,31,30,31],wC=(f,h,g)=>{let y=SC[h];if(h===1&&EC(f))y=29;if(g>y)throw TypeError(`Invalid day for ${Ya[h]} in ${f}: ${g}`)},EC=(f)=>f%4===0&&(f%100!==0||f%400===0),kt=(f,h,g,y)=>{let w=Yf(Yr(f));if(w<g||w>y)throw TypeError(`${h} must be between ${g} and ${y}, inclusive`);return w},bC=(f)=>{if(f===null||f===void 0)return 0;return Jf("0."+f)*1000},xC=(f)=>{let h=f[0],g=1;if(h=="+")g=1;else if(h=="-")g=-1;else throw TypeError(`Offset direction, ${h}, must be "+" or "-"`);let y=Number(f.substring(1,3)),w=Number(f.substring(4,6));return g*(y*60+w)*60*1000},Yr=(f)=>{let h=0;while(h<f.length-1&&f.charAt(h)==="0")h++;if(h===0)return f;return f.slice(h)},wr=function(h){return Object.assign(new String(h),{deserializeJSON(){return JSON.parse(String(h))},toString(){return String(h)},toJSON(){return String(h)}})};wr.from=(f)=>{if(f&&typeof f==="object"&&(f instanceof wr||("deserializeJSON"in f)))return f;else if(typeof f==="string"||Object.getPrototypeOf(f)===String.prototype)return wr(String(f));return wr(JSON.stringify(f))};wr.fromObject=wr.from;function _C(f){if(f.includes(",")||f.includes('"'))f=`"${f.replace(/"/g,"\\\"")}"`;return f}var Za="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",ec="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",tc="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",Zf="(\\d?\\d)",eh="(\\d{4})",TC=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),AC=new RegExp(`^${Za}, ${Zf} ${ec} ${eh} ${tc} GMT$`),IC=new RegExp(`^${Za}, ${Zf}-${ec}-(\\d\\d) ${tc} GMT$`),CC=new RegExp(`^${Za} ${ec} ( [1-9]|\\d\\d) ${tc} ${eh}$`),RC=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],vC=(f)=>{if(f==null)return;let h=NaN;if(typeof f==="number")h=f;else if(typeof f==="string"){if(!/^-?\d*\.?\d+$/.test(f))throw TypeError("parseEpochTimestamp - numeric string invalid.");h=Number.parseFloat(f)}else if(typeof f==="object"&&f.tag===1)h=f.value;if(isNaN(h)||Math.abs(h)===1/0)throw TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(h*1000))},kC=(f)=>{if(f==null)return;if(typeof f!=="string")throw TypeError("RFC3339 timestamps must be strings");let h=TC.exec(f);if(!h)throw TypeError(`Invalid RFC3339 timestamp format ${f}`);let[,g,y,w,S,x,_,,A,P]=h;Lt(y,1,12),Lt(w,1,31),Lt(S,0,23),Lt(x,0,59),Lt(_,0,60);let D=new Date(Date.UTC(Number(g),Number(y)-1,Number(w),Number(S),Number(x),Number(_),Number(A)?Math.round(parseFloat(`0.${A}`)*1000):0));if(D.setUTCFullYear(Number(g)),P.toUpperCase()!="Z"){let[,U,B,z]=/([+-])(\d\d):(\d\d)/.exec(P)||[void 0,"+",0,0],k=U==="-"?1:-1;D.setTime(D.getTime()+k*(Number(B)*60*60*1000+Number(z)*60*1000))}return D},NC=(f)=>{if(f==null)return;if(typeof f!=="string")throw TypeError("RFC7231 timestamps must be strings.");let h,g,y,w,S,x,_,A;if(A=AC.exec(f))[,h,g,y,w,S,x,_]=A;else if(A=IC.exec(f))[,h,g,y,w,S,x,_]=A,y=(Number(y)+1900).toString();else if(A=CC.exec(f))[,g,h,w,S,x,_,y]=A;if(y&&x){let P=Date.UTC(Number(y),RC.indexOf(g),Number(h),Number(w),Number(S),Number(x),_?Math.round(parseFloat(`0.${_}`)*1000):0);Lt(h,1,31),Lt(w,0,23),Lt(S,0,59),Lt(x,0,60);let D=new Date(P);return D.setUTCFullYear(Number(y)),D}throw TypeError(`Invalid RFC7231 date-time value ${f}.`)};function Lt(f,h,g){let y=Number(f);if(y<h||y>g)throw Error(`Value ${y} out of range [${h}, ${g}]`)}function OC(f,h,g){if(g<=0||!Number.isInteger(g))throw Error("Invalid number of delimiters ("+g+") for splitEvery.");let y=f.split(h);if(g===1)return y;let w=[],S="";for(let x=0;x<y.length;x++){if(S==="")S=y[x];else S+=h+y[x];if((x+1)%g===0)w.push(S),S=""}if(S!=="")w.push(S);return w}var PC=(f)=>{let h=f.length,g=[],y=!1,w=void 0,S=0;for(let x=0;x<h;++x){let _=f[x];switch(_){case'"':if(w!=="\\")y=!y;break;case",":if(!y)g.push(f.slice(S,x)),S=x+1;break}w=_}return g.push(f.slice(S)),g.map((x)=>{x=x.trim();let _=x.length;if(_<2)return x;if(x[0]==='"'&&x[_-1]==='"')x=x.slice(1,_-1);return x.replace(/\\"/g,'"')})},Ff=/^-?((0|[1-9]\d*)(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/;class fo{string;type;constructor(f,h){if(this.string=f,this.type=h,!Ff.test(f))throw Error(`@smithy/core/serde - NumericValue string must conform to the Smithy bigDecimal format. Received: "${f}"`)}toString(){return this.string}static[Symbol.hasInstance](f){if(!f||typeof f!=="object")return!1;let h=f;return fo.prototype.isPrototypeOf(f)||h.type==="bigDecimal"&&Ff.test(h.string)}}function MC(f){return new fo(String(f),"bigDecimal")}var th={},Ga={};for(let f=0;f<256;f++){let h=f.toString(16).toLowerCase();if(h.length===1)h=`0${h}`;th[f]=h,Ga[h]=f}function DC(f){if(f.length%2!==0)throw Error("Hex encoded strings must have an even number length");let h=new Uint8Array(f.length/2);for(let g=0;g<f.length;g+=2){let y=f.slice(g,g+2).toLowerCase();if(y in Ga)h[g/2]=Ga[y];else throw Error(`Cannot decode unrecognized sequence ${y} as hexadecimal`)}return h}function rh(f){let h="";for(let g=0;g<f.byteLength;g++)h+=th[f[g]];return h}var UC=(f)=>{if(!f)return 0;if(typeof f==="string")return Buffer.byteLength(f);else if(typeof f.byteLength==="number")return f.byteLength;else if(typeof f.size==="number")return f.size;else if(typeof f.start==="number"&&typeof f.end==="number")return f.end+1-f.start;else if(f instanceof DI){if(f.path!=null)return UI(f.path).size;else if(typeof f.fd==="number")return FI(f.fd).size}throw Error(`Body Length computation failed for ${f}`)},nh=(f)=>{if(f instanceof Uint8Array)return f;if(typeof f==="string")return lo(f);if(ArrayBuffer.isView(f))return new Uint8Array(f.buffer,f.byteOffset,f.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(f)};function ho(f,h){if(h===void 0){h=0;for(let w of f)h+=w.byteLength}let g=new Uint8Array(h),y=0;for(let w of f)g.set(w,y),y+=w.byteLength;return g}var sh=(f,h)=>(g,y)=>async(w)=>{let{response:S}=await g(w);try{let x=await h(S,f);return{response:S,output:x}}catch(x){if(Object.defineProperty(x,"$response",{value:S,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in x)){try{x.message+=`
5
+ Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(A){if(!y.logger||y.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else y.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof x.$responseBodyText<"u"){if(x.$response)x.$response.body=x.$responseBodyText}try{if(MI.isInstance(S)){let{headers:A={}}=S,P=Object.entries(A);x.$metadata={httpStatusCode:S.statusCode,requestId:Ha(/^x-[\w-]+-request-?id$/,P),extendedRequestId:Ha(/^x-[\w-]+-id-2$/,P),cfId:Ha(/^x-[\w-]+-cf-id$/,P)}}}catch(A){}}throw x}},Ha=(f,h)=>(h.find(([g])=>g.match(f))||[void 0,void 0])[1],oh=(f,h)=>(g,y)=>async(w)=>{let S=f,x=y.endpointV2?async()=>$I(y.endpointV2):S.endpoint;if(!x)throw Error("No valid endpoint provider available.");let _=await h(w.input,{...f,endpoint:x});return g({...w,request:_})},ih={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},ah={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function FC(f,h,g){return{applyToStack:(y)=>{y.add(sh(f,g),ih),y.add(oh(f,h),ah)}}}class ch{algorithmIdentifier;secret;hash;constructor(f,h){this.algorithmIdentifier=f,this.secret=h,this.reset()}update(f,h){this.hash.update(nh($f(f,h)))}digest(){return Promise.resolve(this.hash.digest())}reset(){this.hash=this.secret?NI(this.algorithmIdentifier,$f(this.secret)):OI(this.algorithmIdentifier)}}function $f(f,h){if(Buffer.isBuffer(f))return f;if(typeof f==="string")return uo(f,h);if(ArrayBuffer.isView(f))return Qr(f.buffer,f.byteOffset,f.byteLength);return Qr(f)}var uh=class extends Kr{expectedChecksum;checksumSourceLocation;checksum;source;base64Encoder;constructor({expectedChecksum:h,checksum:g,source:y,checksumSourceLocation:w,base64Encoder:S}){super();if(typeof y.pipe!=="function")throw Error(`@smithy/util-stream: unsupported source type ${y?.constructor?.name??y} in ChecksumStream.`);this.source=y,this.base64Encoder=S??Ka,this.expectedChecksum=h,this.checksum=g,this.checksumSourceLocation=w,this.source.on("data",this.onSourceData),this.source.on("end",this.onSourceEnd),this.source.on("error",this.onSourceError),this.source.on("close",this.onSourceClose),this.source.pause()}onSourceData=(h)=>{if(this.destroyed)return;try{this.checksum.update(h)}catch(g){this.destroy(g);return}if(!this.push(h))this.source.pause()};onSourceEnd=async()=>{if(this.destroyed)return;try{let h=await this.checksum.digest(),g=this.base64Encoder(h);if(this.expectedChecksum!==g){this.destroy(Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${g}" in response header "${this.checksumSourceLocation}".`));return}}catch(h){this.destroy(h);return}this.push(null)};onSourceError=(h)=>{this.destroy(h)};onSourceClose=()=>{if(!this.destroyed&&!this.source.readableEnded)this.destroy(Error("Connection lost or stream closed before all data was received."))};_read(h){this.source.resume()}_destroy(h,g){this.source?.removeListener("data",this.onSourceData),this.source?.removeListener("end",this.onSourceEnd),this.source?.removeListener("error",this.onSourceError),this.source?.removeListener("close",this.onSourceClose),this.source?.destroy(),g(h)}},Nt=(f)=>typeof ReadableStream==="function"&&(f?.constructor?.name===ReadableStream.name||f instanceof ReadableStream),po=(f)=>typeof Blob==="function"&&(f?.constructor?.name===Blob.name||f instanceof Blob),$C=(f)=>new TextEncoder().encode(f),dh="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Object.entries(dh).reduce((f,[h,g])=>(f[g]=Number(h),f),{});var BC=dh.split(""),qa=6,Bf=8,LC=63;function lh(f){let h;if(typeof f==="string")h=$C(f);else h=f;let g=typeof h==="object"&&typeof h.length==="number",y=typeof h==="object"&&typeof h.byteOffset==="number"&&typeof h.byteLength==="number";if(!g&&!y)throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let w="";for(let S=0;S<h.length;S+=3){let x=0,_=0;for(let P=S,D=Math.min(S+3,h.length);P<D;P++)x|=h[P]<<(D-P-1)*Bf,_+=Bf;let A=Math.ceil(_/qa);x<<=A*qa-_;for(let P=1;P<=A;P++){let D=(A-P)*qa;w+=BC[(x&LC<<D)>>D]}w+="==".slice(0,4-A)}return w}var zC=typeof ReadableStream==="function"?ReadableStream:function(){};class fh extends zC{}var HC=({expectedChecksum:f,checksum:h,source:g,checksumSourceLocation:y,base64Encoder:w})=>{if(!Nt(g))throw Error(`@smithy/util-stream: unsupported source type ${g?.constructor?.name??g} in ChecksumStream.`);let S=w??lh;if(typeof TransformStream!=="function")throw Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");let x=new TransformStream({start(){},async transform(A,P){h.update(A),P.enqueue(A)},async flush(A){let P=await h.digest(),D=S(P);if(f!==D){let U=Error(`Checksum mismatch: expected "${f}" but received "${D}" in response header "${y}".`);A.error(U)}else A.terminate()}});g.pipeThrough(x);let _=x.readable;return Object.setPrototypeOf(_,fh.prototype),_};function qC(f){if(typeof ReadableStream==="function"&&Nt(f.source))return HC(f);return new uh(f)}class co{allocByteArray;byteLength=0;byteArrays=[];constructor(f){this.allocByteArray=f}push(f){this.byteArrays.push(f),this.byteLength+=f.byteLength}flush(){if(this.byteArrays.length===1){let g=this.byteArrays[0];return this.reset(),g}let f=this.allocByteArray(this.byteLength),h=0;for(let g=0;g<this.byteArrays.length;++g){let y=this.byteArrays[g];f.set(y,h),h+=y.byteLength}return this.reset(),f}reset(){this.byteArrays=[],this.byteLength=0}}function jC(f,h,g){let y=f.getReader(),w=!1,S=0,x=["",new co((P)=>new Uint8Array(P))],_=-1,A=async(P)=>{let{value:D,done:U}=await y.read(),B=D;if(U){if(_!==-1){let z=Jr(x,_);if(Zt(z)>0)P.enqueue(z)}P.close()}else{let z=ph(B,!1);if(_!==z){if(_>=0)P.enqueue(Jr(x,_));_=z}if(_===-1){P.enqueue(B);return}let k=Zt(B);S+=k;let R=Zt(x[_]);if(k>=h&&R===0)P.enqueue(B);else{let N=hh(x,_,B);if(!w&&S>h*2)w=!0,g?.warn(`@smithy/util-stream - stream chunk size ${k} is below threshold of ${h}, automatically buffering.`);if(N>=h)P.enqueue(Jr(x,_));else await A(P)}}};return new ReadableStream({pull:A})}function hh(f,h,g){switch(h){case 0:return f[0]+=g,Zt(f[0]);case 1:case 2:return f[h].push(g),Zt(f[h])}}function Jr(f,h){switch(h){case 0:let g=f[0];return f[0]="",g;case 1:case 2:return f[h].flush()}throw Error(`@smithy/util-stream - invalid index ${h} given to flush()`)}function Zt(f){return f?.byteLength??f?.length??0}function ph(f,h=!0){if(h&&typeof Buffer<"u"&&f instanceof Buffer)return 2;if(f instanceof Uint8Array)return 1;if(typeof f==="string")return 0;return-1}function VC(f,h,g){if(Nt(f))return jC(f,h,g);let y=new Kr({read(){}}),w=!1,S=0,x=["",new co((A)=>new Uint8Array(A)),new co((A)=>Buffer.from(new Uint8Array(A)))],_=-1;return f.on("data",(A)=>{let P=ph(A,!0);if(_!==P){if(_>=0)y.push(Jr(x,_));_=P}if(_===-1){y.push(A);return}let D=Zt(A);S+=D;let U=Zt(x[_]);if(D>=h&&U===0)y.push(A);else{let B=hh(x,_,A);if(!w&&S>h*2)w=!0,g?.warn(`@smithy/util-stream - stream chunk size ${D} is below threshold of ${h}, automatically buffering.`);if(B>=h)y.push(Jr(x,_))}}),f.on("end",()=>{if(_!==-1){let A=Jr(x,_);if(Zt(A)>0)y.push(A)}y.push(null)}),y}var WC=(f,h)=>{let{base64Encoder:g,bodyLengthChecker:y,checksumAlgorithmFn:w,checksumLocationName:S,streamHasher:x}=h,_=g!==void 0&&y!==void 0&&w!==void 0&&S!==void 0&&x!==void 0,A=_?x(w,f):void 0;Promise.resolve(A).catch(()=>{});let P=f.getReader();return new ReadableStream({async pull(D){let{value:U,done:B}=await P.read();if(B){if(D.enqueue(`0\r
6
+ `),_){let z=g(await A);D.enqueue(`${S}:${z}\r
7
+ `),D.enqueue(`\r
8
+ `)}D.close()}else D.enqueue(`${(y(U)||0).toString(16)}\r
9
+ ${U}\r
10
+ `)}})};function GC(f,h){let g=f,y=f;if(Nt(y))return WC(y,h);let{base64Encoder:w,bodyLengthChecker:S,checksumAlgorithmFn:x,checksumLocationName:_,streamHasher:A}=h,P=w!==void 0&&x!==void 0&&_!==void 0&&A!==void 0,D=P?A(x,g):void 0;Promise.resolve(D).catch(()=>{});let U=new Kr({read(){g.resume()}});return g.on("data",(B)=>{let z=S(B)||0;if(z===0)return;if(U.push(`${z.toString(16)}\r
11
+ `),U.push(B),!U.push(`\r
12
+ `))g.pause()}),g.on("error",(B)=>{U.destroy(B)}),g.pause(),g.on("end",async()=>{try{if(U.push(`0\r
13
+ `),P){let B=w(await D);U.push(`${_}:${B}\r
14
+ `),U.push(`\r
15
+ `)}U.push(null)}catch(B){U.destroy(B)}}),U}async function KC(f,h){let g=0,y=[],w=f.getReader(),S=!1;while(!S){let{done:A,value:P}=await w.read();if(P)y.push(P),g+=P?.byteLength??0;if(g>=h)break;S=A}w.releaseLock();let x=new Uint8Array(Math.min(h,g)),_=0;for(let A of y){if(A.byteLength>x.byteLength-_){x.set(A.subarray(0,x.byteLength-_),_);break}else x.set(A,_);_+=A.length}return x}var JC=(f,h)=>{if(Nt(f))return KC(f,h);return new Promise((g,y)=>{let w=new QC;w.limit=h,f.pipe(w),f.on("error",(S)=>{w.end(),y(S)}),w.on("error",y),w.on("finish",function(){let S=ho(this.buffers);g(S)})})},QC=class extends jf{buffers=[];limit=1/0;bytesBuffered=0;_write(h,g,y){if(this.buffers.push(h),this.bytesBuffered+=h.byteLength??0,this.bytesBuffered>=this.limit){let w=this.bytesBuffered-this.limit,S=this.buffers[this.buffers.length-1];this.buffers[this.buffers.length-1]=S.subarray(0,S.byteLength-w),this.emit("finish")}y()}},XC=(f)=>{if(typeof f==="string")return f;if(typeof f!=="object"||typeof f.byteOffset!=="number"||typeof f.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(f)},YC=async(f)=>{if(po(f))return mh(f);return gh(f)};async function mh(f){return f.arrayBuffer().then((h)=>new Uint8Array(h))}async function gh(f){let h=[],g=f.getReader(),y=0;while(!0){let{done:w,value:S}=await g.read();if(S)h.push(S),y+=S.length;if(w)break}return ho(h,y)}var Lf="The stream has already been transformed.",ZC=(f)=>{if(!zf(f)&&!Nt(f)){let w=f?.__proto__?.constructor?.name||f;throw Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${w}`)}let h=!1,g=async()=>{if(h)throw Error(Lf);return h=!0,await YC(f)},y=(w)=>{if(typeof w.stream!=="function")throw Error(`Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.
16
+ If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);return w.stream()};return Object.assign(f,{transformToByteArray:g,transformToString:async(w)=>{let S=await g();if(w==="base64")return lh(S);else if(w==="hex")return rh(S);else if(w===void 0||w==="utf8"||w==="utf-8")return XC(S);else if(typeof TextDecoder==="function")return new TextDecoder(w).decode(S);else throw Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(h)throw Error(Lf);if(h=!0,zf(f))return y(f);else if(Nt(f))return f;else throw Error(`Cannot transform payload to web stream, got ${f}`)}})},zf=(f)=>typeof Blob==="function"&&f instanceof Blob,yh=(f)=>{if(po(f))return mh(f);if(Nt(f))return gh(f);return new Promise((h,g)=>{let y=new Sh,w=f;w.pipe(y),w.on("error",(S)=>{y.end(),g(S)}),y.on("error",g),y.on("finish",function(){let S=ho(this.bufferedBytes);h(S)})})};class Sh extends jf{bufferedBytes=[];_write(f,h,g){this.bufferedBytes.push(f),g()}}var Hf="The stream has already been transformed.",eR=(f)=>{if(!(f instanceof Kr))try{return ZC(f)}catch(y){let w=f?.__proto__?.constructor?.name||f;throw Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${w}`)}let h=!1,g=async()=>{if(h)throw Error(Hf);return h=!0,await yh(f)};return Object.assign(f,{transformToByteArray:g,transformToString:async(y)=>{let w=await g();if(y===void 0||Buffer.isEncoding(y))return Qr(w.buffer,w.byteOffset,w.byteLength).toString(y);else return new TextDecoder(y).decode(w)},transformToWebStream:()=>{if(h)throw Error(Hf);if(f.readableFlowing!==null)throw Error("The stream has been consumed by other callbacks.");if(typeof Kr.toWeb!=="function")throw Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return h=!0,Kr.toWeb(f)}})};async function tR(f){if(typeof f.stream==="function")f=f.stream();return f.tee()}async function rR(f){if(Nt(f)||po(f))return tR(f);let h=new Uf,g=new Uf;return f.pipe(h),f.pipe(g),[h,g]}function nR(f){Object.defineProperty(f,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0})}class wh extends LI(Gf,lo,Ka,Wf){}var sR=PI,Eh=zI(sR),oR=Eh;iR.ChecksumStream=uh;iR.Hash=ch;iR.LazyJsonString=wr;iR.NumericValue=fo;iR.Uint8ArrayBlobAdapter=wh;iR._parseEpochTimestamp=vC;iR._parseRfc3339DateTimeWithOffset=kC;iR._parseRfc7231DateTime=NC;iR.calculateBodyLength=UC;iR.concatBytes=ho;iR.copyDocumentWithTransform=HI;iR.createBufferedReadable=VC;iR.createChecksumStream=qC;iR.dateToUtcString=oC;iR.deserializerMiddleware=sh;iR.deserializerMiddlewareOption=ih;iR.expectBoolean=jI;iR.expectByte=Wa;iR.expectFloat32=io;iR.expectInt=WI;iR.expectInt32=ja;iR.expectLong=Kn;iR.expectNonNull=KI;iR.expectNumber=Gn;iR.expectObject=Kf;iR.expectShort=Va;iR.expectString=JI;iR.expectUnion=QI;iR.fromArrayBuffer=Qr;iR.fromBase64=Wf;iR.fromHex=DC;iR.fromString=uo;iR.fromUtf8=lo;iR.generateIdempotencyToken=oR;iR.getAwsChunkedEncodingStream=GC;iR.getSerdePlugin=FC;iR.handleFloat=ZI;iR.headStream=JC;iR.isArrayBuffer=Vf;iR.isBlob=po;iR.isReadableStream=Nt;iR.limitedParseDouble=Xa;iR.limitedParseFloat=eC;iR.limitedParseFloat32=tC;iR.logger=Jn;iR.nv=MC;iR.parseBoolean=qI;iR.parseEpochTimestamp=pC;iR.parseRfc3339DateTime=aC;iR.parseRfc3339DateTimeWithOffset=uC;iR.parseRfc7231DateTime=hC;iR.quoteHeader=_C;iR.sdkStreamMixin=eR;iR.serializerMiddleware=oh;iR.serializerMiddlewareOption=ah;iR.splitEvery=OC;iR.splitHeader=PC;iR.splitStream=rR;iR.streamCollector=yh;iR.strictParseByte=Yf;iR.strictParseDouble=Qa;iR.strictParseFloat=XI;iR.strictParseFloat32=Jf;iR.strictParseInt=rC;iR.strictParseInt32=nC;iR.strictParseLong=Xf;iR.strictParseShort=Xr;iR.toBase64=Ka;iR.toHex=rh;iR.toUint8Array=nh;iR.toUtf8=Gf;iR.v4=Eh;iR.writeKey=nR});var tn=i(function(Jv){var{createReadStream:Cv}=c("node:fs"),{Writable:Rv}=c("node:stream"),{toUint8Array:en,concatBytes:vv}=Ke(),{createHash:Qn,createHmac:kv}=c("node:crypto"),bh=c("node:zlib");async function Ih(f,h,g=1048576){let y=f.size,w=0;while(w<y){let S=f.slice(w,Math.min(y,w+g));h(new Uint8Array(await S.arrayBuffer())),w+=S.size}}var Nv=async function(h,g){let y=new h;return await Ih(g,(w)=>{y.update(w)}),y.digest()};class sc extends Rv{hash;constructor(f,h){super(h);this.hash=f}_write(f,h,g){try{this.hash.update(en(f))}catch(y){return g(y)}g()}}var Ov=(f,h)=>new Promise((g,y)=>{if(!Pv(h)){y(Error("Unable to calculate hash for non-file streams."));return}let w=Cv(h.path,{start:h.start,end:h.end}),S=new f,x=new sc(S);w.pipe(x),w.on("error",(_)=>{x.end(),y(_)}),x.on("error",y),x.on("finish",function(){S.digest().then(g).catch(y)})}),Pv=(f)=>typeof f.path==="string",Mv=(f,h)=>{if(h.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let g=new f,y=new sc(g);return h.pipe(y),new Promise((w,S)=>{h.on("error",(x)=>{y.end(),S(x)}),y.on("error",S),y.on("finish",()=>{g.digest().then(w).catch(S)})})};class oc{digestLength=16;state=Uint32Array.from(xh);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(f){let h=en(f),g=0,y=h.byteLength;this.bytesHashed+=y;while(y>0)if(this.writeBuffer.setUint8(this.bufferLength++,h[g++]),--y,this.bufferLength===64)rc(this.state,this.writeBuffer),this.bufferLength=0}async digest(){let f=Uint32Array.from(this.state),h=new DataView(this.writeBuffer.buffer.slice(0)),g=this.bufferLength,y=this.bytesHashed*8;if(h.setUint8(g++,128),this.bufferLength%64>=56){for(let x=g;x<64;++x)h.setUint8(x,0);rc(f,h),g=0}for(let x=g;x<56;++x)h.setUint8(x,0);h.setUint32(56,y>>>0,!0),h.setUint32(60,Math.floor(y/4294967296),!0),rc(f,h);let w=new Uint8Array(16),S=new DataView(w.buffer);for(let x=0;x<4;++x)S.setUint32(x*4,f[x],!0);return w}reset(){this.state.set(xh),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0}}var xh=[1732584193,4023233417,2562383102,271733878],er=4294967295,Dv=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),Uv=Array.from({length:64},(f,h)=>Math.abs(Math.sin(h+1))*4294967296>>>0);function rc(f,h){let g=f[0],y=f[1],w=f[2],S=f[3];for(let x=0;x<64;++x){let _,A;if(x<16)_=y&w|~y&S,A=x;else if(x<32)_=S&y|w&~S,A=(5*x+1)%16;else if(x<48)_=y^w^S,A=(3*x+5)%16;else _=w^(y|~S),A=7*x%16;let P=h.getUint32(A*4,!0),D=S;S=w,w=y;let U=Dv[(x>>4)*4+(x&3)],B=(g+_&er)+(P+Uv[x]&er)&er;y=y+((B<<U|B>>>32-U)>>>0)&er,g=D}f[0]=f[0]+g&er,f[1]=f[1]+y&er,f[2]=f[2]+w&er,f[3]=f[3]+S&er}var Fv=(()=>{try{return Qn("md5"),!0}catch{return!1}})(),Ch=Fv?$v():oc;function $v(){return class{digestLength=16;hash=Qn("md5");update(h){this.hash.update(en(h))}async digest(){let h=this.hash.copy().digest();return new Uint8Array(h.buffer,h.byteOffset,h.byteLength)}reset(){this.hash=Qn("md5")}}}var Rh=new Uint32Array(256);for(let f=0;f<256;++f){let h=f;for(let g=0;g<8;++g)h=h&1?3988292384^h>>>1:h>>>1;Rh[f]=h>>>0}var nc=4294967295;class ic{digestLength=4;checksum=nc;update(f){for(let h=0;h<f.length;++h)this.checksum=this.checksum>>>8^Rh[(this.checksum^f[h])&255]}digestSync(){return(this.checksum^nc)>>>0}async digest(){let f=this.digestSync(),h=new Uint8Array(4);return new DataView(h.buffer).setUint32(0,f,!1),h}reset(){this.checksum=nc}}var _h=typeof bh.crc32==="function"?bh.crc32:void 0,vh=_h?Bv(_h):ic;function Bv(f){return class{digestLength=4;value=0;update(g){this.value=f(g,this.value)}digestSync(){return this.value>>>0}async digest(){let g=new Uint8Array(4);return new DataView(g.buffer).setUint32(0,this.digestSync(),!1),g}reset(){this.value=0}}}var ze=64,Th=32,Lv=9007199254740991;class zt{digestLength=Th;state=Int32Array.from(Ah);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=!1;inner;outer;constructor(f){if(f){let h=zt.normalizeKey(f);this.inner=new zt,this.outer=new zt;let{inner:g,outer:y}=this,w=new Uint8Array(ze*2);for(let S=0;S<ze;++S)w[S]=54^h[S],w[S+ze]=92^h[S];g.update(w.subarray(0,ze)),y.update(w.subarray(ze))}}update(f){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(f);return}let h=en(f),g=0,{byteLength:y}=h;if(this.bytesHashed+=y,this.bytesHashed*8>Lv)throw Error("Cannot hash more than 2^53 - 1 bits");while(y>0)if(this.buffer[this.bufferLength++]=h[g++],y--,this.bufferLength===ze)this.hashBuffer(),this.bufferLength=0}async digest(){let{inner:f,outer:h}=this;if(f&&h){if(this.finished)throw Error("Attempted to digest an already finished HMAC.");this.finished=!0;let g=f.digestSync();return h.update(g),h.digestSync()}return this.digestSync()}reset(){this.state=Int32Array.from(Ah),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0}digestSync(){let f=this.state.slice(),h=this.buffer.slice(),g=this.bufferLength,y=this.bytesHashed*8,w=new DataView(h.buffer,h.byteOffset,h.byteLength);if(w.setUint8(g++,128),(g-1)%ze>=ze-8){for(let x=g;x<ze;++x)w.setUint8(x,0);this.hashBufferWith(f,h),g=0}for(let x=g;x<ze-8;++x)w.setUint8(x,0);w.setUint32(ze-8,Math.floor(y/4294967296),!1),w.setUint32(ze-4,y,!1),this.hashBufferWith(f,h);let S=new Uint8Array(Th);for(let x=0;x<8;++x)S[x*4]=f[x]>>>24&255,S[x*4+1]=f[x]>>>16&255,S[x*4+2]=f[x]>>>8&255,S[x*4+3]=f[x]>>>0&255;return S}static normalizeKey(f){let h=en(f);if(h.byteLength>ze){let g=new zt;g.update(h);let y=g.digestSync(),w=new Uint8Array(ze);return w.set(y),w}if(h.byteLength<ze){let g=new Uint8Array(ze);return g.set(h),g}return h}hashBuffer(){this.hashBufferWith(this.state,this.buffer)}hashBufferWith(f,h){let g=this.w??=new Int32Array(64),y=f[0],w=f[1],S=f[2],x=f[3],_=f[4],A=f[5],P=f[6],D=f[7];for(let U=0;U<ze;++U){if(U<16)g[U]=(h[U*4]&255)<<24|(h[U*4+1]&255)<<16|(h[U*4+2]&255)<<8|h[U*4+3]&255;else{let k=g[U-2],R=(k>>>17|k<<15)^(k>>>19|k<<13)^k>>>10;k=g[U-15];let N=(k>>>7|k<<25)^(k>>>18|k<<14)^k>>>3;g[U]=(R+g[U-7]|0)+(N+g[U-16]|0)}let B=(((_>>>6|_<<26)^(_>>>11|_<<21)^(_>>>25|_<<7))+(_&A^~_&P)|0)+(D+(zv[U]+g[U]|0)|0)|0,z=((y>>>2|y<<30)^(y>>>13|y<<19)^(y>>>22|y<<10))+(y&w^y&S^w&S)|0;D=P,P=A,A=_,_=x+B|0,x=S,S=w,w=y,y=B+z|0}f[0]+=y,f[1]+=w,f[2]+=S,f[3]+=x,f[4]+=_,f[5]+=A,f[6]+=P,f[7]+=D}}var Ah=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),zv=new Int32Array([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]),Hv=(()=>{try{return Qn("sha256"),!0}catch{return!1}})(),kh=Hv?qv():zt;function qv(){return class{digestLength=32;secret;hash;isHmac;finished=!1;constructor(h){this.secret=h,this.isHmac=!!h,this.hash=this.createHash()}update(h){if(this.finished)throw Error("Attempted to update an already finished hash.");this.hash.update(h)}async digest(){let h;if(this.isHmac)this.finished=!0,h=this.hash.digest();else h=this.hash.copy().digest();return new Uint8Array(h.buffer,h.byteOffset,h.byteLength)}reset(){this.hash=this.createHash(),this.finished=!1}createHash(){return this.secret?kv("sha256",jv(this.secret)):Qn("sha256")}}}function jv(f){if(typeof f==="string")return f;if(ArrayBuffer.isView(f))return Buffer.from(f.buffer,f.byteOffset,f.byteLength);return Buffer.from(f)}var{digest:Vv,sign:Wv,importKey:Gv}=globalThis?.crypto?.subtle??{},mo=typeof Vv==="function"&&typeof Wv==="function"&&typeof Gv==="function"?globalThis.crypto.subtle:void 0,Kv=8388608;class Nh{digestLength=32;secret;pending=[];pendingBytes=0;fallback;finished=!1;constructor(f){if(f)this.secret=en(f)}update(f){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.fallback){this.fallback.update(f);return}if(this.pending.push(f.slice()),this.pendingBytes+=f.byteLength,this.pendingBytes>=Kv)this.switchToFallback()}async digest(){if(this.fallback)return this.fallback.digest();if(this.secret&&this.finished)throw Error("Attempted to digest an already finished HMAC.");let f=vv(this.pending);if(mo){if(this.secret){this.finished=!0;let y=await mo.importKey("raw",this.secret,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),w=await mo.sign("HMAC",y,f);return new Uint8Array(w)}let g=await mo.digest("SHA-256",f);return new Uint8Array(g)}let h=new zt(this.secret);return h.update(f),h.digest()}reset(){this.pending=[],this.pendingBytes=0,this.fallback=void 0,this.finished=!1}switchToFallback(){let f=new zt(this.secret);for(let h of this.pending)f.update(h);this.fallback=f,this.pending=[],this.pendingBytes=0}}Jv.Crc32=vh;Jv.Crc32Js=ic;Jv.Crc32Node=vh;Jv.Md5=Ch;Jv.Md5Js=oc;Jv.Md5Node=Ch;Jv.Sha256=kh;Jv.Sha256Js=zt;Jv.Sha256Node=kh;Jv.Sha256WebCrypto=Nh;Jv.blobHasher=Nv;Jv.blobReader=Ih;Jv.fileStreamHasher=Ov;Jv.readableStreamHasher=Mv});var gc=i(function(Pk){var{Crc32:Dh}=tn(),{hasOwn:yo}=at(),{toHex:rn,fromHex:dk,toUtf8:lk,fromUtf8:fk}=Ke(),{Readable:hk}=c("node:stream"),{TypeRegistry:pk}=Rt();class sn{bytes;constructor(f){if(this.bytes=f,f.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(f){if(f>9223372036854776000||f<-9223372036854776000)throw Error(`${f} is too large (or, if negative, too small) to represent as an Int64`);let h=new Uint8Array(8);for(let g=7,y=Math.abs(Math.round(f));g>-1&&y>0;g--,y/=256)h[g]=y;if(f<0)Oh(h);return new sn(h)}valueOf(){let f=this.bytes.slice(0),h=f[0]&128;if(h)Oh(f);return parseInt(rn(f),16)*(h?-1:1)}toString(){return String(this.valueOf())}}function Oh(f){for(let h=0;h<8;h++)f[h]^=255;for(let h=7;h>-1;h--)if(f[h]++,f[h]!==0)break}class ac{toUtf8;fromUtf8;constructor(f,h){this.toUtf8=f,this.fromUtf8=h}format(f){let h=[];for(let w in f){if(!yo(f,w))continue;let S=this.fromUtf8(w);if(S.byteLength>255)throw Error(`@smithy/core/event-streams - header name exceeds 255 bytes: ${S.byteLength}`);h.push(Uint8Array.from([S.byteLength]),S,this.formatHeaderValue(f[w]))}let g=new Uint8Array(h.reduce((w,S)=>w+S.byteLength,0)),y=0;for(let w of h)g.set(w,y),y+=w.byteLength;return g}formatHeaderValue(f){switch(f.type){case"boolean":return Uint8Array.from([f.value?0:1]);case"byte":return Uint8Array.from([2,f.value]);case"short":let h=new DataView(new ArrayBuffer(3));return h.setUint8(0,3),h.setInt16(1,f.value,!1),new Uint8Array(h.buffer);case"integer":let g=new DataView(new ArrayBuffer(5));return g.setUint8(0,4),g.setInt32(1,f.value,!1),new Uint8Array(g.buffer);case"long":let y=new Uint8Array(9);return y[0]=5,y.set(f.value.bytes,1),y;case"binary":if(f.value.byteLength>go)throw Error(`@smithy/core/event-streams - header value (binary) exceeds ${go} bytes: ${f.value.byteLength}`);let w=new DataView(new ArrayBuffer(3+f.value.byteLength));w.setUint8(0,6),w.setUint16(1,f.value.byteLength,!1);let S=new Uint8Array(w.buffer);return S.set(f.value,3),S;case"string":let x=this.fromUtf8(f.value);if(x.byteLength>go)throw Error(`@smithy/core/event-streams - header value (string) exceeds ${go} bytes: ${x.byteLength}`);let _=new DataView(new ArrayBuffer(3+x.byteLength));_.setUint8(0,7),_.setUint16(1,x.byteLength,!1);let A=new Uint8Array(_.buffer);return A.set(x,3),A;case"timestamp":let P=new Uint8Array(9);return P[0]=8,P.set(sn.fromNumber(f.value.valueOf()).bytes,1),P;case"uuid":if(!_k.test(f.value))throw Error(`Invalid UUID received: ${f.value}`);let D=new Uint8Array(17);return D[0]=9,D.set(dk(f.value.replace(/-/g,"")),1),D}}parse(f){let h={},g=0;while(g<f.byteLength){let y=f.getUint8(g++),w=this.toUtf8(new Uint8Array(f.buffer,f.byteOffset+g,y));switch(g+=y,f.getUint8(g++)){case 0:h[w]={type:Mh,value:!0};break;case 1:h[w]={type:Mh,value:!1};break;case 2:h[w]={type:mk,value:f.getInt8(g++)};break;case 3:h[w]={type:gk,value:f.getInt16(g,!1)},g+=2;break;case 4:h[w]={type:yk,value:f.getInt32(g,!1)},g+=4;break;case 5:h[w]={type:Sk,value:new sn(new Uint8Array(f.buffer,f.byteOffset+g,8))},g+=8;break;case 6:let S=f.getUint16(g,!1);g+=2,h[w]={type:wk,value:new Uint8Array(f.buffer,f.byteOffset+g,S)},g+=S;break;case 7:let x=f.getUint16(g,!1);g+=2,h[w]={type:Ek,value:this.toUtf8(new Uint8Array(f.buffer,f.byteOffset+g,x))},g+=x;break;case 8:h[w]={type:bk,value:new Date(new sn(new Uint8Array(f.buffer,f.byteOffset+g,8)).valueOf())},g+=8;break;case 9:let _=new Uint8Array(f.buffer,f.byteOffset+g,16);g+=16,h[w]={type:xk,value:`${rn(_.subarray(0,4))}-${rn(_.subarray(4,6))}-${rn(_.subarray(6,8))}-${rn(_.subarray(8,10))}-${rn(_.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return h}}var Ph;(function(f){f[f.boolTrue=0]="boolTrue",f[f.boolFalse=1]="boolFalse",f[f.byte=2]="byte",f[f.short=3]="short",f[f.integer=4]="integer",f[f.long=5]="long",f[f.byteArray=6]="byteArray",f[f.string=7]="string",f[f.timestamp=8]="timestamp",f[f.uuid=9]="uuid"})(Ph||(Ph={}));var Mh="boolean",mk="byte",gk="short",yk="integer",Sk="long",wk="binary",Ek="string",bk="timestamp",xk="uuid",_k=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,go=32767,Uh=4,tr=Uh*2,Er=4,Tk=tr+Er*2;function Ak({byteLength:f,byteOffset:h,buffer:g}){if(f<Tk)throw Error("Provided message too short to accommodate event stream message overhead");let y=new DataView(g,h,f),w=y.getUint32(0,!1);if(f!==w)throw Error("Reported message length does not match received message length");let S=y.getUint32(Uh,!1),x=y.getUint32(tr,!1),_=y.getUint32(f-Er,!1),A=new Dh;if(A.update(new Uint8Array(g,h,tr)),x!==A.digestSync())throw Error(`The prelude checksum specified in the message (${x}) does not match the calculated CRC32 checksum (${A.digestSync()})`);if(A.update(new Uint8Array(g,h+tr,f-(tr+Er))),_!==A.digestSync())throw Error(`The message checksum (${A.digestSync()}) did not match the expected value of ${_}`);return{headers:new DataView(g,h+tr+Er,S),body:new Uint8Array(g,h+tr+Er+S,w-S-(tr+Er+Er))}}class cc{headerMarshaller;messageBuffer;isEndOfStream;constructor(f,h){this.headerMarshaller=new ac(f,h),this.messageBuffer=[],this.isEndOfStream=!1}feed(f){this.messageBuffer.push(this.decode(f))}endOfStream(){this.isEndOfStream=!0}getMessage(){let f=this.messageBuffer.pop(),h=this.isEndOfStream;return{getMessage(){return f},isEndOfStream(){return h}}}getAvailableMessages(){let f=this.messageBuffer;this.messageBuffer=[];let h=this.isEndOfStream;return{getMessages(){return f},isEndOfStream(){return h}}}encode({headers:f,body:h}){let g=this.headerMarshaller.format(f),y=g.byteLength+h.byteLength+16,w=new Uint8Array(y),S=new DataView(w.buffer,w.byteOffset,w.byteLength),x=new Dh;return S.setUint32(0,y,!1),S.setUint32(4,g.byteLength,!1),x.update(w.subarray(0,8)),S.setUint32(8,x.digestSync(),!1),w.set(g,12),w.set(h,g.byteLength+12),x.update(w.subarray(8,y-4)),S.setUint32(y-4,x.digestSync(),!1),w}decode(f){let{headers:h,body:g}=Ak(f);return{headers:this.headerMarshaller.parse(h),body:g}}formatHeaders(f){return this.headerMarshaller.format(f)}}class uc{options;constructor(f){this.options=f}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let f of this.options.inputStream)yield this.options.decoder.decode(f)}}class dc{options;constructor(f){this.options=f}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let f of this.options.messageStream)yield this.options.encoder.encode(f);if(this.options.includeEndFrame)yield new Uint8Array(0)}}class lc{options;constructor(f){this.options=f}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let f of this.options.messageStream){let h=await this.options.deserializer(f);if(h===void 0)continue;yield h}}}class fc{options;constructor(f){this.options=f}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let f of this.options.inputStream)yield this.options.serializer(f)}}function Fh(f){let h=0,g=0,y=null,w=null,S=(_)=>{if(typeof _!=="number")throw Error("Attempted to allocate an event message where size was not a number: "+_);h=_,g=4,y=new Uint8Array(_),new DataView(y.buffer).setUint32(0,_,!1)},x=async function*(){let _=f[Symbol.asyncIterator]();while(!0){let{value:A,done:P}=await _.next();if(P){if(!h)return;else if(h===g)yield y;else throw Error("Truncated event message received.");return}let D=A.length,U=0;while(U<D){if(!y){let z=D-U;if(!w)w=new Uint8Array(4);let k=Math.min(4-g,z);if(w.set(A.slice(U,U+k),g),g+=k,U+=k,g<4)break;S(new DataView(w.buffer).getUint32(0,!1)),w=null}let B=Math.min(h-g,D-U);if(y.set(A.slice(U,U+B),g),g+=B,U+=B,h&&h===g)yield y,y=null,h=0,g=0}}};return{[Symbol.asyncIterator]:x}}function Ik(f,h){let g=hc(h.deserializer,h.toUtf8);return{[Symbol.asyncIterator]:async function*(){for await(let y of f){let w=h.eventStreamCodec.decode(y),S=await g(w);if(S===void 0)continue;yield S}}}}function hc(f,h){return async function(g){let{value:y}=g.headers[":message-type"];if(y==="error"){let w=Error(g.headers[":error-message"].value||"UnknownError");throw w.name=g.headers[":error-code"].value,w}else if(y==="exception"){let w=g.headers[":exception-type"].value,S={[w]:g},x=await f(S);if(x.$unknown){let _=Error(h(g.body));throw _.name=w,_}throw x[w]}else if(y==="event"){let w={[g.headers[":event-type"].value]:g},S=await f(w);if(S.$unknown)return;return S}else throw Error(`Unrecognizable event type: ${g.headers[":event-type"].value}`)}}var pc=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:h,utf8Decoder:g}){this.eventStreamCodec=new cc(h,g),this.utfEncoder=h}deserialize(h,g){let y=Fh(h);return new lc({messageStream:new uc({inputStream:y,decoder:this.eventStreamCodec}),deserializer:hc(g,this.utfEncoder)})}serialize(h,g){return new dc({messageStream:new fc({inputStream:h,serializer:g}),encoder:this.eventStreamCodec,includeEndFrame:!0})}},Ck=(f)=>new pc(f);class mc{universalMarshaller;constructor({utf8Encoder:f,utf8Decoder:h}){this.universalMarshaller=new pc({utf8Decoder:h,utf8Encoder:f})}deserialize(f,h){let g=typeof f[Symbol.asyncIterator]==="function"?f:vk(f);return this.universalMarshaller.deserialize(g,h)}serialize(f,h){return hk.from(this.universalMarshaller.serialize(f,h))}}var Rk=(f)=>new mc(f);async function*vk(f){let h=!1,g=!1,y=[];f.on("error",(w)=>{if(!h)h=!0;if(w)throw w}),f.on("data",(w)=>{y.push(w)}),f.on("end",()=>{h=!0});while(!g){let w=await new Promise((S)=>setTimeout(()=>S(y.shift()),0));if(w)yield w;g=h&&y.length===0}}var kk=(f)=>({[Symbol.asyncIterator]:async function*(){let h=f.getReader();try{while(!0){let{done:g,value:y}=await h.read();if(g)return;yield y}}finally{h.releaseLock()}}}),Nk=(f)=>{let h=f[Symbol.asyncIterator]();return new ReadableStream({async pull(g){let{done:y,value:w}=await h.next();if(y)return g.close();g.enqueue(w)}})},Ok=(f)=>Object.assign(f,{eventStreamMarshaller:f.eventStreamSerdeProvider(f)});class $h{marshaller;serializer;deserializer;serdeContext;defaultContentType;compositeErrorRegistry;constructor({marshaller:f,serializer:h,deserializer:g,serdeContext:y,defaultContentType:w,compositeErrorRegistry:S}){this.marshaller=f,this.serializer=h,this.deserializer=g,this.serdeContext=y,this.defaultContentType=w,this.compositeErrorRegistry=S}async serializeEventStream({eventStream:f,requestSchema:h,initialRequest:g,initialMessageType:y}){let w=this.marshaller,S=h.getEventStreamMember(),x=h.getMemberSchema(S),_=this.serializer,A=this.defaultContentType,P=Symbol("initialRequestMarker"),D={async*[Symbol.asyncIterator](){if(g){let U={":event-type":{type:"string",value:y??"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:A}};_.write(h,g);let B=_.flush();yield{[P]:!0,headers:U,body:B}}for await(let U of f)yield U}};return w.serialize(D,(U)=>{if(U[P])return{headers:U.headers,body:U.body};let B="";for(let V in U){if(!yo(U,V))continue;if(V!=="__type"){B=V;break}}let{additionalHeaders:z,body:k,eventType:R,explicitPayloadContentType:N}=this.writeEventBody(B,x,U);return{headers:{":event-type":{type:"string",value:R},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:N??A},...z},body:k}})}async deserializeEventStream({response:f,responseSchema:h,initialResponseContainer:g,initialMessageType:y}){let w=this.marshaller,S=h.getEventStreamMember(),_=h.getMemberSchema(S).getMemberSchemas(),A=Symbol("initialResponseMarker"),P=w.deserialize(f.body,async(B)=>{let z="";for(let R in B){if(!yo(B,R))continue;if(R!=="__type"){z=R;break}}let k=B[z].body;if(z===(y??"initial-response")){let R=await this.deserializer.read(h,k);return delete R[S],{[A]:!0,...R}}else if(z in _){let R=_[z];if(R.isStructSchema()){let N={},q=!1;for(let[V,W]of R.structIterator()){let{eventHeader:G,eventPayload:K}=W.getMergedTraits();if(q=q||Boolean(G||K),K){if(W.isBlobSchema())N[V]=k;else if(W.isStringSchema())N[V]=(this.serdeContext?.utf8Encoder??lk)(k);else if(W.isStructSchema())N[V]=await this.deserializer.read(W,k)}else if(G){let J=B[z].headers[V]?.value;if(J!=null)if(W.isNumericSchema())if(J&&typeof J==="object"&&"bytes"in J)N[V]=BigInt(J.toString());else N[V]=Number(J);else N[V]=J}}return{[z]:await this.readEventMember(R,k,q,N)}}return{[z]:await this.deserializer.read(R,k)}}else return{$unknown:B}}),D=P[Symbol.asyncIterator](),U=await D.next();if(U.done)return P;if(U.value?.[A]){if(!h)throw Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let B in U.value){if(!yo(U.value,B))continue;g[B]=U.value[B]}}return{async*[Symbol.asyncIterator](){if(!U?.value?.[A])yield U.value;while(!0){let{done:B,value:z}=await D.next();if(B)break;yield z}}}}async readEventMember(f,h,g,y){let w,S=f.getSchema();if(Array.isArray(S)&&S[0]===-3){let _=S[1],A=pk.for(_);this.compositeErrorRegistry?.copyFrom(A),w=(this.compositeErrorRegistry??A)?.getErrorCtor(S)}let x=g?y:h.byteLength===0?{}:await this.deserializer.read(f,h);if(w){let _=x.message??x.Message??"Unknown",A={},P=f.getMergedTraits().error;if(P)A.$fault=P;return Object.assign(new w({}),A,{message:_},x)}return x}writeEventBody(f,h,g){let y=this.serializer,w=f,S=null,x,_=(()=>h.getSchema()[4].includes(f))(),A={};if(!_){let[U,B]=g[f];w=U,y.write(15,B)}else{let U=h.getMemberSchema(f);if(U.isStructSchema()){for(let[B,z]of U.structIterator()){let{eventHeader:k,eventPayload:R}=z.getMergedTraits();if(R)S=B;else if(k){let N=g[f][B],q="binary";if(z.isNumericSchema())if(-2147483648<=N&&N<=2147483647)q="integer";else q="long";else if(z.isTimestampSchema())q="timestamp";else if(z.isStringSchema())q="string";else if(z.isBooleanSchema())q="boolean";if(N!=null)A[B]={type:q,value:N},delete g[f][B]}}if(S!==null){let B=U.getMemberSchema(S);if(B.isBlobSchema())x="application/octet-stream";else if(B.isStringSchema())x="text/plain";y.write(B,g[f][S])}else y.write(U,g[f])}else if(U.isUnitSchema())y.write(U,{});else throw Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}let P=y.flush()??new Uint8Array;return{body:typeof P==="string"?(this.serdeContext?.utf8Decoder??fk)(P):P,eventType:w,explicitPayloadContentType:x,additionalHeaders:A}}}Pk.EventStreamCodec=cc;Pk.EventStreamMarshaller=mc;Pk.EventStreamSerde=$h;Pk.HeaderMarshaller=ac;Pk.Int64=sn;Pk.MessageDecoderStream=uc;Pk.MessageEncoderStream=dc;Pk.SmithyMessageDecoderStream=lc;Pk.SmithyMessageEncoderStream=fc;Pk.UniversalEventStreamMarshaller=pc;Pk.eventStreamSerdeProvider=Rk;Pk.getChunkedStream=Fh;Pk.getMessageUnmarshaller=hc;Pk.getUnmarshalledStream=Ik;Pk.iterableToReadableStream=Nk;Pk.readableStreamToIterable=kk;Pk.resolveEventStreamSerdeConfig=Ok;Pk.universalEventStreamSerdeProvider=Ck});var Bh=i(function(Ht){Object.defineProperty(Ht,"__esModule",{value:!0});Ht.SmithyMessageEncoderStream=Ht.SmithyMessageDecoderStream=Ht.MessageEncoderStream=Ht.MessageDecoderStream=Ht.Int64=Ht.HeaderMarshaller=Ht.EventStreamCodec=void 0;var br=gc();Object.defineProperty(Ht,"EventStreamCodec",{enumerable:!0,get:function(){return br.EventStreamCodec}});Object.defineProperty(Ht,"HeaderMarshaller",{enumerable:!0,get:function(){return br.HeaderMarshaller}});Object.defineProperty(Ht,"Int64",{enumerable:!0,get:function(){return br.Int64}});Object.defineProperty(Ht,"MessageDecoderStream",{enumerable:!0,get:function(){return br.MessageDecoderStream}});Object.defineProperty(Ht,"MessageEncoderStream",{enumerable:!0,get:function(){return br.MessageEncoderStream}});Object.defineProperty(Ht,"SmithyMessageDecoderStream",{enumerable:!0,get:function(){return br.SmithyMessageDecoderStream}});Object.defineProperty(Ht,"SmithyMessageEncoderStream",{enumerable:!0,get:function(){return br.SmithyMessageEncoderStream}})});var Lh=i(function(Xn){Object.defineProperty(Xn,"__esModule",{value:!0});Xn.toUtf8=Xn.toUint8Array=Xn.fromUtf8=void 0;var yc=Ke();Object.defineProperty(Xn,"fromUtf8",{enumerable:!0,get:function(){return yc.fromUtf8}});Object.defineProperty(Xn,"toUint8Array",{enumerable:!0,get:function(){return yc.toUint8Array}});Object.defineProperty(Xn,"toUtf8",{enumerable:!0,get:function(){return yc.toUtf8}})});var Ne=i(function(TO){var{Uint8ArrayBlobAdapter:Ic,sdkStreamMixin:GN,splitEvery:KN,splitHeader:Tp,fromBase64:To,_parseEpochTimestamp:JN,_parseRfc7231DateTime:QN,_parseRfc3339DateTimeWithOffset:XN,LazyJsonString:un,NumericValue:He,toUtf8:Ro,fromUtf8:YN,generateIdempotencyToken:Oc,toBase64:cn,dateToUtcString:Pc,quoteHeader:ZN,writeKey:_r,parseEpochTimestamp:Ap,parseRfc7231DateTime:Ip,parseRfc3339DateTimeWithOffset:Cp}=Ke(),{HttpRequest:dn,HttpResponse:Rp,hasOwn:ke,isValidHostname:vp,getSmithyContext:eO}=at(),{parseQueryString:tO,parseUrl:rO}=at();TO.HttpRequest=dn;TO.HttpResponse=Rp;TO.isValidHostname=vp;TO.parseQueryString=tO;TO.parseUrl=rO;var{TypeRegistry:Nc,NormalizedSchema:Ie,translateTraits:kp,deref:nO}=Rt(),{FieldPosition:sO}=Jt(),qt=async(f=new Uint8Array,h)=>{if(f instanceof Uint8Array)return Ic.mutate(f);if(!f)return Ic.mutate(new Uint8Array);let g=h.streamCollector(f);return Ic.mutate(await g)};function rs(f){return encodeURIComponent(f).replace(/[!'()*]/g,function(h){return"%"+h.charCodeAt(0).toString(16).toUpperCase()})}class ln{serdeContext;setSerdeContext(f){this.serdeContext=f}}class vo extends ln{options;compositeErrorRegistry;constructor(f){super();this.options=f,this.compositeErrorRegistry=new Nc(f.defaultNamespace);for(let h of f.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(h)}getRequestType(){return dn}getResponseType(){return Rp}setSerdeContext(f){if(this.serdeContext=f,this.serializer.setSerdeContext(f),this.deserializer.setSerdeContext(f),this.getPayloadCodec())this.getPayloadCodec().setSerdeContext(f)}updateServiceEndpoint(f,h){if("url"in h){if(f.protocol=h.url.protocol,f.hostname=h.url.hostname,f.port=h.url.port?Number(h.url.port):void 0,f.path=h.url.pathname,f.fragment=h.url.hash||void 0,f.username=h.url.username||void 0,f.password=h.url.password||void 0,!f.query)f.query={};for(let[g,y]of h.url.searchParams.entries())f.query[g]=y;if(h.headers)for(let g in h.headers){if(!ke(h.headers,g))continue;f.headers[g]=h.headers[g].join(", ")}return f}else{if(f.protocol=h.protocol,f.hostname=h.hostname,f.port=h.port?Number(h.port):void 0,f.path=h.path,f.query={...h.query},h.headers)for(let g in h.headers){if(!ke(h.headers,g))continue;f.headers[g]=h.headers[g]}return f}}setHostPrefix(f,h,g){if(this.serdeContext?.disableHostPrefix)return;let y=Ie.of(h.input),w=kp(h.traits??{});if(w.endpoint){let S=w.endpoint?.[0];if(typeof S==="string"){for(let[x,_]of y.structIterator()){if(!_.getMergedTraits().hostLabel)continue;let A=g[x];if(typeof A!=="string")throw Error(`@smithy/core/schema - ${x} in input must be a string as hostLabel.`);S=S.replace(`{${x}}`,A)}if(f.hostname=S+f.hostname,!vp(f.hostname))throw Error(`[${f.hostname}] is not a valid hostname.`)}}}deserializeMetadata(f){return{httpStatusCode:f.statusCode,requestId:f.headers["x-amzn-requestid"]??f.headers["x-amzn-request-id"]??f.headers["x-amz-request-id"],extendedRequestId:f.headers["x-amz-id-2"],cfId:f.headers["x-amz-cf-id"]}}resolveError(f,h,g){let y=[-3,"","Error",0,[],[],0],w;for(let S of g)for(let x of h)try{if(x==="*")w=S.getSchema(f);else w=S.getSchema(x+"#"+f);let _=S.getErrorCtor(w);if(_)return[w,_,"modeled"];else{let A=S.getBaseException();if(A){let P=S.getErrorCtor(A);if(P)return[w,P,"synthetic"]}}}catch(_){}for(let S of g){let x=S.getBaseException();if(x){let _=S.getErrorCtor(x);if(_)return[x,_,"synthetic"]}}return[y,Error,"native"]}async serializeEventStream({eventStream:f,requestSchema:h,initialRequest:g}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:f,requestSchema:h,initialRequest:g})}async deserializeEventStream({response:f,responseSchema:h,initialResponseContainer:g}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:f,responseSchema:h,initialResponseContainer:g})}async loadEventStreamCapability(){let{EventStreamSerde:f,eventStreamSerdeProvider:h}=gc(),g=this.resolveEventStreamMarshaller(h);return new f({marshaller:g,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType(),compositeErrorRegistry:this.compositeErrorRegistry})}getDefaultContentType(){throw Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(f,h,g,y,w){return[]}getEventStreamMarshaller(){let f=this.serdeContext;if(!f.eventStreamMarshaller)throw Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return f.eventStreamMarshaller}resolveEventStreamMarshaller(f){let h=this.serdeContext;if(h.eventStreamMarshaller)return h.eventStreamMarshaller;return f(this.serdeContext)}}class Np extends vo{async serializeRequest(f,h,g){let y=h&&typeof h==="object"?h:{},w=this.serializer,S={},x={},_=await g.endpoint(),A=Ie.of(f?.input),P=[],D=[],U=!1,B,z=new dn({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:S,headers:x,body:void 0});if(_){this.updateServiceEndpoint(z,_),this.setHostPrefix(z,f,y);let k=kp(f.traits);if(k.http){z.method=k.http[0];let[R,N]=k.http[1].split("?");if(z.path=="/")z.path=R;else z.path+=R;let q=new URLSearchParams(N??"");for(let[V,W]of q)S[V]=W}}for(let[k,R]of A.structIterator()){let N=R.getMergedTraits()??{},q=y[k];if(q==null&&!R.isIdempotencyToken()){if(N.httpLabel){if(z.path.includes(`{${k}+}`)||z.path.includes(`{${k}}`))throw Error(`No value provided for input HTTP label: ${k}.`)}continue}if(N.httpPayload)if(R.isStreaming())if(R.isStructSchema()){if(y[k])B=await this.serializeEventStream({eventStream:y[k],requestSchema:A})}else B=q;else w.write(R,q),B=w.flush();else if(N.httpLabel){w.write(R,q);let V=w.flush();if(z.path.includes(`{${k}+}`))z.path=z.path.replace(`{${k}+}`,V.split("/").map(rs).join("/"));else if(z.path.includes(`{${k}}`))z.path=z.path.replace(`{${k}}`,rs(V))}else if(N.httpHeader)w.write(R,q),x[N.httpHeader.toLowerCase()]=String(w.flush());else if(typeof N.httpPrefixHeaders==="string")for(let V in q){if(!ke(q,V))continue;let W=q[V],G=N.httpPrefixHeaders+V;w.write([R.getValueSchema(),{httpHeader:G}],W),x[G.toLowerCase()]=w.flush()}else if(N.httpQuery||N.httpQueryParams)this.serializeQuery(R,q,S);else U=!0,P.push(k),D.push(R)}if(U&&y){let[k,R]=(A.getName(!0)??"#Unknown").split("#"),N=A.getSchema()[6],q=[3,k,R,A.getMergedTraits(),P,D,void 0];if(N)q[6]=N;else q.pop();w.write(q,y),B=w.flush()}return z.headers=x,z.query=S,z.body=B,z}serializeQuery(f,h,g){let y=this.serializer,w=f.getMergedTraits();if(w.httpQueryParams){for(let S in h){if(!ke(h,S))continue;if(!(S in g)){let x=h[S],_=f.getValueSchema();Object.assign(_.getMergedTraits(),{...w,httpQuery:S,httpQueryParams:void 0}),this.serializeQuery(_,x,g)}}return}if(f.isListSchema()){let S=!!f.getMergedTraits().sparse,x=[];for(let _ of h){y.write([f.getValueSchema(),w],_);let A=y.flush();if(S||A!==void 0)x.push(A)}g[w.httpQuery]=x}else y.write([f,w],h),g[w.httpQuery]=y.flush()}async deserializeResponse(f,h,g){let y=this.deserializer,w=Ie.of(f.output),S={};if(g.statusCode>=300){let _=await qt(g.body,h);if(_.byteLength>0)Object.assign(S,await y.read(15,_));throw await this.handleError(f,h,g,S,this.deserializeMetadata(g)),Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(let _ in g.headers){if(!ke(g.headers,_))continue;let A=g.headers[_];delete g.headers[_],g.headers[_.toLowerCase()]=A}let x=await this.deserializeHttpMessage(w,h,g,S);if(x.length){let _=await qt(g.body,h);if(_.byteLength>0){let A=await y.read(w,_);for(let P of x)if(A[P]!=null)S[P]=A[P]}}else if(x.discardResponseBody)await qt(g.body,h);return S.$metadata=this.deserializeMetadata(g),S}async deserializeHttpMessage(f,h,g,y,w){let S;if(y instanceof Set)S=w;else S=y;let x=!0,_=this.deserializer,A=Ie.of(f),P=[];for(let[D,U]of A.structIterator()){let B=U.getMemberTraits();if(B.httpPayload){if(x=!1,U.isStreaming())if(U.isStructSchema())S[D]=await this.deserializeEventStream({response:g,responseSchema:A});else S[D]=GN(g.body);else if(g.body){let k=await qt(g.body,h);if(k.byteLength>0)S[D]=await _.read(U,k)}}else if(B.httpHeader){let z=String(B.httpHeader).toLowerCase(),k=g.headers[z];if(k!=null)if(U.isListSchema()){let R=U.getValueSchema();R.getMergedTraits().httpHeader=z;let N;if(R.isTimestampSchema()&&R.getSchema()===4)N=KN(k,",",2);else N=Tp(k);let q=[];for(let V of N)q.push(await _.read(R,V.trim()));S[D]=q}else S[D]=await _.read(U,k)}else if(B.httpPrefixHeaders!==void 0){S[D]={};for(let z in g.headers){if(!ke(g.headers,z))continue;if(z.startsWith(B.httpPrefixHeaders)){let k=g.headers[z],R=U.getValueSchema();R.getMergedTraits().httpHeader=z,S[D][z.slice(B.httpPrefixHeaders.length)]=await _.read(R,k)}}}else if(B.httpResponseCode)S[D]=g.statusCode;else P.push(D)}return P.discardResponseBody=x,P}}class Mc extends vo{async serializeRequest(f,h,g){let y=this.serializer,w={},S={},x=await g.endpoint(),_=Ie.of(f?.input),A=_.getSchema(),P,D=h&&typeof h==="object"?h:{},U=new dn({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:w,headers:S,body:void 0});if(x)this.updateServiceEndpoint(U,x),this.setHostPrefix(U,f,D);if(D){let B=_.getEventStreamMember();if(B){if(D[B]){let z={};for(let[k]of _.structIterator())if(k!==B&&D[k]!=null)z[k]=D[k];P=await this.serializeEventStream({eventStream:D[B],requestSchema:_,initialRequest:z})}}else y.write(A,D),P=y.flush()}return U.headers=Object.assign(U.headers,S),U.query=w,U.body=P,U.method="POST",U}async deserializeResponse(f,h,g){let y=this.deserializer,w=Ie.of(f.output),S={};if(this.isErrorResponse(g.statusCode)){let _=await qt(g.body,h);if(_.byteLength>0)Object.assign(S,await y.read(15,_));throw await this.handleError(f,h,g,S,this.deserializeMetadata(g)),Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(let _ in g.headers){if(!ke(g.headers,_))continue;let A=g.headers[_];delete g.headers[_],g.headers[_.toLowerCase()]=A}let x=w.getEventStreamMember();if(x)S[x]=await this.deserializeEventStream({response:g,responseSchema:w,initialResponseContainer:S});else{let _=await qt(g.body,h);if(_.byteLength>0)Object.assign(S,await y.read(w,_))}return S.$metadata=this.deserializeMetadata(g),S}isErrorResponse(f){return f>=300}}class Dc extends Mc{constructor({defaultNamespace:f,errorTypeRegistries:h}){super({defaultNamespace:f,errorTypeRegistries:h})}async serializeRequest(f,h,g){let y=await super.serializeRequest(f,h,g);if(Object.assign(y.headers,{"content-type":this.getDefaultContentType(),"smithy-protocol":this.getSmithyProtocolHeaderValue(),accept:this.getDefaultContentType()}),nO(f.input)==="unit")delete y.body,delete y.headers["content-type"];else this.applyEmptyBody(y);let{service:w,operation:S}=eO(g),x=`/service/${w}/operation/${S}`;if(y.path.endsWith("/"))y.path+=x.slice(1);else y.path+=x;return y}isErrorResponse(f){return f!==200}}var Op=(f,h,g,y,w,S)=>{if(h!=null&&h[g]!==void 0){let x=y();if(x==null||x.length<=0)throw Error("Empty value provided for input HTTP label: "+g+".");f=f.replace(w,S?x.split("/").map((_)=>rs(_)).join("/"):rs(x))}else throw Error("No value provided for input HTTP label: "+g+".");return f};function oO(f,h){return new Uc(f,h)}class Uc{input;context;query={};method="";headers={};path="";body=null;hostname="";resolvePathStack=[];constructor(f,h){this.input=f,this.context=h}async build(){let{hostname:f,protocol:h="https",port:g,path:y}=await this.context.endpoint();this.path=y;for(let w of this.resolvePathStack)w(this.path);return new dn({protocol:h,hostname:this.hostname||f,port:g,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(f){return this.hostname=f,this}bp(f){return this.resolvePathStack.push((h)=>{this.path=`${h?.endsWith("/")?h.slice(0,-1):h||""}`+f}),this}p(f,h,g,y){return this.resolvePathStack.push((w)=>{this.path=Op(w,this.input,f,h,g,y)}),this}h(f){return this.headers=f,this}q(f){return this.query=f,this}b(f){return this.body=f,this}m(f){return this.method=f,this}}function Tr(f,h){if(h.timestampFormat.useTrait){if(f.isTimestampSchema()&&(f.getSchema()===5||f.getSchema()===6||f.getSchema()===7))return f.getSchema()}let{httpLabel:g,httpPrefixHeaders:y,httpHeader:w,httpQuery:S}=f.getMergedTraits();return(h.httpBindings?typeof y==="string"||Boolean(w)?6:Boolean(S)||Boolean(g)?5:void 0:void 0)??h.timestampFormat.default}class Fc extends ln{settings;constructor(f){super();this.settings=f}read(f,h){let g=Ie.of(f);if(g.isListSchema())return Tp(h).map((y)=>this.read(g.getValueSchema(),y));if(g.isBlobSchema())return(this.serdeContext?.base64Decoder??To)(h);if(g.isTimestampSchema())switch(Tr(g,this.settings)){case 5:return XN(h);case 6:return QN(h);case 7:return JN(h);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",h),new Date(h)}if(g.isStringSchema()){let y=g.getMergedTraits().mediaType,w=h;if(y){if(g.getMergedTraits().httpHeader)w=this.base64ToUtf8(w);if(y==="application/json"||y.endsWith("+json"))w=un.from(w);return w}}if(g.isNumericSchema())return Number(h);if(g.isBigIntegerSchema())return BigInt(h);if(g.isBigDecimalSchema())return new He(h,"bigDecimal");if(g.isBooleanSchema())return String(h).toLowerCase()==="true";return h}base64ToUtf8(f){return(this.serdeContext?.utf8Encoder??Ro)((this.serdeContext?.base64Decoder??To)(f))}}class Pp extends ln{codecDeserializer;stringDeserializer;constructor(f,h){super();this.codecDeserializer=f,this.stringDeserializer=new Fc(h)}setSerdeContext(f){this.stringDeserializer.setSerdeContext(f),this.codecDeserializer.setSerdeContext(f),this.serdeContext=f}read(f,h){let g=Ie.of(f),y=g.getMergedTraits(),w=this.serdeContext?.utf8Encoder??Ro;if(y.httpHeader||y.httpResponseCode)return this.stringDeserializer.read(g,w(h));if(y.httpPayload){if(g.isBlobSchema()){let S=this.serdeContext?.utf8Decoder??YN;if(typeof h==="string")return S(h);return h}else if(g.isStringSchema()){if("byteLength"in h)return w(h);return h}}return this.codecDeserializer.read(g,h)}}class $c extends ln{settings;stringBuffer="";constructor(f){super();this.settings=f}write(f,h){let g=Ie.of(f);switch(typeof h){case"object":if(h===null){this.stringBuffer="null";return}if(g.isTimestampSchema()){if(!(h instanceof Date))throw Error(`@smithy/core/protocols - received non-Date value ${h} when schema expected Date in ${g.getName(!0)}`);switch(Tr(g,this.settings)){case 5:this.stringBuffer=h.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=Pc(h);break;case 7:this.stringBuffer=String(h.getTime()/1000);break;default:console.warn("Missing timestamp format, using epoch seconds",h),this.stringBuffer=String(h.getTime()/1000)}return}if(g.isBlobSchema()&&"byteLength"in h){this.stringBuffer=(this.serdeContext?.base64Encoder??cn)(h);return}if(g.isListSchema()&&Array.isArray(h)){let S="";for(let x of h){this.write([g.getValueSchema(),g.getMergedTraits()],x);let _=this.flush(),A=g.getValueSchema().isTimestampSchema()?_:ZN(_);if(S!=="")S+=", ";S+=A}this.stringBuffer=S;return}this.stringBuffer=JSON.stringify(h,null,2);break;case"string":let y=g.getMergedTraits().mediaType,w=h;if(y){if(y==="application/json"||y.endsWith("+json"))w=un.from(w);if(g.getMergedTraits().httpHeader){this.stringBuffer=(this.serdeContext?.base64Encoder??cn)(w.toString());return}}this.stringBuffer=h;break;default:if(g.isIdempotencyToken())this.stringBuffer=Oc();else this.stringBuffer=String(h)}}flush(){let f=this.stringBuffer;return this.stringBuffer="",f}}class Mp{codecSerializer;stringSerializer;buffer;constructor(f,h,g=new $c(h)){this.codecSerializer=f,this.stringSerializer=g}setSerdeContext(f){this.codecSerializer.setSerdeContext(f),this.stringSerializer.setSerdeContext(f)}write(f,h){let g=Ie.of(f),y=g.getMergedTraits();if(y.httpHeader||y.httpLabel||y.httpQuery){this.stringSerializer.write(g,h),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(g,h)}flush(){if(this.buffer!==void 0){let f=this.buffer;return this.buffer=void 0,f}return this.codecSerializer.flush()}}class Dp{name;kind;values;constructor({name:f,kind:h=sO.HEADER,values:g=[]}){this.name=f,this.kind=h,this.values=g}add(f){this.values.push(f)}set(f){this.values=f}remove(f){this.values=this.values.filter((h)=>h!==f)}toString(){return this.values.map((f)=>f.includes(",")||f.includes(" ")?`"${f}"`:f).join(", ")}get(){return this.values}}class Up{entries={};encoding;constructor({fields:f=[],encoding:h="utf-8"}){f.forEach(this.setField.bind(this)),this.encoding=h}setField(f){this.entries[f.name.toLowerCase()]=f}getField(f){return this.entries[f.toLowerCase()]}removeField(f){delete this.entries[f.toLowerCase()]}getByType(f){return Object.values(this.entries).filter((h)=>h.kind===f)}}var iO=(f)=>{if(f.logger&&f.logger.constructor?.name!=="NoOpLogger")f.requestHandler?.updateHttpClientConfig?.(Symbol.for("logger"),f.logger);if(f.defaultSocketTimeout)f.requestHandler?.updateHttpClientConfig?.(Symbol.for("@smithy/defaultSocketTimeout"),f.defaultSocketTimeout);return{setHttpHandler(h){f.requestHandler=h},httpHandler(){return f.requestHandler},updateHttpClientConfig(h,g){f.requestHandler?.updateHttpClientConfig(h,g)},httpHandlerConfigs(){return f.requestHandler.httpHandlerConfigs()}}},aO=(f)=>({requestHandler:f.httpHandler()}),gp="content-length";function Fp(f){return(h)=>async(g)=>{let y=g.request;if(dn.isInstance(y)){let{body:w,headers:S}=y;if(w&&Object.keys(S).map((x)=>x.toLowerCase()).indexOf(gp)===-1)try{let x=f(w);if(x!=null)y.headers={...y.headers,[gp]:String(x)}}catch(x){}}return h({...g,request:y})}}var $p={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},cO=(f)=>({applyToStack:(h)=>{h.add(Fp(f.bodyLengthChecker),$p)}}),ts=(f)=>encodeURIComponent(f).replace(/[!'()*]/g,uO),uO=(f)=>`%${f.charCodeAt(0).toString(16).toUpperCase()}`,dO=(f)=>f.split("/").map(ts).join("/");function lO(f){let h=[];for(let g of Object.keys(f).sort()){let y=f[g];if(g=ts(g),Array.isArray(y))for(let w=0,S=y.length;w<S;w++)h.push(`${g}=${ts(y[w])}`);else{let w=g;if(y||typeof y==="string")w+=`=${ts(y)}`;h.push(w)}}return h.join("&")}class Ar{serdeContext;setSerdeContext(f){this.serdeContext=f}}class Bc{from;to;keys;constructor(f,h){this.from=f,this.to=h;let g=Object.keys(this.from),y=new Set(g);y.delete("__type"),this.keys=y}mark(f){this.keys.delete(f)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){let f=this.keys.values().next().value,h=this.from[f];this.to.$unknown=[f,h]}}}var es;function Bp(){if(es===void 0)try{if(typeof Buffer!=="function")es=!1;else{let f=JSON.parse(Buffer.from([123,125]));es=f!==null&&typeof f==="object"}}catch{es=!1}return es}function Lc(f,h,g){if(g?.source){let y=g.source;if(typeof h==="number")if(h<=Number.MAX_SAFE_INTEGER&&h>=Number.MIN_SAFE_INTEGER){if(hO(y,h))return h;return new He(y,"bigDecimal")}else{if(fO(y))return new He(y,"bigDecimal");if(/[eE]/.test(y))return pO(y);return BigInt(y)}}return h}function fO(f){let h=f.indexOf(".");if(h===-1)return!1;let g=f.search(/[eE]/);if(g===-1)return!0;let y=g-h-1;return parseInt(f.slice(g+1),10)<y}function hO(f,h){if(f===String(h))return!0;if(Object.is(h,-0))return!0;if(/[eE]/.test(f))return Cc(f)===Cc(String(h));let g=f.replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""),y=String(h);if(g===y)return!0;if(/[eE]/.test(y))return g===Cc(y);return!1}function Cc(f){let h=f.startsWith("-"),g=h?f.slice(1):f,y=g.search(/[eE]/),w;if(y===-1)w=g;else{let S=parseInt(g.slice(y+1),10),x=g.slice(0,y),_=x.indexOf("."),A,P;if(_===-1)A=x,P=x.length;else A=x.slice(0,_)+x.slice(_+1),P=_;A=A.replace(/0+$/,"")||"0";let D=P+S;if(A==="0")w="0";else if(D<=0)w="0."+"0".repeat(-D)+A;else if(D>=A.length)w=A+"0".repeat(D-A.length);else w=A.slice(0,D)+"."+A.slice(D)}if(w.includes("."))w=w.replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"");return(h?"-":"")+w}function pO(f){let h=f.search(/[eE]/),g=parseInt(f.slice(h+1),10),y=f.startsWith("-"),w=f.slice(y?1:0,h),S=w.indexOf("."),x,_;if(S===-1)x=w,_=g;else{x=w.slice(0,S)+w.slice(S+1);let P=w.length-S-1;_=g-P}x=x.replace(/0+$/,"")||"0";let A=BigInt(x)*10n**BigInt(_+(w.replace(".","").length-x.length));return y?-A:A}var Rc=Symbol.for("@aws-sdk/reviver");function zc(f){let h=Ie.of(f),g=h.getSchema();if(Array.isArray(g)&&h.isStructSchema()){if(Rc in g)return g[Rc];let y=Ao(h,new Set);return g[Rc]=y,y}return Ao(h,new Set)}function Ao(f,h){let g=f.getSchema();if(h.has(g))return!1;if(h.add(g),f.isBigIntegerSchema()||f.isBigDecimalSchema())return!0;if(f.isStructSchema()){for(let[,y]of f.structIterator())if(Ao(y,h))return!0}else if(f.isListSchema()||f.isMapSchema()){if(Ao(f.getValueSchema(),h))return!0}else if(f.isDocumentSchema())return!0;return!1}var mO=(f,h)=>qt(f,h).then((g)=>(h?.utf8Encoder??Ro)(g));async function ko(f,h,g){let y;if(Bp()&&typeof f?.[Symbol.asyncIterator]==="function"){let S=await qt(f,h);if(typeof Buffer==="function")if(Buffer.isBuffer(S))y=S;else y=Buffer.from(S.buffer,S.byteOffset,S.byteLength)}if(!y)y=await mO(f,h);if(y.length===0)return{};let w=g&&zc(g)?Lc:void 0;try{return JSON.parse(y,w)}catch(S){if(S?.name==="SyntaxError")Object.defineProperty(S,"$responseBodyText",{value:typeof y==="string"?y:y.toString("utf8")});throw S}}var gO=async(f,h)=>{let g=await ko(f,h);return g.message=g.message??g.Message,g},yp=(f,h)=>Object.keys(f).find((g)=>g.toLowerCase()===h.toLowerCase()),vc=(f)=>{let h=f;if(typeof h==="number")h=h.toString();if(h.indexOf(",")>=0)h=h.split(",")[0];if(h.indexOf(":")>=0)h=h.split(":")[0];if(h.indexOf("#")>=0)h=h.split("#")[1];return h},yO=(f,h)=>zp(f,h,["header","code","type"]),SO=(f,h,g=!1)=>zp(f,h,g?["code","header","type"]:["type","code","header"]),Lp=(f,h)=>{if(h?.__type!==void 0){let g=h.__type;if(typeof g==="number")g=g.toString();if(g.indexOf(",")>=0)g=g.split(",")[0];if(g.indexOf(":")>=0)g=g.split(":")[0];return g}},zp=({headers:f},h,g)=>{while(g.length>0)switch(g.shift()){case"header":let w=yp(f??{},"x-amzn-errortype");if(w!==void 0)return vc(f[w]);break;case"code":let S=yp(h??{},"code");if(S&&h[S]!==void 0)return vc(h[S]);break;case"type":if(h?.__type!==void 0)return vc(h.__type);break}};class Hc extends Ar{settings;constructor(f){super();this.settings=f}async read(f,h){let g=zc(f)?Lc:void 0,y;if(typeof h==="string"){if(h.length===0)return{};y=JSON.parse(h,g)}else if(h instanceof Uint8Array&&Bp()){if(h.byteLength===0)return{};let w=Buffer.isBuffer(h)?h:Buffer.from(h.buffer,h.byteOffset,h.byteLength);y=JSON.parse(w,g)}else y=await ko(h,this.serdeContext,f);return this._read(f,y)}readObject(f,h){return this._read(f,h)}_read(f,h){let g=h!==null&&typeof h==="object",y=Ie.of(f);if(g){if(y.isStructSchema())return this._readStruct(y,h);if(Array.isArray(h)&&y.isListSchema()){let S=y.getValueSchema();if(this.needsTransform(S))for(let x=0;x<h.length;++x)h[x]=this._read(S,h[x]);return h}if(y.isMapSchema()){let S=y.getValueSchema(),x=h;if(this.needsTransform(S))for(let _ in x){if(!ke(x,_))continue;if(_==="__proto__")_r(x);x[_]=this._read(S,x[_])}return x}}if(y.isBlobSchema()&&typeof h==="string")return To(h);let w=y.getMergedTraits().mediaType;if(y.isStringSchema()&&typeof h==="string"&&w){if(w==="application/json"||w.endsWith("+json"))return un.from(h);return h}if(y.isTimestampSchema()&&h!=null)switch(Tr(y,this.settings)){case 5:return Cp(h);case 6:return Ip(h);case 7:return Ap(h);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",h),new Date(h)}if(y.isBigIntegerSchema()&&(typeof h==="number"||typeof h==="string"))return BigInt(h);if(y.isBigDecimalSchema()&&h!=null){if(h instanceof He)return h;let S=h;if(S.type==="bigDecimal"&&"string"in S)return new He(S.string,S.type);return new He(String(h),"bigDecimal")}if(y.isNumericSchema()&&typeof h==="string"){switch(h){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return h}if(y.isDocumentSchema()){if(g)if(Array.isArray(h))for(let S=0;S<h.length;++S){let x=h[S];if(!(x instanceof He))h[S]=this._read(y,x)}else{let S=h;for(let x in S){if(!ke(S,x))continue;if(x==="__proto__")_r(S);let _=S[x];if(!(_ instanceof He))S[x]=this._read(y,_)}}}return h}_readStruct(f,h){let g=f.isUnionSchema(),y={},w,S=typeof h.__type==="string",{jsonName:x}=this.settings;if(x&&S)w={};let _;if(g)_=new Bc(h,y);for(let[A,P]of f.structIterator()){let D=A;if(x){if(D=P.getMergedTraits().jsonName??D,S)w[D]=A}if(g)_.mark(D);if(h[D]!=null)y[A]=this._read(P,h[D])}if(g)_.writeUnknown();else if(S)for(let A in h){if(!ke(h,A))continue;let P=h[A],D=x?w[A]??A:A;if(!(D in y))y[D]=P}return y}needsTransform(f){if(f.isBlobSchema()||f.isTimestampSchema()||f.isBigIntegerSchema()||f.isBigDecimalSchema()||f.isNumericSchema())return!0;if(f.isDocumentSchema()||f.isStructSchema()||f.isListSchema()||f.isMapSchema())return!0;if(f.isStringSchema()&&f.getMergedTraits().mediaType)return!0;return!1}}class Io extends Uint8Array{string=null;static allocUnsafe(f){if(typeof Buffer==="function"){let h=Buffer.allocUnsafe(f);return new Io(h.buffer,h.byteOffset,h.byteLength)}return new Io(f)}toString(){return this.s()}valueOf(){return this.s()}includes(f,h){if(typeof f==="string")return this.s().includes(f,h);return Uint8Array.prototype.includes.call(this,f,h)}indexOf(f,h){if(typeof f==="string")return this.s().indexOf(f,h);return Uint8Array.prototype.indexOf.call(this,f,h)}lastIndexOf(f,h){if(typeof f==="string")return this.s().lastIndexOf(f,h);let g=Uint8Array.prototype.lastIndexOf;if(h!==void 0)return g.call(this,f,h);return g.call(this,f)}startsWith(f,h){return this.s().startsWith(f,h)}endsWith(f,h){return this.s().endsWith(f,h)}match(f){return this.s().match(f)}replace(f,h){return this.s().replace(f,h)}search(f){return this.s().search(f)}split(f,h){return this.s().split(f,h)}substring(f,h){return this.s().substring(f,h)}trim(){return this.s().trim()}trimStart(){return this.s().trimStart()}trimEnd(){return this.s().trimEnd()}charAt(f){return this.s().charAt(f)}charCodeAt(f){return this.s().charCodeAt(f)}padStart(f,h){return this.s().padStart(f,h)}padEnd(f,h){return this.s().padEnd(f,h)}repeat(f){return this.s().repeat(f)}toUpperCase(){return this.s().toUpperCase()}toLowerCase(){return this.s().toLowerCase()}s(){if(this.string==null){let f=Date.now();if(f>Sp+60000)console.warn("@aws-sdk/core/protocols - WARN - JsonCodec2: you have called a string method on a Uint8Array request body. It has been automatically converted to string. In a future version this will throw an error."),Sp=f;this.string=Ro(this)}return this.string}}var Sp=0,bo=new TextEncoder,wp=123,Ep=125,wO=91,EO=93,an=34,xo=58,_o=44,bp=92,bO=new Uint8Array([116,114,117,101]),xO=new Uint8Array([102,97,108,115,101]),_O=new Uint8Array([110,117,108,108]),Ot=Array(128).fill(null);Ot[8]="b";Ot[9]="t";Ot[10]="n";Ot[12]="f";Ot[13]="r";Ot[34]='"';Ot[92]="\\";for(let f=0;f<32;f++)if(Ot[f]===null)Ot[f]="u00"+f.toString(16).padStart(2,"0");var xp=2048;function kc(f){return Io.allocUnsafe(f)}class No extends Ar{settings;json;i=0;rootSchema;rawValue;passthrough=!1;constructor(f){super();this.settings=f,this.json=kc(xp)}write(f,h){if(this.i=0,this.rawValue=h,this.rootSchema=Ie.of(f),this.passthrough=this.rootSchema.isBlobSchema()||this.rootSchema.isStringSchema(),!this.passthrough)this.writeValue(this.rootSchema,h,void 0)}writeDiscriminatedDocument(f,h){this.i=0,this.rootSchema=Ie.of(f);let g=this.rootSchema;if(g.isStructSchema()&&h!=null&&typeof h==="object"){this.writeValue(g,h,void 0);let y=`"__type":"${g.getName(!0)??"Unknown"}",`,w=y.length;this.ensure(w),this.json.copyWithin(1+w,1,this.i),bo.encodeInto(y,this.json.subarray(1)),this.i+=w}else this.writeValue(g,h,void 0)}flush(){this.rootSchema=void 0;let f=this.i;this.i=0;let h=this.rawValue;if(this.rawValue=void 0,f===0)return h;let g=this.json.subarray(0,f);return this.json=kc(xp),g}ensure(f){let{i:h,json:g}=this;if(h+f>g.length){let y=g.length*2;while(y<h+f)y*=2;let w=kc(y);w.set(this.json),this.json=w}}writeAscii(f){let h=f.length;this.ensure(h);let{i:g,json:y}=this;for(let w=0;w<h;++w)y[g]=f.charCodeAt(w),g+=1;this.i=g}writeAsciiQuoted(f){let h=f.length;this.ensure(h+4);let{json:g,i:y}=this;g[y++]=an;for(let w=0;w<h;++w)g[y++]=f.charCodeAt(w);g[y++]=an,this.i=y}writeJsonString(f){let h=f.length;this.ensure(h*3+2),this.json[this.i++]=an;for(let g=0;g<h;++g){let y=f.charCodeAt(g);if(y>34&&y<92)this.json[this.i++]=y;else if(y<128){let w=Ot[y];if(w!==null){this.ensure(w.length+1+(h-g-1)*3+1),this.json[this.i++]=bp;for(let S=0;S<w.length;S++)this.json[this.i++]=w.charCodeAt(S)}else this.json[this.i++]=y}else if(y>=55296&&y<=56319){let w=g+1<h?f.charCodeAt(g+1):0;if(w>=56320&&w<=57343){this.ensure(4);let{written:S}=bo.encodeInto(f.substring(g,g+2),this.json.subarray(this.i));this.i+=S,++g}else this.ensure(6+(h-g-1)*3+1),this.writeUnicodeEscape(y)}else if(y>=56320&&y<=57343)this.ensure(6+(h-g-1)*3+1),this.writeUnicodeEscape(y);else{let{i:w,json:S}=this;if(y<2048)S[w++]=192|y>>6,S[w++]=128|y&63;else S[w++]=224|y>>12,S[w++]=128|y>>6&63,S[w++]=128|y&63;this.i=w}}this.json[this.i++]=an}writeUnicodeEscape(f){let{json:h,i:g}=this;h[g++]=bp,h[g++]=117;let y=f.toString(16).padStart(4,"0");for(let w=0;w<4;++w)h[g++]=y.charCodeAt(w);this.i=g}static B64=(()=>{let h=new Uint8Array(64);for(let g=0;g<64;++g)h[g]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(g);return h})();writeBase64(f){let h=Math.ceil(f.length/3)*4;this.ensure(h+2);let g=this.json,y=No.B64,w=this.i;g[w++]=an;let S=f.length,x=S%3,_=S-x;for(let A=0;A<_;A+=3){let P=f[A],D=f[A+1],U=f[A+2];g[w++]=y[P>>2],g[w++]=y[(P&3)<<4|D>>4],g[w++]=y[(D&15)<<2|U>>6],g[w++]=y[U&63]}if(x===2){let A=f[_],P=f[_+1];g[w++]=y[A>>2],g[w++]=y[(A&3)<<4|P>>4],g[w++]=y[(P&15)<<2],g[w++]=61}else if(x===1){let A=f[_];g[w++]=y[A>>2],g[w++]=y[(A&3)<<4],g[w++]=61,g[w++]=61}g[w++]=an,this.i=w}writeValue(f,h,g){if(h==null){if(g?.isStructSchema()){if(h===void 0){if(Ie.of(f).isIdempotencyToken()){this.writeAsciiQuoted(Oc());return}}return}this.ensure(4),this.json.set(_O,this.i),this.i+=4;return}let y=Ie.of(f),w=typeof h==="object";if(y.isStringSchema()){let S=y.getMergedTraits().mediaType;if(S){if(S==="application/json"||S.endsWith("+json")){this.writeJsonString(un.from(h).toString());return}}}if(this.settings.bigNumberAsString&&h!=null&&(y.isBigIntegerSchema()||y.isBigDecimalSchema())){let S=h instanceof He?h.string:String(h);this.writeAsciiQuoted(S);return}if(w){if(y.isStructSchema()){this.writeStruct(y,h);return}if(Array.isArray(h)&&(y.isListSchema()||y.isDocumentSchema())){this.writeList(y,h,y.isDocumentSchema());return}if(y.isMapSchema()){this.writeMap(y,h,!1);return}if(h instanceof Uint8Array&&(y.isBlobSchema()||y.isDocumentSchema())){this.writeBase64(h);return}if(h instanceof Date&&(y.isTimestampSchema()||y.isDocumentSchema())){this.writeTimestamp(y,h);return}if(h instanceof He){this.writeAscii(h.string);return}if(y.isDocumentSchema()){if(Array.isArray(h))this.writeList(y,h,!0);else this.writeMap(y,h,!0);return}let S=JSON.stringify(h);this.writeAscii(S);return}if(typeof h==="string"){if(y.isBlobSchema()){let S=(this.serdeContext?.base64Encoder??cn)(h);this.writeAsciiQuoted(S);return}this.writeJsonString(h);return}if(typeof h==="number"){if(Math.abs(h)===1/0||Number.isNaN(h)){this.writeAsciiQuoted(String(h));return}let S=String(h);this.writeAscii(S);return}if(typeof h==="boolean"){this.ensure(5);let{i:S,json:x}=this;if(h)x.set(bO,S),S+=4;else x.set(xO,S),S+=5;this.i=S;return}if(typeof h==="bigint"){this.writeAscii(h.toString());return}this.writeAscii(String(h))}writeStruct(f,h){this.ensure(2),this.json[this.i++]=wp;let g=!1,y=typeof h.__type==="string",w;if(y)w=new Set;for(let[S,x]of f.structIterator()){let _=h[S];if(_==null&&!x.isIdempotencyToken())continue;if(g)this.ensure(1),this.json[this.i++]=_o;g=!0;let A=this.settings.jsonName?x.getMergedTraits().jsonName??S:S;if(w)w.add(S),w.add(A);this.writeAsciiQuoted(A),this.json[this.i++]=xo,this.writeValue(x,_,f)}if(!g&&f.isUnionSchema()){let{$unknown:S}=h;if(Array.isArray(S)){let[x,_]=S;this.writeAsciiQuoted(x),this.ensure(1),this.json[this.i++]=xo,this.writeValue(15,_,f)}}else if(y)for(let S in h){if(w.has(S))continue;w.add(S);let x=h[S];if(g)this.ensure(1),this.json[this.i++]=_o;g=!0,this.writeAsciiQuoted(S),this.ensure(1),this.json[this.i++]=xo,this.writeValue(15,x,void 0)}this.ensure(1),this.json[this.i++]=Ep}writeList(f,h,g){let y=!!f.getMergedTraits().sparse,w=f.getValueSchema();if(!g){if(w.isStringSchema()||w.isNumericSchema()||w.isBooleanSchema()){let x=!1;for(let A=0;A<h.length;++A){let P=h[A];if(Number.isNaN(P)||P===1/0||P===-1/0||P==null&&!y){x=!0;break}}let _;if(!x)_=JSON.stringify(h);else{let A=[];for(let P=0;P<h.length;++P){let D=h[P];if(D==null&&!y)continue;if(Number.isNaN(D)||D===1/0||D===-1/0)A.push(String(D));else A.push(D)}_=JSON.stringify(A)}this.ensure(_.length*3),this.i+=bo.encodeInto(_,this.json.subarray(this.i)).written;return}}this.ensure(2),this.json[this.i++]=wO;let S=!1;for(let x=0;x<h.length;++x){let _=h[x];if(g?_===void 0:_==null&&!y)continue;if(S)this.ensure(1),this.json[this.i++]=_o;this.writeValue(w,_,void 0),S=!0}this.ensure(1),this.json[this.i++]=EO}writeMap(f,h,g){let y=!!f.getMergedTraits().sparse,w=f.getValueSchema();if(!g){if(w.isStringSchema()||w.isNumericSchema()||w.isBooleanSchema()){let x;for(let A in h){if(!ke(h,A))continue;let P=h[A];if(Number.isNaN(P)||P===1/0||P===-1/0)(x??={})[A]=P,h[A]=String(P);else if(P===null&&!y)(x??={})[A]=null,h[A]=void 0}let _=JSON.stringify(h);if(x)Object.assign(h,x);this.ensure(_.length*3),this.i+=bo.encodeInto(_,this.json.subarray(this.i)).written;return}}this.ensure(2),this.json[this.i++]=wp;let S=!0;for(let x in h){if(!ke(h,x))continue;let _=h[x];if(g?_===void 0:_==null&&!y)continue;if(!S)this.ensure(1),this.json[this.i++]=_o;S=!1,this.writeJsonString(x),this.ensure(1),this.json[this.i++]=xo,this.writeValue(w,_,void 0)}this.ensure(1),this.json[this.i++]=Ep}writeTimestamp(f,h){switch(Tr(f,this.settings)){case 5:{let y=h.toISOString().replace(".000Z","Z");this.writeAsciiQuoted(y);return}case 6:{this.writeAsciiQuoted(Pc(h));return}case 7:{let y=String(h.getTime()/1000);this.writeAscii(y);return}default:{let y=String(h.getTime()/1000);this.writeAscii(y);return}}}}class qc extends Ar{settings;constructor(f){super();this.settings=f}createSerializer(){let f=new No(this.settings);return f.setSerdeContext(this.serdeContext),f}createDeserializer(){let f=new Hc(this.settings);return f.setSerdeContext(this.serdeContext),f}}class Hp extends Dc{codec=new qc({timestampFormat:{useTrait:!1,default:7},jsonName:!1,bigNumberAsString:!0});serializer=this.codec.createSerializer();deserializer=this.codec.createDeserializer();getShapeId(){return"smithy.protocols#rpcv2Json"}getPayloadCodec(){return this.codec}getSmithyProtocolHeaderValue(){return"rpc-v2-json"}applyEmptyBody(f){if(!f.body)f.body="{}"}async handleError(f,h,g,y,w){let S=Lp(g,y)??"Unknown",x={$metadata:w,$fault:g.statusCode<=500?"client":"server"},_=this.options.defaultNamespace;if(S.includes("#"))[_]=S.split("#");let A=this.compositeErrorRegistry,P=Nc.for(_);A.copyFrom(P);let D;try{D=A.getSchema(S)}catch(q){if(y.Message)y.message=y.Message;let V=Nc.for("smithy.ts.sdk.synthetic."+_);A.copyFrom(V);let W=A.getBaseException();if(W){let G=A.getErrorCtor(W);throw Object.assign(new G({name:S}),x,y)}throw Object.assign(Error(S),x,y)}let U=Ie.of(D),B=A.getErrorCtor(D),z=y.message??y.Message??"Unknown",k=new B({}),R={},N=this.codec.createDeserializer();for(let[q,V]of U.structIterator())if(y[q]!=null)R[q]=N.readObject(V,y[q]);throw Object.assign(k,x,{$fault:U.getMergedTraits().error,message:z},R)}getDefaultContentType(){return"application/json"}}class jc extends Ar{settings;constructor(f){super();this.settings=f}async read(f,h){let g=zc(f)?Lc:void 0;return this._read(f,typeof h==="string"?JSON.parse(h,g):await ko(h,this.serdeContext,f))}readObject(f,h){return this._read(f,h)}_read(f,h){let g=h!==null&&typeof h==="object",y=Ie.of(f);if(g){if(y.isStructSchema()){let S=h,x=y.isUnionSchema(),_={},A=void 0,{jsonName:P}=this.settings;if(P)A={};let D;if(x)D=new Bc(S,_);for(let[U,B]of y.structIterator()){let z=U;if(P)z=B.getMergedTraits().jsonName??z,A[z]=U;if(x)D.mark(z);if(S[z]!=null)_[U]=this._read(B,S[z])}if(x)D.writeUnknown();else if(typeof S.__type==="string")for(let U in S){if(!ke(S,U))continue;let B=S[U],z=P?A[U]??U:U;if(!(z in _))_[z]=B}return _}if(Array.isArray(h)&&y.isListSchema()){let S=y.getValueSchema(),x=[];for(let _ of h)x.push(this._read(S,_));return x}if(y.isMapSchema()){let S=y.getValueSchema(),x={};for(let _ in h){if(!ke(h,_))continue;if(_==="__proto__")_r(x);x[_]=this._read(S,h[_])}return x}}if(y.isBlobSchema()&&typeof h==="string")return To(h);let w=y.getMergedTraits().mediaType;if(y.isStringSchema()&&typeof h==="string"&&w){if(w==="application/json"||w.endsWith("+json"))return un.from(h);return h}if(y.isTimestampSchema()&&h!=null)switch(Tr(y,this.settings)){case 5:return Cp(h);case 6:return Ip(h);case 7:return Ap(h);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",h),new Date(h)}if(y.isBigIntegerSchema()&&(typeof h==="number"||typeof h==="string"))return BigInt(h);if(y.isBigDecimalSchema()&&h!=null){if(h instanceof He)return h;let S=h;if(S.type==="bigDecimal"&&"string"in S)return new He(S.string,S.type);return new He(String(h),"bigDecimal")}if(y.isNumericSchema()&&typeof h==="string"){switch(h){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return h}if(y.isDocumentSchema())if(g){let S=Array.isArray(h)?[]:{};for(let x in h){if(!ke(h,x))continue;if(x==="__proto__")_r(S);let _=h[x];if(_ instanceof He)S[x]=_;else S[x]=this._read(y,_)}return S}else return structuredClone(h);return h}}var _p=String.fromCharCode(925);class qp{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(f,h)=>{if(h instanceof He){let g=`${_p+"nv"+this.counter++}_`+h.string;return this.values.set(`"${g}"`,h.string),g}if(typeof h==="bigint"){let g=h.toString(),y=`${_p+"b"+this.counter++}_`+g;return this.values.set(`"${y}"`,g),y}return h}}replaceInJson(f){if(this.stage===0)throw Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return f;for(let[h,g]of this.values)f=f.replace(h,g);return f}}class Vc extends Ar{settings;buffer;useReplacer=!1;rootSchema;constructor(f){super();this.settings=f}write(f,h){this.rootSchema=Ie.of(f),this.buffer=this._write(this.rootSchema,h)}flush(){let{rootSchema:f,useReplacer:h}=this;if(this.rootSchema=void 0,this.useReplacer=!1,f?.isStructSchema()||f?.isDocumentSchema()){if(!h)return JSON.stringify(this.buffer);let g=new qp;return g.replaceInJson(JSON.stringify(this.buffer,g.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(f,h){if(this.write(f,h),typeof this.buffer==="object")this.buffer.__type=Ie.of(f).getName(!0)}_write(f,h,g){let y=h!==null&&typeof h==="object",w=Ie.of(f);if(y){if(w.isStructSchema()){let S=h,x={},{jsonName:_}=this.settings,A=void 0;if(_)A={};let P=0;for(let[D,U]of w.structIterator()){let B=this._write(U,S[D],w);if(B!==void 0){let z=D;if(_)z=U.getMergedTraits().jsonName??D,A[D]=z;x[z]=B,P++}}if(w.isUnionSchema()&&P===0){let{$unknown:D}=S;if(Array.isArray(D)){let[U,B]=D;if(U==="__proto__")_r(x);x[U]=this._write(15,B)}}else if(typeof S.__type==="string")for(let D in S){if(!ke(S,D))continue;let U=S[D],B=_?A[D]??D:D;if(!(B in x))x[B]=this._write(15,U)}return x}if(Array.isArray(h)&&w.isListSchema()){let S=w.getValueSchema(),x=[],_=!!w.getMergedTraits().sparse;for(let A of h)if(_||A!=null)x.push(this._write(S,A));return x}if(w.isMapSchema()){let S=w.getValueSchema(),x={},_=!!w.getMergedTraits().sparse;for(let A in h){if(!ke(h,A))continue;let P=h[A];if(_||P!=null){if(A==="__proto__")_r(x);x[A]=this._write(S,P)}}return x}if(h instanceof Uint8Array&&w.isBlobSchema()){if(w===this.rootSchema)return h;return(this.serdeContext?.base64Encoder??cn)(h)}if(h instanceof Date&&(w.isTimestampSchema()||w.isDocumentSchema()))switch(Tr(w,this.settings)){case 5:return h.toISOString().replace(".000Z","Z");case 6:return Pc(h);case 7:return h.getTime()/1000;default:return console.warn("Missing timestamp format, using epoch seconds",h),h.getTime()/1000}if(h instanceof He)this.useReplacer=!0}if(h===null&&g?.isStructSchema())return;if(w.isStringSchema()){if(typeof h>"u"&&w.isIdempotencyToken())return Oc();let S=w.getMergedTraits().mediaType;if(h!=null&&S){if(S==="application/json"||S.endsWith("+json"))return un.from(h)}return h}if(typeof h==="number"){if(Math.abs(h)===1/0||isNaN(h))return String(h);return h}if(typeof h==="string"&&w.isBlobSchema()){if(w===this.rootSchema)return h;return(this.serdeContext?.base64Encoder??cn)(h)}if(typeof h==="bigint")this.useReplacer=!0;if(w.isDocumentSchema())if(y){if(h instanceof Uint8Array)return(this.serdeContext?.base64Encoder??cn)(h);let S=Array.isArray(h)?[]:{};for(let x in h){if(!ke(h,x))continue;let _=h[x];if(x==="__proto__")_r(S);if(_ instanceof He)this.useReplacer=!0,S[x]=_;else S[x]=this._write(w,_)}return S}else return structuredClone(h);return h}}class jp extends Ar{settings;constructor(f){super();this.settings=f}createSerializer(){let f=new Vc(this.settings);return f.setSerdeContext(this.serdeContext),f}createDeserializer(){let f=new jc(this.settings);return f.setSerdeContext(this.serdeContext),f}}TO.AbstractRpcV2Protocol=Dc;TO.Field=Dp;TO.Fields=Up;TO.FromStringShapeDeserializer=Fc;TO.HttpBindingProtocol=Np;TO.HttpInterceptingShapeDeserializer=Pp;TO.HttpInterceptingShapeSerializer=Mp;TO.HttpProtocol=vo;TO.JsonCodec=jp;TO.JsonCodec2=qc;TO.JsonShapeDeserializer=jc;TO.JsonShapeDeserializer2=Hc;TO.JsonShapeSerializer=Vc;TO.JsonShapeSerializer2=No;TO.RequestBuilder=Uc;TO.RpcProtocol=Mc;TO.SerdeContext=ln;TO.SmithyRpcV2JsonProtocol=Hp;TO.ToStringShapeSerializer=$c;TO.buildQueryString=lO;TO.collectBody=qt;TO.contentLengthMiddleware=Fp;TO.contentLengthMiddlewareOptions=$p;TO.determineTimestampFormat=Tr;TO.escapeUri=ts;TO.escapeUriPath=dO;TO.extendedEncodeURIComponent=rs;TO.getContentLengthPlugin=cO;TO.getHttpHandlerExtensionConfiguration=iO;TO.loadJsonRpcErrorCode=SO;TO.loadRestJsonErrorCode=yO;TO.loadSmithyRpcV2JsonErrorCode=Lp;TO.parseJsonBody=ko;TO.parseJsonErrorBody=gO;TO.requestBuilder=oO;TO.resolveHttpHandlerRuntimeConfig=aO;TO.resolvedPath=Op});var rr=i(function(vP){var{getSmithyContext:Wc,hasOwn:hP}=at();vP.getSmithyContext=Wc;var{HttpRequest:Gc}=Ne(),{requestBuilder:pP}=Ne();vP.requestBuilder=pP;var{HttpApiKeyAuthLocation:Vp}=Jt(),mP=(f,h)=>{if(!h||h.length===0)return f;let g=[];for(let y of h)for(let w of f)if(w.schemeId.split("#")[1]===y)g.push(w);for(let y of f)if(!g.find(({schemeId:w})=>w===y.schemeId))g.push(y);return g};function gP(f){let h=new Map;for(let g of f)h.set(g.schemeId,g);return h}var Kc=(f,h)=>(g,y)=>async(w)=>{let S=f.httpAuthSchemeProvider(await h.httpAuthSchemeParametersProvider(f,y,w.input)),x=f.authSchemePreference?await f.authSchemePreference():[],_=mP(S,x),A=gP(f.httpAuthSchemes),P=Wc(y),D=[];for(let U of _){let B=A.get(U.schemeId);if(!B){D.push(`HttpAuthScheme \`${U.schemeId}\` was not enabled for this service.`);continue}let z=B.identityProvider(await h.identityProviderConfigProvider(f));if(!z){D.push(`HttpAuthScheme \`${U.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:k={},signingProperties:R={}}=U.propertiesExtractor?.(f,y)||{};U.identityProperties=Object.assign(U.identityProperties||{},k),U.signingProperties=Object.assign(U.signingProperties||{},R),P.selectedHttpAuthScheme={httpAuthOption:U,identity:await z(U.identityProperties),signer:B.signer};break}if(!P.selectedHttpAuthScheme)throw Error(D.join(`
17
+ `));return g(w)},Wp={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},yP=(f,{httpAuthSchemeParametersProvider:h,identityProviderConfigProvider:g})=>({applyToStack:(y)=>{y.addRelativeTo(Kc(f,{httpAuthSchemeParametersProvider:h,identityProviderConfigProvider:g}),Wp)}}),Gp={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"serializerMiddleware"},SP=(f,{httpAuthSchemeParametersProvider:h,identityProviderConfigProvider:g})=>({applyToStack:(y)=>{y.addRelativeTo(Kc(f,{httpAuthSchemeParametersProvider:h,identityProviderConfigProvider:g}),Gp)}}),wP=(f)=>(h)=>{throw h},EP=(f,h)=>{},Kp=(f)=>(h,g)=>async(y)=>{if(!Gc.isInstance(y.request))return h(y);let S=Wc(g).selectedHttpAuthScheme;if(!S)throw Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:x={}},identity:_,signer:A}=S,P=await h({...y,request:await A.sign(y.request,_,x)}).catch((A.errorHandler||wP)(x));return(A.successHandler||EP)(P.response,x),P},Jp={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},bP=(f)=>({applyToStack:(h)=>{h.addRelativeTo(Kp(),Jp)}}),xP=(f)=>{if(typeof f==="function")return f;let h=Promise.resolve(f);return()=>h},_P=async(f,h,g,y=(S)=>S,...w)=>{let S=new f(g);return S=y(S)??S,await h.send(S,...w)};function TP(f,h,g,y,w){return async function*(x,_,...A){let P=_,D=x.startingToken??P[g],U=!0,B;while(U){if(P[g]=D,w)P[w]=P[w]??x.pageSize;if(x.client instanceof f)B=await _P(h,x.client,_,x.withCommand,...A);else throw Error(`Invalid client, expected instance of ${f.name}`);yield B;let z=D;D=AP(B,y),U=!!(D&&(!x.stopOnSameToken||D!==z))}return}}var AP=(f,h)=>{let g=f,y=h.split(".");for(let w of y){if(!g||typeof g!=="object")return;g=g[w]}return g};function IP(f,h,g){if(!f.__smithy_context)f.__smithy_context={features:{}};else if(!f.__smithy_context.features)f.__smithy_context.features={};f.__smithy_context.features[h]=g}class Qp{authSchemes=new Map;constructor(f){for(let h in f){if(!hP(f,h))continue;let g=f[h];if(g!==void 0)this.authSchemes.set(h,g)}}getIdentityProvider(f){return this.authSchemes.get(f)}}class Xp{async sign(f,h,g){if(!g)throw Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing");if(!g.name)throw Error("request could not be signed with `apiKey` since the `name` signer property is missing");if(!g.in)throw Error("request could not be signed with `apiKey` since the `in` signer property is missing");if(!h.apiKey)throw Error("request could not be signed with `apiKey` since the `apiKey` is not defined");let y=Gc.clone(f);if(g.in===Vp.QUERY)y.query[g.name]=h.apiKey;else if(g.in===Vp.HEADER)y.headers[g.name]=g.scheme?`${g.scheme} ${h.apiKey}`:h.apiKey;else throw Error("request can only be signed with `apiKey` locations `query` or `header`, but found: `"+g.in+"`");return y}}class Yp{async sign(f,h,g){let y=Gc.clone(f);if(!h.token)throw Error("request could not be signed with `token` since the `token` is not defined");return y.headers.Authorization=`Bearer ${h.token}`,y}}class Zp{async sign(f,h,g){return f}}var em=(f)=>function(g){return rm(g)&&g.expiration.getTime()-Date.now()<f},tm=300000,CP=em(tm),rm=(f)=>f.expiration!==void 0,RP=(f,h,g)=>{if(f===void 0)return;let y=typeof f!=="function"?async()=>Promise.resolve(f):f,w,S,x,_=!1,A=async(P)=>{if(!S)S=y(P);try{w=await S,x=!0,_=!1}finally{S=void 0}return w};if(h===void 0)return async(P)=>{if(!x||P?.forceRefresh)w=await A(P);return w};return async(P)=>{if(!x||P?.forceRefresh)w=await A(P);if(_)return w;if(!g(w))return _=!0,w;if(h(w))return await A(P),w;return w}};vP.DefaultIdentityProviderConfig=Qp;vP.EXPIRATION_MS=tm;vP.HttpApiKeyAuthSigner=Xp;vP.HttpBearerAuthSigner=Yp;vP.NoAuthSigner=Zp;vP.createIsIdentityExpiredFunction=em;vP.createPaginator=TP;vP.doesIdentityRequireRefresh=rm;vP.getHttpAuthSchemeEndpointRuleSetPlugin=yP;vP.getHttpAuthSchemePlugin=SP;vP.getHttpSigningPlugin=bP;vP.httpAuthSchemeEndpointRuleSetMiddlewareOptions=Wp;vP.httpAuthSchemeMiddleware=Kc;vP.httpAuthSchemeMiddlewareOptions=Gp;vP.httpSigningMiddleware=Kp;vP.httpSigningMiddlewareOptions=Jp;vP.isIdentityExpired=CP;vP.memoizeIdentityProvider=RP;vP.normalizeProvider=xP;vP.setFeature=IP});var fn=i(function(x1){var{Readable:YP}=c("node:stream"),{NoOpLogger:ZP,normalizeProvider:nm}=ct(),{HttpResponse:sm,HttpRequest:Po}=Ne(),{parseRfc7231DateTime:e1,v4:om}=Ke(),{hasOwn:t1}=at(),im=(f)=>f?.body instanceof YP||typeof ReadableStream<"u"&&f?.body instanceof ReadableStream,r1=["AccessDeniedException","AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],n1=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],s1=["TimeoutError","RequestTimeout","RequestTimeoutException"],o1=[500,502,503,504],i1=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],a1=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],Yc=(f)=>f?.$retryable!==void 0,am=(f)=>r1.includes(f.name),cm=(f)=>f.$metadata?.clockSkewCorrected,um=(f)=>{let h=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);if(!(f&&f instanceof TypeError))return!1;return h.has(f.message)},ss=(f)=>f.$metadata?.httpStatusCode===429||n1.includes(f.name)||f.$retryable?.throttling==!0,os=(f,h=0)=>f?.name!=="AbortError"&&(Yc(f)||cm(f)||f.name==="InvalidSignatureException"&&f.message?.includes("Signature expired")||s1.includes(f.name)||i1.includes(f?.code||"")||a1.includes(f?.code||"")||o1.includes(f.$metadata?.httpStatusCode||0)||um(f)||lm(f)||f.cause!==void 0&&h<=10&&os(f.cause,h+1)),dm=(f)=>{if(f.$metadata?.httpStatusCode!==void 0){let h=f.$metadata.httpStatusCode;if(500<=h&&h<=599&&!os(f))return!0;return!1}return!1};function lm(f){return f.code==="ERR_HTTP2_STREAM_ERROR"&&f.message.includes("NGHTTP2_REFUSED_STREAM")}var fm=100,Do=20000,hm=500,Mo=500,pm=5,mm=10,Zc=1,Uo="amz-sdk-invocation-id",Fo="amz-sdk-request";function gm(f,h){if(!sm.isInstance(f))return;for(let g in f.headers){if(!t1(f.headers,g))continue;let y=g.toLowerCase();if(y==="retry-after"){let w=f.headers[g],S=NaN;if(w.endsWith("GMT"))try{S=(e1(w).getTime()-Date.now())/1000}catch(x){h?.trace?.("Failed to parse retry-after header"),h?.trace?.(x)}else if(w.match(/ GMT, ((\d+)|(\d+\.\d+))$/))S=Number(w.match(/ GMT, ([\d.]+)$/)?.[1]);else if(w.match(/^((\d+)|(\d+\.\d+))$/))S=Number(w);else if(Date.parse(w)>=Date.now())S=(Date.parse(w)-Date.now())/1000;if(isNaN(S))return;return new Date(Date.now()+S*1000)}else if(y==="x-amz-retry-after"){let w=f.headers[g],S=Number(w);if(isNaN(S)){h?.trace?.(`Failed to parse x-amz-retry-after=${w}`);return}return new Date(Date.now()+S)}}}function c1(f,h){return gm(f,h)}var ym=(f)=>{if(f instanceof Error)return f;if(f instanceof Object)return Object.assign(Error(),f);if(typeof f==="string")return Error(f);return Error(`AWS SDK error wrapper for ${f}`)};function Sm(f){return(h)=>(g,y)=>async(w)=>{let S=await h.retryStrategy(),x=await h.maxAttempts();if(d1(S)){S=S;let _=await S.acquireInitialRetryToken((y.partition_id??"")+(y.__retryLongPoll?":longpoll":"")),A=Error(),P=0,D=0,{request:U}=w,B=Po.isInstance(U);if(B)U.headers[Uo]=om();while(!0)try{if(B)U.headers[Fo]=`attempt=${P+1}; max=${x}`;let{response:z,output:k}=await g(w);return S.recordSuccess(_),k.$metadata.attempts=P+1,k.$metadata.totalRetryDelay=D,{response:z,output:k}}catch(z){let k=l1(z,h.logger);if(A=ym(z),B&&f(U))throw(y.logger instanceof ZP?console:y.logger)?.warn("An error was encountered in a non-retryable streaming request."),A;try{_=await S.refreshRetryTokenForRetry(_,k)}catch(N){if(!A.$metadata)A.$metadata={};throw A.$metadata.attempts=P+1,A.$metadata.totalRetryDelay=D,A}P=_.getRetryCount();let R=_.getRetryDelay();if(D+=(_?.$retryLog?.acquisitionDelay??0)+R,R>0)await u1(R)}}else{if(S=S,S?.mode)y.userAgent=[...y.userAgent||[],["cfg/retry-mode",S.mode]];return S.retry(g,w)}}}var u1=(f)=>new Promise((h)=>setTimeout(h,f)),d1=(f)=>typeof f.acquireInitialRetryToken<"u"&&typeof f.refreshRetryTokenForRetry<"u"&&typeof f.recordSuccess<"u",l1=(f,h)=>{let g={error:f,errorType:f1(f)},y=gm(f.$response,h);if(y)g.retryAfterHint=y;return g},f1=(f)=>{if(ss(f))return"THROTTLING";if(os(f))return"TRANSIENT";if(dm(f))return"SERVER_ERROR";return"CLIENT_ERROR"},wm={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function h1(f){let h=Sm(f);return(g)=>({applyToStack:(y)=>{y.add(h(g),wm)}})}class is{static setTimeoutFn=(f,h)=>setTimeout(f,h);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(f){this.beta=f?.beta??0.7,this.minCapacity=f?.minCapacity??1,this.minFillRate=f?.minFillRate??0.5,this.scaleConstant=f?.scaleConstant??0.4,this.smooth=f?.smooth??0.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(f){let h;this.updateMeasuredRate();let g=f;if(g?.errorType==="THROTTLING"||ss(g?.error??f)){let S=!this.enabled?this.measuredTxRate:Math.min(this.measuredTxRate,this.fillRate);this.lastMaxRate=S,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),h=this.cubicThrottle(S),this.enableTokenBucket()}else this.calculateTimeWindow(),h=this.cubicSuccess(this.getCurrentTimeInSeconds());let w=Math.min(h,2*this.measuredTxRate);this.updateTokenBucketRate(w)}getCurrentTimeInSeconds(){return Date.now()/1000}async acquireTokenBucket(f){if(!this.enabled)return;this.refillTokenBucket();while(f>this.availableTokens){let h=(f-this.availableTokens)/this.fillRate*1000;await new Promise((g)=>is.setTimeoutFn(g,h)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-f}refillTokenBucket(){let f=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=f;return}let h=(f-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+h),this.lastTimestamp=f}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,0.3333333333333333))}cubicThrottle(f){return this.getPrecise(f*this.beta)}cubicSuccess(f){return this.getPrecise(this.scaleConstant*Math.pow(f-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(f){this.refillTokenBucket(),this.fillRate=Math.max(f,this.minFillRate),this.maxCapacity=Math.max(f,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){let f=this.getCurrentTimeInSeconds(),h=Math.floor(f*2)/2;if(this.requestCount++,h>this.lastTxRateBucket){let g=this.requestCount/(h-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(g*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=h}}getPrecise(f){return parseFloat(f.toFixed(8))}}class Oe{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return Oe.v2026?50:100}static throttlingDelay(){return Oe.v2026?1000:500}static cost(){return Oe.v2026?14:5}static throttlingCost(){return Oe.v2026?5:10}static modifiedCostType(){return Oe.v2026?"THROTTLING":"TRANSIENT"}}class Em{x=Oe.delay();computeNextBackoffDelay(f){let h=Math.random(),g=2,y=h*Math.min(this.x*2**f,Do);return Math.floor(y)}setDelayBase(f){this.x=f}}class Jc{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(f,h,g,y){this.delay=f,this.count=h,this.cost=g,this.longPoll=y}getRetryCount(){return this.count}getRetryDelay(){return Math.min(Do,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var jt;(function(f){f.STANDARD="standard",f.ADAPTIVE="adaptive"})(jt||(jt={}));var Ir=3,bm=jt.STANDARD,Oo={incompatible:1,attempts:2,capacity:3},ns=class{mode=jt.STANDARD;retryBackoffStrategy;capacity=Mo;maxAttemptsProvider;baseDelay;constructor(h){if(typeof h==="number")this.maxAttemptsProvider=async()=>h;else if(typeof h==="function")this.maxAttemptsProvider=h;else if(h&&typeof h==="object")this.maxAttemptsProvider=async()=>h.maxAttempts,this.baseDelay=h.baseDelay,this.retryBackoffStrategy=h.backoff;this.maxAttemptsProvider??=async()=>Ir,this.baseDelay??=Oe.delay(),this.retryBackoffStrategy??=new Em}async acquireInitialRetryToken(h){return new Jc(Oe.delay(),0,void 0,Oe.v2026&&h.includes(":longpoll"))}async refreshRetryTokenForRetry(h,g){let y=await this.getMaxAttempts(),w=this.retryCode(h,g,y),S=w===0,x=h.isLongPoll?.();if(S||x){let _=g.errorType;this.retryBackoffStrategy.setDelayBase(_==="THROTTLING"?Oe.throttlingDelay():this.baseDelay);let A=this.retryBackoffStrategy.computeNextBackoffDelay(h.getRetryCount()),P=A;if(g.retryAfterHint instanceof Date)P=Math.max(A,Math.min(g.retryAfterHint.getTime()-Date.now(),A+5000));if(!S){let D=Oe.v2026&&w===Oo.capacity&&x?P:0;if(D>0)await new Promise((U)=>setTimeout(U,D))}else{let D=this.getCapacityCost(_);this.capacity-=D;let U=new Jc(0,h.getRetryCount()+1,D,h.isLongPoll?.()??!1);return await new Promise((B)=>setTimeout(B,P)),U.$retryLog.acquisitionDelay=P,U}}throw Error("No retry token available")}recordSuccess(h){this.capacity=Math.min(Mo,this.capacity+(h.getRetryCost()??Zc))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(h){return console.warn(`Max attempts provider could not resolve. Using default of ${Ir}`),Ir}}retryCode(h,g,y){let w=h.getRetryCount()+1,S=this.isRetryableError(g.errorType)?0:Oo.incompatible,x=w<y?0:Oo.attempts,_=this.capacity>=this.getCapacityCost(g.errorType)?0:Oo.capacity;return S||x||_}getCapacityCost(h){return h===Oe.modifiedCostType()?Oe.throttlingCost():Oe.cost()}isRetryableError(h){return h==="THROTTLING"||h==="TRANSIENT"}},xm=class{mode=jt.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(h,g){let{rateLimiter:y}=g??{};this.rateLimiter=y??new is,this.standardRetryStrategy=g?new ns({maxAttempts:typeof h==="number"?h:3,...g}):new ns(h)}async acquireInitialRetryToken(h){let g=await this.standardRetryStrategy.acquireInitialRetryToken(h);return await this.rateLimiter.getSendToken(),g}async refreshRetryTokenForRetry(h,g){this.rateLimiter.updateClientSendingRate(g);let y=await this.standardRetryStrategy.refreshRetryTokenForRetry(h,g);return await this.rateLimiter.getSendToken(),y}recordSuccess(h){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(h)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}};class _m extends ns{computeNextBackoffDelay;constructor(f,h=Oe.delay()){super(typeof f==="function"?f:async()=>f);if(typeof h==="number")this.computeNextBackoffDelay=()=>h;else this.computeNextBackoffDelay=h;this.retryBackoffStrategy.computeNextBackoffDelay=(g)=>{let y=g+1;return this.computeNextBackoffDelay(y)}}}var p1=(f,h)=>{let g=f,y=Zc,w=pm,S=mm,x=f,_=(U)=>U.name==="TimeoutError"?S:w,A=(U)=>_(U)<=x;return Object.freeze({hasRetryTokens:A,retrieveRetryTokens:(U)=>{if(!A(U))throw Error("No retry token available");let B=_(U);return x-=B,B},releaseRetryTokens:(U)=>{x+=U??y,x=Math.min(x,g)}})},Tm=(f,h)=>Math.floor(Math.min(Do,Math.random()*2**h*f)),Am=(f)=>{if(!f)return!1;return Yc(f)||am(f)||ss(f)||os(f)};class eu{maxAttemptsProvider;retryDecider;delayDecider;retryQuota;mode=jt.STANDARD;constructor(f,h){this.maxAttemptsProvider=f,this.retryDecider=h?.retryDecider??Am,this.delayDecider=h?.delayDecider??Tm,this.retryQuota=h?.retryQuota??p1(Mo)}shouldRetry(f,h,g){return h<g&&this.retryDecider(f)&&this.retryQuota.hasRetryTokens(f)}async getMaxAttempts(){let f;try{f=await this.maxAttemptsProvider()}catch(h){f=Ir}return f}async retry(f,h,g){let y,w=0,S=0,x=await this.getMaxAttempts(),{request:_}=h;if(Po.isInstance(_))_.headers[Uo]=om();while(!0)try{if(Po.isInstance(_))_.headers[Fo]=`attempt=${w+1}; max=${x}`;if(g?.beforeRequest)await g.beforeRequest();let{response:A,output:P}=await f(h);if(g?.afterRequest)g.afterRequest(A);return this.retryQuota.releaseRetryTokens(y),P.$metadata.attempts=w+1,P.$metadata.totalRetryDelay=S,{response:A,output:P}}catch(A){let P=ym(A);if(w++,this.shouldRetry(P,w,x)){y=this.retryQuota.retrieveRetryTokens(P);let D=this.delayDecider(ss(P)?hm:fm,w),U=m1(P.$response),B=Math.max(U||0,D);S+=B,await new Promise((z)=>setTimeout(z,B));continue}if(!P.$metadata)P.$metadata={};throw P.$metadata.attempts=w,P.$metadata.totalRetryDelay=S,P}}}var m1=(f)=>{if(!sm.isInstance(f))return;let h=Object.keys(f.headers).find((S)=>S.toLowerCase()==="retry-after");if(!h)return;let g=f.headers[h],y=Number(g);if(!Number.isNaN(y))return Math.min(y*1000,20000);let w=new Date(g);return Math.min(w.getTime()-Date.now(),20000)};class Im extends eu{rateLimiter;constructor(f,h){let{rateLimiter:g,...y}=h??{};super(f,y);this.rateLimiter=g??new is,this.mode=jt.ADAPTIVE}async retry(f,h){return super.retry(f,h,{beforeRequest:async()=>this.rateLimiter.getSendToken(),afterRequest:(g)=>{this.rateLimiter.updateClientSendingRate(g)}})}}var Qc="AWS_MAX_ATTEMPTS",Xc="max_attempts",g1={environmentVariableSelector:(f)=>{let h=f[Qc];if(!h)return;let g=parseInt(h);if(Number.isNaN(g))throw Error(`Environment variable ${Qc} mast be a number, got "${h}"`);return g},configFileSelector:(f)=>{let h=f[Xc];if(!h)return;let g=parseInt(h);if(Number.isNaN(g))throw Error(`Shared config file entry ${Xc} mast be a number, got "${h}"`);return g},default:Ir},y1=(f,h)=>{let{retryStrategy:g,retryMode:y}=f,{defaultMaxAttempts:w=Ir,defaultBaseDelay:S=Oe.delay()}=h??{},x=nm(f.maxAttempts??w),_=g?Promise.resolve(g):void 0,A=async()=>{let P=await x();if(await nm(y)()===jt.ADAPTIVE)return new xm(x,{maxAttempts:P,baseDelay:S});return new ns({maxAttempts:P,baseDelay:S})};return Object.assign(f,{maxAttempts:x,retryStrategy:()=>_??=A()})},Cm="AWS_RETRY_MODE",Rm="retry_mode",S1={environmentVariableSelector:(f)=>f[Cm],configFileSelector:(f)=>f[Rm],default:bm},vm=()=>(f)=>async(h)=>{let{request:g}=h;if(Po.isInstance(g))delete g.headers[Uo],delete g.headers[Fo];return f(h)},km={name:"omitRetryHeadersMiddleware",tags:["RETRY","HEADERS","OMIT_RETRY_HEADERS"],relation:"before",toMiddleware:"awsAuthMiddleware",override:!0},w1=(f)=>({applyToStack:(h)=>{h.addRelativeTo(vm(),km)}}),E1=Sm(im),b1=h1(im);x1.AdaptiveRetryStrategy=xm;x1.CONFIG_MAX_ATTEMPTS=Xc;x1.CONFIG_RETRY_MODE=Rm;x1.ConfiguredRetryStrategy=_m;x1.DEFAULT_MAX_ATTEMPTS=Ir;x1.DEFAULT_RETRY_DELAY_BASE=fm;x1.DEFAULT_RETRY_MODE=bm;x1.DefaultRateLimiter=is;x1.DeprecatedAdaptiveRetryStrategy=Im;x1.DeprecatedStandardRetryStrategy=eu;x1.ENV_MAX_ATTEMPTS=Qc;x1.ENV_RETRY_MODE=Cm;x1.INITIAL_RETRY_TOKENS=Mo;x1.INVOCATION_ID_HEADER=Uo;x1.MAXIMUM_RETRY_DELAY=Do;x1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS=g1;x1.NODE_RETRY_MODE_CONFIG_OPTIONS=S1;x1.NO_RETRY_INCREMENT=Zc;x1.REQUEST_HEADER=Fo;x1.RETRY_COST=pm;x1.RETRY_MODES=jt;x1.Retry=Oe;x1.StandardRetryStrategy=ns;x1.THROTTLING_RETRY_DELAY_BASE=hm;x1.TIMEOUT_RETRY_COST=mm;x1.defaultDelayDecider=Tm;x1.defaultRetryDecider=Am;x1.getOmitRetryHeadersPlugin=w1;x1.getRetryAfterHint=c1;x1.getRetryPlugin=b1;x1.isBrowserNetworkError=um;x1.isClockSkewCorrectedError=cm;x1.isClockSkewError=am;x1.isNodeJsHttp2TransientError=lm;x1.isRetryableByTrait=Yc;x1.isServerError=dm;x1.isThrottlingError=ss;x1.isTransientError=os;x1.omitRetryHeadersMiddleware=vm;x1.omitRetryHeadersMiddlewareOptions=km;x1.resolveRetryConfig=y1;x1.retryMiddleware=E1;x1.retryMiddlewareOptions=wm});var Om=i(function(fM){var nr={REQUEST_ID:Symbol.for("_AWS_LAMBDA_REQUEST_ID"),X_RAY_TRACE_ID:Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"),TENANT_ID:Symbol.for("_AWS_LAMBDA_TENANT_ID"),TRACEPARENT:Symbol.for("_AWS_LAMBDA_TRACEPARENT"),TRACESTATE:Symbol.for("_AWS_LAMBDA_TRACESTATE"),BAGGAGE:Symbol.for("_AWS_LAMBDA_BAGGAGE")},tu=["true","1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA??"");if(!tu)globalThis.awslambda=globalThis.awslambda||{};class $o{static PROTECTED_KEYS=nr;isProtectedKey(f){return Object.values(nr).includes(f)}getRequestId(){return this.get(nr.REQUEST_ID)??"-"}getXRayTraceId(){return this.get(nr.X_RAY_TRACE_ID)}getTenantId(){return this.get(nr.TENANT_ID)}getTraceparent(){return this.get(nr.TRACEPARENT)}getTracestate(){return this.get(nr.TRACESTATE)}getBaggage(){return this.get(nr.BAGGAGE)}}class Nm extends $o{currentContext;getContext(){return this.currentContext}hasContext(){return this.currentContext!==void 0}get(f){return this.currentContext?.[f]}set(f,h){if(this.isProtectedKey(f))throw Error(`Cannot modify protected Lambda context field: ${String(f)}`);this.currentContext=this.currentContext||{},this.currentContext[f]=h}run(f,h){return this.currentContext=f,h()}}class nu extends $o{als;static async create(){let f=new nu,h=await import("node:async_hooks");return f.als=new h.AsyncLocalStorage,f}getContext(){return this.als.getStore()}hasContext(){return this.als.getStore()!==void 0}get(f){return this.als.getStore()?.[f]}set(f,h){if(this.isProtectedKey(f))throw Error(`Cannot modify protected Lambda context field: ${String(f)}`);let g=this.als.getStore();if(!g)throw Error("No context available");g[f]=h}run(f,h){return this.als.run(f,h)}}fM.InvokeStore=void 0;(function(f){let h=null;async function g(y){if(!h)h=(async()=>{let S=y===!0||"AWS_LAMBDA_MAX_CONCURRENCY"in process.env?await nu.create():new Nm;if(!tu&&globalThis.awslambda?.InvokeStore)return globalThis.awslambda.InvokeStore;else if(!tu&&globalThis.awslambda)return globalThis.awslambda.InvokeStore=S,S;else return S})();return h}f.getInstanceAsync=g,f._testing=process.env.AWS_LAMBDA_BENCHMARK_MODE==="1"?{reset:()=>{if(h=null,globalThis.awslambda?.InvokeStore)delete globalThis.awslambda.InvokeStore;globalThis.awslambda={InvokeStore:void 0}}}:void 0})(fM.InvokeStore||(fM.InvokeStore={}));fM.InvokeStoreBase=$o});var Pm=i(function(su,ou){/*!
18
+ * Bowser - a browser detector
19
+ * https://github.com/lancedikson/bowser
20
+ * MIT License | (c) Dustin Diaz 2012-2015
21
+ * MIT License | (c) Denis Demchenko 2015-2026
22
+ */(function(f,h){typeof su=="object"&&typeof ou<"u"?ou.exports=h():typeof define=="function"&&define.amd?define([],h):(f=typeof globalThis<"u"?globalThis:f||self).bowser=h()})(su,function(){var f={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","HeyTap Browser":"heytap","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",Ladybird:"ladybird",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc","Vivo Browser":"vivo",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},h={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",heytap:"HeyTap Browser",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",ladybird:"Ladybird",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivo:"Vivo Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},g={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},y={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},w={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",LibWeb:"LibWeb",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"},S=function(){function k(){}return k.getFirstMatch=function(R,N){var q=N.match(R);return q&&q.length>0&&q[1]||""},k.getSecondMatch=function(R,N){var q=N.match(R);return q&&q.length>1&&q[2]||""},k.matchAndReturnConst=function(R,N,q){if(R.test(N))return q},k.isFirefoxOnIpad=function(R){var N=R.indexOf("Macintosh");if(N===-1)return!1;var q=R.indexOf(" FxiOS",N+9);return q!==-1&&R.indexOf("/",q+6)!==-1},k.getWindowsVersionName=function(R){switch(R){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},k.getMacOSVersionName=function(R){var N=R.split(".").splice(0,2).map(function(W){return parseInt(W,10)||0});N.push(0);var q=N[0],V=N[1];if(q===10)switch(V){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}switch(q){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}},k.getAndroidVersionName=function(R){var N=R.split(".").splice(0,2).map(function(q){return parseInt(q,10)||0});if(N.push(0),!(N[0]===1&&N[1]<5))return N[0]===1&&N[1]<6?"Cupcake":N[0]===1&&N[1]>=6?"Donut":N[0]===2&&N[1]<2?"Eclair":N[0]===2&&N[1]===2?"Froyo":N[0]===2&&N[1]>2?"Gingerbread":N[0]===3?"Honeycomb":N[0]===4&&N[1]<1?"Ice Cream Sandwich":N[0]===4&&N[1]<4?"Jelly Bean":N[0]===4&&N[1]>=4?"KitKat":N[0]===5?"Lollipop":N[0]===6?"Marshmallow":N[0]===7?"Nougat":N[0]===8?"Oreo":N[0]===9?"Pie":void 0},k.getVersionPrecision=function(R){return R.split(".").length},k.compareVersions=function(R,N,q){q===void 0&&(q=!1);var V=k.getVersionPrecision(R),W=k.getVersionPrecision(N),G=Math.max(V,W),K=0,J=k.map([R,N],function(re){var Y=G-k.getVersionPrecision(re),X=re+Array(Y+1).join(".0");return k.map(X.split("."),function(ie){return Array(20-ie.length).join("0")+ie}).reverse()});for(q&&(K=G-Math.min(V,W)),G-=1;G>=K;){if(J[0][G]>J[1][G])return 1;if(J[0][G]===J[1][G]){if(G===K)return 0;G-=1}else if(J[0][G]<J[1][G])return-1}},k.map=function(R,N){var q,V=[];if(Array.prototype.map)return Array.prototype.map.call(R,N);for(q=0;q<R.length;q+=1)V.push(N(R[q]));return V},k.find=function(R,N){var q,V;if(Array.prototype.find)return Array.prototype.find.call(R,N);for(q=0,V=R.length;q<V;q+=1){var W=R[q];if(N(W,q))return W}},k.assign=function(R){for(var N,q,V=R,W=arguments.length,G=Array(W>1?W-1:0),K=1;K<W;K++)G[K-1]=arguments[K];if(Object.assign)return Object.assign.apply(Object,[R].concat(G));var J=function(){var re=G[N];typeof re=="object"&&re!==null&&Object.keys(re).forEach(function(Y){V[Y]=re[Y]})};for(N=0,q=G.length;N<q;N+=1)J();return R},k.getBrowserAlias=function(R){return f[R]},k.getBrowserTypeByAlias=function(R){return h[R]||""},k}(),x=/version\/(\d+(\.?_?\d+)+)/i,_=[{test:[/gptbot/i],describe:function(k){var R={name:"GPTBot"},N=S.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/chatgpt-user/i],describe:function(k){var R={name:"ChatGPT-User"},N=S.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/oai-searchbot/i],describe:function(k){var R={name:"OAI-SearchBot"},N=S.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(k){var R={name:"ClaudeBot"},N=S.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(k){var R={name:"Omgilibot"},N=S.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/diffbot/i],describe:function(k){var R={name:"Diffbot"},N=S.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/perplexitybot/i],describe:function(k){var R={name:"PerplexityBot"},N=S.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/perplexity-user/i],describe:function(k){var R={name:"Perplexity-User"},N=S.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/youbot/i],describe:function(k){var R={name:"YouBot"},N=S.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/meta-webindexer/i],describe:function(k){var R={name:"Meta-WebIndexer"},N=S.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/meta-externalads/i],describe:function(k){var R={name:"Meta-ExternalAds"},N=S.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/meta-externalagent/i],describe:function(k){var R={name:"Meta-ExternalAgent"},N=S.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/meta-externalfetcher/i],describe:function(k){var R={name:"Meta-ExternalFetcher"},N=S.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/googlebot/i],describe:function(k){var R={name:"Googlebot"},N=S.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/linespider/i],describe:function(k){var R={name:"Linespider"},N=S.getFirstMatch(/(?:linespider)(?:-[-\w]{1,64})?[\s/](\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/amazonbot/i],describe:function(k){var R={name:"AmazonBot"},N=S.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/bingbot/i],describe:function(k){var R={name:"BingCrawler"},N=S.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/baiduspider/i],describe:function(k){var R={name:"BaiduSpider"},N=S.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/duckduckbot/i],describe:function(k){var R={name:"DuckDuckBot"},N=S.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/ia_archiver/i],describe:function(k){var R={name:"InternetArchiveCrawler"},N=S.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(k){var R={name:"SlackBot"},N=S.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]{1,64})?[\s/](\d+(\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/yahoo!?[\s/]*slurp/i],describe:function(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe:function(){return{name:"PingdomBot"}}},{test:[/opera/i],describe:function(k){var R={name:"Opera"},N=S.getFirstMatch(x,k)||S.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/opr\/|opios/i],describe:function(k){var R={name:"Opera"},N=S.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/SamsungBrowser/i],describe:function(k){var R={name:"Samsung Internet for Android"},N=S.getFirstMatch(x,k)||S.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/Whale/i],describe:function(k){var R={name:"NAVER Whale Browser"},N=S.getFirstMatch(x,k)||S.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/PaleMoon/i],describe:function(k){var R={name:"Pale Moon"},N=S.getFirstMatch(x,k)||S.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/HeyTapBrowser/i],describe:function(k){var R={name:"HeyTap Browser"},N=S.getFirstMatch(/(?:HeyTapBrowser)[\s/](\d+(?:\.\d+)*)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/VivoBrowser/i],describe:function(k){var R={name:"Vivo Browser"},N=S.getFirstMatch(/(?:VivoBrowser)[\s/](\d+(?:\.\d+)*)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/MZBrowser/i],describe:function(k){var R={name:"MZ Browser"},N=S.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/focus/i],describe:function(k){var R={name:"Focus"},N=S.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/swing/i],describe:function(k){var R={name:"Swing"},N=S.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/coast/i],describe:function(k){var R={name:"Opera Coast"},N=S.getFirstMatch(x,k)||S.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(k){var R={name:"Opera Touch"},N=S.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/yabrowser/i],describe:function(k){var R={name:"Yandex Browser"},N=S.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/ucbrowser/i],describe:function(k){var R={name:"UC Browser"},N=S.getFirstMatch(x,k)||S.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/Maxthon|mxios/i],describe:function(k){var R={name:"Maxthon"},N=S.getFirstMatch(x,k)||S.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/epiphany/i],describe:function(k){var R={name:"Epiphany"},N=S.getFirstMatch(x,k)||S.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/puffin/i],describe:function(k){var R={name:"Puffin"},N=S.getFirstMatch(x,k)||S.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/sleipnir/i],describe:function(k){var R={name:"Sleipnir"},N=S.getFirstMatch(x,k)||S.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/k-meleon/i],describe:function(k){var R={name:"K-Meleon"},N=S.getFirstMatch(x,k)||S.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/micromessenger/i],describe:function(k){var R={name:"WeChat"},N=S.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/qqbrowser/i],describe:function(k){var R={name:/qqbrowserlite/i.test(k)?"QQ Browser Lite":"QQ Browser"},N=S.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/msie|trident/i],describe:function(k){var R={name:"Internet Explorer"},N=S.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/\sedg\//i],describe:function(k){var R={name:"Microsoft Edge"},N=S.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/edg([ea]|ios)\//i],describe:function(k){var R={name:"Microsoft Edge"},N=S.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:function(k){return!!k.hasBrand("Vivaldi")||k.test(/vivaldi/i)},describe:function(k,R){var N={name:"Vivaldi"};if(R){var q=R.getBrandVersion("Vivaldi");if(q)return N.version=q,N}var V=S.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,k);return V&&(N.version=V),N}},{test:[/seamonkey/i],describe:function(k){var R={name:"SeaMonkey"},N=S.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/sailfish/i],describe:function(k){var R={name:"Sailfish"},N=S.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,k);return N&&(R.version=N),R}},{test:[/silk/i],describe:function(k){var R={name:"Amazon Silk"},N=S.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/phantom/i],describe:function(k){var R={name:"PhantomJS"},N=S.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/slimerjs/i],describe:function(k){var R={name:"SlimerJS"},N=S.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(k){var R={name:"BlackBerry"},N=S.getFirstMatch(x,k)||S.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/(web|hpw)[o0]s/i],describe:function(k){var R={name:"WebOS Browser"},N=S.getFirstMatch(x,k)||S.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/bada/i],describe:function(k){var R={name:"Bada"},N=S.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/tizen/i],describe:function(k){var R={name:"Tizen"},N=S.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/qupzilla/i],describe:function(k){var R={name:"QupZilla"},N=S.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/librewolf/i],describe:function(k){var R={name:"LibreWolf"},N=S.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/firefox|iceweasel|fxios/i],describe:function(k){var R={name:"Firefox"},N=S.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/electron/i],describe:function(k){var R={name:"Electron"},N=S.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(k){var R={name:"Sogou Browser"},N=S.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,k),q=S.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,k),V=S.getFirstMatch(/se ([\d.]+)x/i,k),W=N||q||V;return W&&(R.version=W),R}},{test:[/MiuiBrowser/i],describe:function(k){var R={name:"Miui"},N=S.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:function(k){return!!k.hasBrand("DuckDuckGo")||k.test(/\sDdg\/[\d.]+$/i)},describe:function(k,R){var N={name:"DuckDuckGo"};if(R){var q=R.getBrandVersion("DuckDuckGo");if(q)return N.version=q,N}var V=S.getFirstMatch(/\sDdg\/([\d.]+)$/i,k);return V&&(N.version=V),N}},{test:function(k){return k.hasBrand("Brave")},describe:function(k,R){var N={name:"Brave"};if(R){var q=R.getBrandVersion("Brave");if(q)return N.version=q,N}return N}},{test:[/chromium/i],describe:function(k){var R={name:"Chromium"},N=S.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,k)||S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/ladybird/i],describe:function(k){var R={name:"Ladybird"},N=S.getFirstMatch(/ladybird\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/chrome|crios|crmo/i],describe:function(k){var R={name:"Chrome"},N=S.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/GSA/i],describe:function(k){var R={name:"Google Search"},N=S.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:function(k){var R=!k.test(/like android/i),N=k.test(/android/i);return R&&N},describe:function(k){var R={name:"Android Browser"},N=S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/playstation 4/i],describe:function(k){var R={name:"PlayStation 4"},N=S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/safari|applewebkit/i],describe:function(k){var R={name:"Safari"},N=S.getFirstMatch(x,k);return N&&(R.version=N),R}},{test:[/.*/i],describe:function(k){var R=k.search("\\(")!==-1?/^(.*)\/([^/]*)[ \t]\((.*)/:/^(.*)\/([^/]*) /;return{name:S.getFirstMatch(R,k),version:S.getSecondMatch(R,k)}}}],A=[{test:[/Roku\/DVP/],describe:function(k){var R=S.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,k);return{name:y.Roku,version:R}}},{test:[/windows phone/i],describe:function(k){var R=S.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,k);return{name:y.WindowsPhone,version:R}}},{test:[/windows /i],describe:function(k){var R=S.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,k),N=S.getWindowsVersionName(R);return{name:y.Windows,version:R,versionName:N}}},{test:function(k){return S.isFirefoxOnIpad(k.getUA())},describe:function(k){var R={name:y.iOS},N=S.getSecondMatch(/(Version\/)(\d[\d.]+)/,k);return N&&(R.version=N),R}},{test:[/macintosh/i],describe:function(k){var R=S.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,k).replace(/[_\s]/g,"."),N=S.getMacOSVersionName(R),q={name:y.MacOS,version:R};return N&&(q.versionName=N),q}},{test:[/(ipod|iphone|ipad)/i],describe:function(k){var R=S.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,k).replace(/[_\s]/g,".");return{name:y.iOS,version:R}}},{test:[/OpenHarmony/i],describe:function(k){var R=S.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,k);return{name:y.HarmonyOS,version:R}}},{test:function(k){var R=!k.test(/like android/i),N=k.test(/android/i);return R&&N},describe:function(k){var R=S.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,k),N=S.getAndroidVersionName(R),q={name:y.Android,version:R};return N&&(q.versionName=N),q}},{test:[/(web|hpw)[o0]s/i],describe:function(k){var R=S.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,k),N={name:y.WebOS};return R&&R.length&&(N.version=R),N}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(k){var R=S.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,k)||S.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,k)||S.getFirstMatch(/\bbb(\d+)/i,k);return{name:y.BlackBerry,version:R}}},{test:[/bada/i],describe:function(k){var R=S.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,k);return{name:y.Bada,version:R}}},{test:[/tizen/i],describe:function(k){var R=S.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,k);return{name:y.Tizen,version:R}}},{test:[/linux/i],describe:function(){return{name:y.Linux}}},{test:[/CrOS/],describe:function(){return{name:y.ChromeOS}}},{test:[/PlayStation 4/],describe:function(k){var R=S.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,k);return{name:y.PlayStation4,version:R}}}],P=[{test:[/googlebot/i],describe:function(){return{type:g.bot,vendor:"Google"}}},{test:[/linespider/i],describe:function(){return{type:g.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe:function(){return{type:g.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe:function(){return{type:g.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe:function(){return{type:g.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe:function(){return{type:g.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe:function(){return{type:g.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe:function(){return{type:g.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe:function(){return{type:g.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(){return{type:g.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(){return{type:g.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe:function(){return{type:g.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe:function(){return{type:g.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe:function(){return{type:g.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe:function(){return{type:g.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe:function(){return{type:g.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe:function(){return{type:g.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe:function(){return{type:g.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe:function(){return{type:g.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe:function(){return{type:g.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{type:g.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(){return{type:g.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe:function(){return{type:g.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{type:g.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe:function(){return{type:g.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe:function(k){var R=S.getFirstMatch(/(can-l01)/i,k)&&"Nova",N={type:g.mobile,vendor:"Huawei"};return R&&(N.model=R),N}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:g.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:g.tablet,vendor:"Apple",model:"iPad"}}},{test:function(k){return S.isFirefoxOnIpad(k.getUA())},describe:function(){return{type:g.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:g.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:g.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:g.tablet}}},{test:function(k){var R=k.test(/ipod|iphone/i),N=k.test(/like (ipod|iphone)/i);return R&&!N},describe:function(k){var R=S.getFirstMatch(/(ipod|iphone)/i,k);return{type:g.mobile,vendor:"Apple",model:R}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:g.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe:function(k){var R=S.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,k),N={type:g.mobile,vendor:"Nokia"};return R&&(N.model=R),N}},{test:[/[^-]mobi/i],describe:function(){return{type:g.mobile}}},{test:function(k){return k.getBrowserName(!0)==="blackberry"},describe:function(){return{type:g.mobile,vendor:"BlackBerry"}}},{test:function(k){return k.getBrowserName(!0)==="bada"},describe:function(){return{type:g.mobile}}},{test:function(k){return k.getBrowserName()==="windows phone"},describe:function(){return{type:g.mobile,vendor:"Microsoft"}}},{test:function(k){var R=Number(String(k.getOSVersion()).split(".")[0]);return k.getOSName(!0)==="android"&&R>=3},describe:function(){return{type:g.tablet}}},{test:function(k){return k.getOSName(!0)==="android"},describe:function(){return{type:g.mobile}}},{test:[/smart-?tv|smarttv/i],describe:function(){return{type:g.tv}}},{test:[/netcast/i],describe:function(){return{type:g.tv}}},{test:function(k){return k.getOSName(!0)==="macos"},describe:function(){return{type:g.desktop,vendor:"Apple"}}},{test:function(k){return k.getOSName(!0)==="windows"},describe:function(){return{type:g.desktop}}},{test:function(k){return k.getOSName(!0)==="linux"},describe:function(){return{type:g.desktop}}},{test:function(k){return k.getOSName(!0)==="playstation 4"},describe:function(){return{type:g.tv}}},{test:function(k){return k.getOSName(!0)==="roku"},describe:function(){return{type:g.tv}}}],D=[{test:function(k){return k.getBrowserName(!0)==="microsoft edge"},describe:function(k){if(/\sedg\//i.test(k))return{name:w.Blink};var R=S.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,k);return{name:w.EdgeHTML,version:R}}},{test:function(k){return k.getBrowserName(!0)==="ladybird"},describe:function(){return{name:w.LibWeb}}},{test:[/trident/i],describe:function(k){var R={name:w.Trident},N=S.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:function(k){return k.test(/presto/i)},describe:function(k){var R={name:w.Presto},N=S.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:function(k){var R=k.test(/gecko/i),N=k.test(/like gecko/i);return R&&!N},describe:function(k){var R={name:w.Gecko},N=S.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:w.Blink}}},{test:[/(apple)?webkit/i],describe:function(k){var R={name:w.WebKit},N=S.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,k);return N&&(R.version=N),R}}],U=function(){function k(N,q,V){if(q===void 0&&(q=!1),V===void 0&&(V=null),N==null||N==="")throw Error("UserAgent parameter can't be empty");this._ua=N;var W=!1;typeof q=="boolean"?(W=q,this._hints=V):this._hints=q!=null&&typeof q=="object"?q:null,this.parsedResult={},W!==!0&&this.parse()}var R=k.prototype;return R.getHints=function(){return this._hints},R.hasBrand=function(N){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var q=N.toLowerCase();return this._hints.brands.some(function(V){return V.brand&&V.brand.toLowerCase()===q})},R.getBrandVersion=function(N){if(this._hints&&Array.isArray(this._hints.brands)){var q=N.toLowerCase(),V=S.find(this._hints.brands,function(W){return W.brand&&W.brand.toLowerCase()===q});return V?V.version:void 0}},R.getUA=function(){return this._ua},R.test=function(N){return N.test(this._ua)},R.parseBrowser=function(){var N=this;this.parsedResult.browser={};var q=S.find(_,function(V){if(typeof V.test=="function")return V.test(N);if(Array.isArray(V.test))return V.test.some(function(W){return N.test(W)});throw Error("Browser's test function is not valid")});return q&&(this.parsedResult.browser=q.describe(this.getUA(),this)),this.parsedResult.browser},R.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},R.getBrowserName=function(N){return N?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},R.getBrowserVersion=function(){return this.getBrowser().version},R.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},R.parseOS=function(){var N=this;this.parsedResult.os={};var q=S.find(A,function(V){if(typeof V.test=="function")return V.test(N);if(Array.isArray(V.test))return V.test.some(function(W){return N.test(W)});throw Error("Browser's test function is not valid")});return q&&(this.parsedResult.os=q.describe(this.getUA())),this.parsedResult.os},R.getOSName=function(N){var q=this.getOS().name;return N?String(q).toLowerCase()||"":q||""},R.getOSVersion=function(){return this.getOS().version},R.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},R.getPlatformType=function(N){N===void 0&&(N=!1);var q=this.getPlatform().type;return N?String(q).toLowerCase()||"":q||""},R.parsePlatform=function(){var N=this;this.parsedResult.platform={};var q=S.find(P,function(V){if(typeof V.test=="function")return V.test(N);if(Array.isArray(V.test))return V.test.some(function(W){return N.test(W)});throw Error("Browser's test function is not valid")});return q&&(this.parsedResult.platform=q.describe(this.getUA())),this.parsedResult.platform},R.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},R.getEngineName=function(N){return N?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},R.parseEngine=function(){var N=this;this.parsedResult.engine={};var q=S.find(D,function(V){if(typeof V.test=="function")return V.test(N);if(Array.isArray(V.test))return V.test.some(function(W){return N.test(W)});throw Error("Browser's test function is not valid")});return q&&(this.parsedResult.engine=q.describe(this.getUA())),this.parsedResult.engine},R.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},R.getResult=function(){return S.assign({},this.parsedResult)},R.satisfies=function(N){var q=this,V={},W=0,G={},K=0;if(Object.keys(N).forEach(function(Te){var se=N[Te];typeof se=="string"||Array.isArray(se)?(G[Te]=se,K+=1):typeof se=="object"&&(V[Te]=se,W+=1)}),W>0){var J=Object.keys(V),re=S.find(J,function(Te){return q.isOS(Te)});if(re){var Y=this.satisfies(V[re]);if(Y!==void 0)return Y}var X=S.find(J,function(Te){return q.isPlatform(Te)});if(X){var ie=this.satisfies(V[X]);if(ie!==void 0)return ie}}if(K>0){var ye=Object.keys(G),ve=S.find(ye,function(Te){return q.isBrowser(Te,!0)});if(ve!==void 0)return this.compareVersions(G[ve])}},R.isBrowser=function(N,q){q===void 0&&(q=!1);var V=this.getBrowserName().toLowerCase(),W=N.toLowerCase(),G=S.getBrowserTypeByAlias(W);return q&&G&&(W=G.toLowerCase()),W===V},R.compareVersions=function(N){var q=this;return typeof N=="string"?this.compareVersion(N):N.some(function(V){return q.compareVersion(V)})},R.compareVersion=function(N){var q=[0],V=N,W=!1,G=this.getBrowserVersion();if(typeof G=="string")return N[0]===">"||N[0]==="<"?(V=N.substr(1),N[1]==="="?(W=!0,V=N.substr(2)):q=[],N[0]===">"?q.push(1):q.push(-1)):N[0]==="="?V=N.substr(1):N[0]==="~"&&(W=!0,V=N.substr(1)),q.indexOf(S.compareVersions(G,V,W))>-1},R.isOS=function(N){return this.getOSName(!0)===String(N).toLowerCase()},R.isPlatform=function(N){return this.getPlatformType(!0)===String(N).toLowerCase()},R.isEngine=function(N){return this.getEngineName(!0)===String(N).toLowerCase()},R.is=function(N,q){return q===void 0&&(q=!1),this.isBrowser(N,q)||this.isOS(N)||this.isPlatform(N)},R.some=function(N){var q=this;return N===void 0&&(N=[]),N.some(function(V){return q.is(V)})},k}();function B(k){var R=function(N){if(typeof N!="object"||!N)return N;var q=N[Symbol.toPrimitive];if(q!==void 0){var V=q.call(N,"string");if(typeof V!="object")return V;throw TypeError("@@toPrimitive must return a primitive value.")}return String(N)}(k);return typeof R=="symbol"?R:R+""}var z=function(){function k(){}return k.getParser=function(q,V,W){if(V===void 0&&(V=!1),W===void 0&&(W=null),typeof q!="string")throw Error("UserAgent should be a string");return new U(q,V,W)},k.parse=function(q,V){return V===void 0&&(V=null),new U(q,V).getResult()},R=k,(N=[{key:"BROWSER_MAP",get:function(){return h}},{key:"ENGINE_MAP",get:function(){return w}},{key:"OS_MAP",get:function(){return y}},{key:"PLATFORMS_MAP",get:function(){return g}}])&&function(q,V){/*!
23
+ * Bowser - a browser detector
24
+ * https://github.com/bowser-js/bowser
25
+ * MIT License | (c) Dustin Diaz 2012-2015
26
+ * MIT License | (c) Denis Demchenko 2015-2026
27
+ */for(var W=0;W<V.length;W++){var G=V[W];G.enumerable=G.enumerable||!1,G.configurable=!0,"value"in G&&(G.writable=!0),Object.defineProperty(q,B(G.key),G)}}(R,N),Object.defineProperty(R,"prototype",{writable:!1}),R;var R,N}();return z.parse,z.getParser,z})});var nt=i(function(cD){var{Retry:pM,RETRY_MODES:Mm}=fn(),{HttpRequest:lu,parseUrl:mM}=Ne(),{InvokeStore:Dm}=Om(),{normalizeProvider:gM}=rr(),{platform:yM,release:SM}=c("node:os"),{versions:iu,env:Um}=c("node:process"),{isValidHostLabel:wM,isIpAddress:zm,customEndpointFunctions:EM}=Yt(),{EndpointError:bM,resolveEndpoint:xM}=Yt();cD.EndpointError=bM;cD.isIpAddress=zm;cD.resolveEndpoint=xM;var{loadConfig:_M,NODE_REGION_CONFIG_OPTIONS:qm,NODE_REGION_CONFIG_FILE_OPTIONS:jm}=Ce(),{REGION_ENV_NAME:TM,REGION_INI_NAME:AM,resolveRegionConfig:IM}=Ce();cD.NODE_REGION_CONFIG_FILE_OPTIONS=jm;cD.NODE_REGION_CONFIG_OPTIONS=qm;cD.REGION_ENV_NAME=TM;cD.REGION_INI_NAME=AM;cD.resolveRegionConfig=IM;var Lo={warningEmitted:!1},CM=(f)=>{if(f&&!Lo.warningEmitted){if(process.env.AWS_SDK_JS_NODE_VERSION_SUPPORT_WARNING_DISABLED==="true"){Lo.warningEmitted=!0;return}let h=parseInt(f.substring(1,f.indexOf("."))),g=22;if(h<g)Lo.warningEmitted=!0,process.emitWarning(`NodeVersionSupportWarning: The AWS SDK for JavaScript (v3)
28
+ versions published after the first week of January 2027
29
+ will require node >=${g}. You are running node ${f}.
30
+
31
+ To continue receiving updates to AWS services, bug fixes,
32
+ and security updates please upgrade to node >=${g}.
33
+
34
+ More information can be found at: https://a.co/c895JFp`)}},RM=()=>(f,h)=>async(g)=>(h.__retryLongPoll=!0,f(g)),vM={name:"longPollMiddleware",tags:["RETRY"],step:"initialize",override:!0},kM=(f)=>({applyToStack:(h)=>{h.add(RM(),vM)}});function NM(f,h,g){if(!f.$source)f.$source={};return f.$source[h]=g,f}pM.v2026||=typeof process==="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function Pt(f,h,g){if(!f.__aws_sdk_context)f.__aws_sdk_context={features:{}};else if(!f.__aws_sdk_context.features)f.__aws_sdk_context.features={};f.__aws_sdk_context.features[h]=g}function OM(f,h,g){if(!f.$source)f.$source={};return f.$source[h]=g,f}function PM(f){return f}var Vm=(f)=>(h)=>async(g)=>{if(!lu.isInstance(g.request))return h(g);let{request:y}=g,{handlerProtocol:w=""}=f.requestHandler.metadata||{};if(w.indexOf("h2")>=0&&!y.headers[":authority"])delete y.headers.host,y.headers[":authority"]=y.hostname+(y.port?":"+y.port:"");else if(!y.headers.host){let S=y.hostname;if(y.port!=null)S+=`:${y.port}`;y.headers.host=S}return h(g)},Wm={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},MM=(f)=>({applyToStack:(h)=>{h.add(Vm(f),Wm)}}),Gm=()=>(f,h)=>async(g)=>{try{let y=await f(g),{clientName:w,commandName:S,logger:x,dynamoDbDocumentClientOptions:_={}}=h,{overrideInputFilterSensitiveLog:A,overrideOutputFilterSensitiveLog:P}=_,D=A??h.inputFilterSensitiveLog,U=P??h.outputFilterSensitiveLog,{$metadata:B,...z}=y.output;return x?.info?.({clientName:w,commandName:S,input:D(g.input),output:U(z),metadata:B}),y}catch(y){let{clientName:w,commandName:S,logger:x,dynamoDbDocumentClientOptions:_={}}=h,{overrideInputFilterSensitiveLog:A}=_,P=A??h.inputFilterSensitiveLog;throw x?.error?.({clientName:w,commandName:S,input:P(g.input),error:y,metadata:y.$metadata}),y}},Km={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},DM=(f)=>({applyToStack:(h)=>{h.add(Gm(),Km)}}),Jm={step:"build",tags:["RECURSION_DETECTION","TRACE_CONTEXT_PROPAGATION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},UM="AWS_LAMBDA_FUNCTION_NAME",FM="_X_AMZN_TRACE_ID",au="X-Amzn-Trace-Id",du="traceparent",Qm="tracestate",Xm="baggage",Zm=()=>(f)=>async(h)=>{let{request:g}=h;if(!lu.isInstance(g))return f(h);let y;{let w=Object.keys(g.headers??{}).find((S)=>S.toLowerCase()===au.toLowerCase())??au;if(!g.headers.hasOwnProperty(w)){let S=process.env[UM],x=process.env[FM];y??=await Dm.getInstanceAsync();let A=y?.getXRayTraceId()??x,P=(D)=>typeof D==="string"&&D.length>0;if(P(S)&&P(A))g.headers[au]=A}}if($M(g.headers),!g.headers[du]){let S=(y??=await Dm.getInstanceAsync())?.getTraceparent?.();if(S){g.headers[du]=S;let x=y?.getTracestate?.();if(x)g.headers[Qm]=x;let _=y?.getBaggage?.();if(_)g.headers[Xm]=_}}return f(h)};function $M(f){for(let h of Object.keys(f)){let g=h.toLowerCase();if(h!==g&&(g===du||g===Qm||g===Xm))f[g]=f[h],delete f[h]}}var BM=(f)=>({applyToStack:(h)=>{h.add(Zm(),Jm)}}),fu=void 0;function LM(f){if(f===void 0)return!0;return typeof f==="string"&&f.length<=50}function zM(f){let h=gM(f.userAgentAppId??fu),{customUserAgent:g}=f;return Object.assign(f,{customUserAgent:typeof g==="string"?[[g]]:g,userAgentAppId:async()=>{let y=await h();if(!LM(y)){let w=f.logger?.constructor?.name==="NoOpLogger"||!f.logger?console:f.logger;if(typeof y!=="string")w?.warn("userAgentAppId must be a string or undefined.");else if(y.length>50)w?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return y}})}var eg={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)"}}}],version:"1.1"},tg=eg,rg="",ng=(f)=>{let{partitions:h}=tg;for(let y of h){let{regions:w,outputs:S}=y;for(let[x,_]of Object.entries(w))if(x===f)return{...S,..._}}for(let y of h){let{regionRegex:w,outputs:S}=y;if(new RegExp(w).test(f))return{...S}}let g=h.find((y)=>y.id==="aws");if(!g)throw Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...g.outputs}},sg=(f,h="")=>{tg=f,rg=h},HM=()=>{sg(eg,"")},og=()=>rg,qM=/\d{12}\.ddb/;async function jM(f,h,g){if(g.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor")Pt(f,"PROTOCOL_RPC_V2_CBOR","M");if(typeof h.retryStrategy==="function"){let S=await h.retryStrategy();if(typeof S.mode==="string")switch(S.mode){case Mm.ADAPTIVE:Pt(f,"RETRY_MODE_ADAPTIVE","F");break;case Mm.STANDARD:Pt(f,"RETRY_MODE_STANDARD","E");break}}if(typeof h.accountIdEndpointMode==="function"){let S=f.endpointV2;if(String(S?.url?.hostname).match(qM))Pt(f,"ACCOUNT_ID_ENDPOINT","O");switch(await h.accountIdEndpointMode?.()){case"disabled":Pt(f,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":Pt(f,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":Pt(f,"ACCOUNT_ID_MODE_REQUIRED","R");break}}let w=f.__smithy_context?.selectedHttpAuthScheme?.identity;if(w?.$source){let S=w;if(S.accountId)Pt(f,"RESOLVED_ACCOUNT_ID","T");for(let[x,_]of Object.entries(S.$source??{}))Pt(f,x,_)}}var Fm="user-agent",cu="x-amz-user-agent",$m=" ",uu="/",VM=/[^!$%&'*+\-.^_`|~\w]/g,WM=/[^!$%&'*+\-.^_`|~\w#]/g,Bm="-",GM=1024;function KM(f){let h="";for(let g in f){let y=f[g];if(h.length+y.length+1<=GM){if(h.length)h+=","+y;else h+=y;continue}break}return h}var ig=(f)=>(h,g)=>async(y)=>{let{request:w}=y;if(!lu.isInstance(w))return h(y);let{headers:S}=w,x=g?.userAgent?.map(Bo)||[],_=(await f.defaultUserAgentProvider()).map(Bo);await jM(g,f,y);let A=g;_.push(`m/${KM(Object.assign({},g.__smithy_context?.features,A.__aws_sdk_context?.features))}`);let P=f?.customUserAgent?.map(Bo)||[],D=await f.userAgentAppId();if(D)_.push(Bo(["app",`${D}`]));let U=og(),B=(U?[U]:[]).concat([..._,...x,...P]).join($m),z=[..._.filter((k)=>k.startsWith("aws-sdk-")),...P].join($m);if(f.runtime!=="browser"){if(z)S[cu]=S[cu]?`${S[Fm]} ${z}`:z;S[Fm]=B}else S[cu]=B;return h({...y,request:w})},Bo=(f)=>{let h=f[0].split(uu).map((x)=>x.replace(VM,Bm)).join(uu),g=f[1]?.replace(WM,Bm),y=h.indexOf(uu),w=h.substring(0,y),S=h.substring(y+1);if(w==="api")S=S.toLowerCase();return[w,S,g].filter((x)=>x&&x.length>0).reduce((x,_,A)=>{switch(A){case 0:return _;case 1:return`${x}/${_}`;default:return`${x}#${_}`}},"")},ag={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},JM=(f)=>({applyToStack:(h)=>{h.add(ig(f),ag)}}),QM=()=>{let f=["deno","bun","llrt"];for(let h of f)if(iu[h])return[`md/${h}`,iu[h]];return["md/nodejs",iu.node]},cg={isCrtAvailable:!1},XM=()=>{if(cg.isCrtAvailable)return["md/crt-avail"];return null},ug=({serviceId:f,clientVersion:h})=>{let g=QM();return async(y)=>{let w=[["aws-sdk-js",h],["ua","2.1"],[`os/${yM()}`,SM()],["lang/js"],g],S=XM();if(S)w.push(S);if(f)w.push([`api/${f}`,h]);if(Um.AWS_EXECUTION_ENV)w.push([`exec-env/${Um.AWS_EXECUTION_ENV}`]);let x=await y?.userAgentAppId?.();return x?[...w,[`app/${x}`]]:[...w]}},YM=ug,dg="AWS_SDK_UA_APP_ID",lg="sdk_ua_app_id",ZM="sdk-ua-app-id",eD={environmentVariableSelector:(f)=>f[dg],configFileSelector:(f)=>f[lg]??f[ZM],default:fu},tD=({serviceId:f,clientVersion:h})=>async(g)=>{let y=Pm(),w=y.parse??y.default.parse??(()=>""),S=typeof window<"u"&&window?.navigator?.userAgent?w(window.navigator.userAgent):void 0,x=[["aws-sdk-js",h],["ua","2.1"],[`os/${S?.os?.name||"other"}`,S?.os?.version],["lang/js"],["md/browser",`${S?.browser?.name??"unknown"}_${S?.browser?.version??"unknown"}`]];if(f)x.push([`api/${f}`,h]);let _=await g?.userAgentAppId?.();if(_)x.push([`app/${_}`]);return x},rD={os(f){if(/iPhone|iPad|iPod/.test(f))return"iOS";if(/Macintosh|Mac OS X/.test(f))return"macOS";if(/Windows NT/.test(f))return"Windows";if(/Android/.test(f))return"Android";if(/Linux/.test(f))return"Linux";return},browser(f){if(/EdgiOS|EdgA|Edg\//.test(f))return"Microsoft Edge";if(/Firefox\//.test(f))return"Firefox";if(/Chrome\//.test(f))return"Chrome";if(/Safari\//.test(f))return"Safari";return}},hu=(f,h=!1)=>{if(h){for(let g of f.split("."))if(!hu(g))return!1;return!0}if(!wM(f))return!1;if(f.length<3||f.length>63)return!1;if(f!==f.toLowerCase())return!1;if(zm(f))return!1;return!0},Lm=":",nD="/",fg=(f)=>{let h=f.split(Lm);if(h.length<6)return null;let[g,y,w,S,x,..._]=h;if(g!=="arn"||y===""||w===""||_.join(Lm)==="")return null;let A=_.map((P)=>P.split(nD)).flat();return{partition:y,service:w,region:S,accountId:x,resourceId:A}},hg={isVirtualHostableS3Bucket:hu,parseArn:fg,partition:ng};EM.aws=hg;var sD=(f)=>{if(typeof f.endpointProvider!=="function")throw Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client.");let{endpoint:h}=f;if(h===void 0)f.endpoint=async()=>pg(f.endpointProvider({Region:typeof f.region==="function"?await f.region():f.region,UseDualStack:typeof f.useDualstackEndpoint==="function"?await f.useDualstackEndpoint():f.useDualstackEndpoint,UseFIPS:typeof f.useFipsEndpoint==="function"?await f.useFipsEndpoint():f.useFipsEndpoint,Endpoint:void 0},{logger:f.logger}));return f},pg=(f)=>mM(f.url);function oD(f={}){return _M({...qm,async default(){if(!mg.silence)console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly.");return"us-east-1"}},{...jm,...f})}var mg={silence:!1},iD=(f)=>({setRegion(h){f.region=h},region(){return f.region}}),aD=(f)=>({region:f.region()});cD.DEFAULT_UA_APP_ID=fu;cD.NODE_APP_ID_CONFIG_OPTIONS=eD;cD.UA_APP_ID_ENV_NAME=dg;cD.UA_APP_ID_INI_NAME=lg;cD.awsEndpointFunctions=hg;cD.createDefaultUserAgentProvider=ug;cD.createUserAgentStringParsingProvider=tD;cD.crtAvailability=cg;cD.defaultUserAgent=YM;cD.emitWarningIfUnsupportedVersion=CM;cD.fallback=rD;cD.getAwsRegionExtensionConfiguration=iD;cD.getHostHeaderPlugin=MM;cD.getLoggerPlugin=DM;cD.getLongPollPlugin=kM;cD.getRecursionDetectionPlugin=BM;cD.getUserAgentMiddlewareOptions=ag;cD.getUserAgentPlugin=JM;cD.getUserAgentPrefix=og;cD.hostHeaderMiddleware=Vm;cD.hostHeaderMiddlewareOptions=Wm;cD.isVirtualHostableS3Bucket=hu;cD.loggerMiddleware=Gm;cD.loggerMiddlewareOptions=Km;cD.parseArn=fg;cD.partition=ng;cD.recursionDetectionMiddleware=Zm;cD.recursionDetectionMiddlewareOptions=Jm;cD.resolveAwsRegionExtensionConfiguration=aD;cD.resolveDefaultAwsRegionalEndpointsConfig=sD;cD.resolveHostHeaderConfig=PM;cD.resolveUserAgentConfig=zM;cD.setCredentialFeature=NM;cD.setFeature=Pt;cD.setPartitionInfo=sg;cD.setTokenFeature=OM;cD.state=Lo;cD.stsRegionDefaultResolver=oD;cD.stsRegionWarning=mg;cD.toEndpointV1=pg;cD.useDefaultPartitionInfo=HM;cD.userAgentMiddleware=ig});var pu=i(function(cU){var{setCredentialFeature:oU}=nt(),{CredentialsProviderError:iU}=Ce(),aU=(f)=>async()=>{f?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv");let h=process.env.AWS_ACCESS_KEY_ID,g=process.env.AWS_SECRET_ACCESS_KEY,y=process.env.AWS_SESSION_TOKEN,w=process.env.AWS_CREDENTIAL_EXPIRATION,S=process.env.AWS_CREDENTIAL_SCOPE,x=process.env.AWS_ACCOUNT_ID;if(h&&g){let _={accessKeyId:h,secretAccessKey:g,...y&&{sessionToken:y},...w&&{expiration:new Date(w)},...S&&{credentialScope:S},...x&&{accountId:x}};return oU(_,"CREDENTIALS_ENV_VARS","g"),_}throw new iU("Unable to find environment variable credentials.",{logger:f?.logger})};cU.ENV_ACCOUNT_ID="AWS_ACCOUNT_ID";cU.ENV_CREDENTIAL_SCOPE="AWS_CREDENTIAL_SCOPE";cU.ENV_EXPIRATION="AWS_CREDENTIAL_EXPIRATION";cU.ENV_KEY="AWS_ACCESS_KEY_ID";cU.ENV_SECRET="AWS_SECRET_ACCESS_KEY";cU.ENV_SESSION="AWS_SESSION_TOKEN";cU.fromEnv=aU});var Ho=i(function(HU){var{ProviderError:mu,CredentialsProviderError:sr,loadConfig:wu}=Ce(),gU=c("node:http"),{parseUrl:yU}=Ne(),wg=(f)=>Boolean(f)&&typeof f==="object"&&typeof f.AccessKeyId==="string"&&typeof f.SecretAccessKey==="string"&&typeof f.Token==="string"&&typeof f.Expiration==="string",Eg=(f)=>({accessKeyId:f.AccessKeyId,secretAccessKey:f.SecretAccessKey,sessionToken:f.Token,expiration:new Date(f.Expiration),...f.AccountId&&{accountId:f.AccountId}}),Eu=({maxRetries:f=0,timeout:h=1000})=>({maxRetries:f,timeout:h});function us(f){return new Promise((h,g)=>{let y=gU.request({method:"GET",...f,hostname:f.hostname?.replace(/^\[(.+)\]$/,"$1")});y.on("error",(w)=>{g(Object.assign(new mu("Unable to connect to instance metadata service"),w)),y.destroy()}),y.on("timeout",()=>{g(new mu("TimeoutError from instance metadata service")),y.destroy()}),y.on("response",(w)=>{let{statusCode:S=400}=w;if(S<200||300<=S)g(Object.assign(new mu("Error response received from instance metadata service"),{statusCode:S})),y.destroy();let x=[];w.on("data",(_)=>{x.push(_)}),w.on("end",()=>{h(Buffer.concat(x)),y.destroy()})}),y.end()})}var yu=(f,h)=>{let g=f();for(let y=0;y<h;y++)g=g.catch(f);return g},as="AWS_CONTAINER_CREDENTIALS_FULL_URI",zo="AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",Su="AWS_CONTAINER_AUTHORIZATION_TOKEN",SU=(f={})=>{let{timeout:h,maxRetries:g}=Eu(f);return()=>yu(async()=>{let y=await _U({logger:f.logger}),w=JSON.parse(await wU(h,y));if(!wg(w))throw new sr("Invalid response received from instance metadata service.",{logger:f.logger});return Eg(w)},g)},wU=async(f,h)=>{if(process.env[Su])h.headers={...h.headers,Authorization:process.env[Su]};return(await us({...h,timeout:f})).toString()},EU="169.254.170.2",bU=new Set(["localhost","127.0.0.1"]),xU=new Set(["http:","https:"]),_U=async({logger:f})=>{if(process.env[zo])return{hostname:EU,path:process.env[zo]};if(process.env[as]){let h;try{h=new URL(process.env[as])}catch{throw new sr(`${process.env[as]} is not a valid container metadata service URL`,{tryNextLink:!1,logger:f})}if(!h.hostname||!bU.has(h.hostname))throw new sr(`${h.hostname} is not a valid container metadata service hostname`,{tryNextLink:!1,logger:f});if(!h.protocol||!xU.has(h.protocol))throw new sr(`${h.protocol} is not a valid container metadata service protocol`,{tryNextLink:!1,logger:f});return{protocol:h.protocol,hostname:h.hostname,path:h.pathname+h.search,port:h.port?parseInt(h.port,10):void 0}}throw new sr(`The container metadata credential provider cannot be used unless the ${zo} or ${as} environment variable is set`,{tryNextLink:!1,logger:f})};class bu extends sr{tryNextLink;name="InstanceMetadataV1FallbackError";constructor(f,h=!0){super(f,h);this.tryNextLink=h,Object.setPrototypeOf(this,bu.prototype)}}var cs;(function(f){f.IPv4="http://169.254.169.254",f.IPv6="http://[fd00:ec2::254]"})(cs||(cs={}));var TU="AWS_EC2_METADATA_SERVICE_ENDPOINT",AU="ec2_metadata_service_endpoint",IU={environmentVariableSelector:(f)=>f[TU],configFileSelector:(f)=>f[AU],default:void 0},hn;(function(f){f.IPv4="IPv4",f.IPv6="IPv6"})(hn||(hn={}));var CU="AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE",RU="ec2_metadata_service_endpoint_mode",vU={environmentVariableSelector:(f)=>f[CU],configFileSelector:(f)=>f[RU],default:hn.IPv4},bg=async()=>yU(await kU()||await NU()),kU=async()=>wu(IU)(),NU=async()=>{let f=await wu(vU)();switch(f){case hn.IPv4:return cs.IPv4;case hn.IPv6:return cs.IPv6;default:throw Error(`Unsupported endpoint mode: ${f}. Select from ${Object.values(hn)}`)}},OU=300,PU=300,MU="https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html",gg=(f,h)=>{let g=OU+Math.floor(Math.random()*PU),y=new Date(Date.now()+g*1000);h.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(y)}.
35
+ For more information, please visit: `+MU);let w=f.originalExpiration??f.expiration;return{...f,...w?{originalExpiration:w}:{},expiration:y}},DU=(f,h={})=>{let g=h?.logger||console,y;return async()=>{let w;try{if(w=await f(),w.expiration&&w.expiration.getTime()<Date.now())w=gg(w,g)}catch(S){if(y)g.warn("Credential renew failed: ",S),w=gg(y,g);else throw S}return y=w,w}},xg="/latest/meta-data/iam/security-credentials/",UU="/latest/api/token",gu="AWS_EC2_METADATA_V1_DISABLED",yg="ec2_metadata_v1_disabled",Sg="x-aws-ec2-metadata-token",FU=(f={})=>DU($U(f),{logger:f.logger}),$U=(f={})=>{let h=!1,{logger:g,profile:y}=f,{timeout:w,maxRetries:S}=Eu(f),x=async(_,A)=>{if(h||A.headers?.[Sg]==null){let U=!1,B=!1,z=await wu({environmentVariableSelector:(k)=>{let R=k[gu];if(B=!!R&&R!=="false",R===void 0)throw new sr(`${gu} not set in env, checking config file next.`,{logger:f.logger});return B},configFileSelector:(k)=>{let R=k[yg];return U=!!R&&R!=="false",U},default:!1},{profile:y})();if(f.ec2MetadataV1Disabled||z){let k=[];if(f.ec2MetadataV1Disabled)k.push("credential provider initialization (runtime option ec2MetadataV1Disabled)");if(U)k.push(`config file profile (${yg})`);if(B)k.push(`process environment variable (${gu})`);throw new bu(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${k.join(", ")}].`)}}let D=(await yu(async()=>{let U;try{U=await LU(A)}catch(B){if(B.statusCode===401)h=!1;throw B}return U},_)).trim();return yu(async()=>{let U;try{U=await zU(D,A,f)}catch(B){if(B.statusCode===401)h=!1;throw B}return U},_)};return async()=>{let _=await bg();if(h)return g?.debug("AWS SDK Instance Metadata","using v1 fallback (no token fetch)"),x(S,{..._,timeout:w});else{let A;try{A=(await BU({..._,timeout:w})).toString()}catch(P){if(P?.statusCode===400)throw Object.assign(P,{message:"EC2 Metadata token request returned error"});else if(P.message==="TimeoutError"||[403,404,405].includes(P.statusCode))h=!0;return g?.debug("AWS SDK Instance Metadata","using v1 fallback (initial)"),x(S,{..._,timeout:w})}return x(S,{..._,headers:{[Sg]:A},timeout:w})}}},BU=async(f)=>us({...f,path:UU,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"21600"}}),LU=async(f)=>(await us({...f,path:xg})).toString(),zU=async(f,h,g)=>{let y=JSON.parse((await us({...h,path:xg+f})).toString());if(!wg(y))throw new sr("Invalid response received from instance metadata service.",{logger:g.logger});return Eg(y)};HU.DEFAULT_MAX_RETRIES=0;HU.DEFAULT_TIMEOUT=1000;HU.ENV_CMDS_AUTH_TOKEN=Su;HU.ENV_CMDS_FULL_URI=as;HU.ENV_CMDS_RELATIVE_URI=zo;HU.Endpoint=cs;HU.fromContainerMetadata=SU;HU.fromInstanceMetadata=FU;HU.getInstanceMetadataEndpoint=bg;HU.httpRequest=us;HU.providerConfigFromInit=Eu});var pn=i(function(dF){var{hasOwn:vg}=Ke(),{streamCollector:eF}=Ke();dF.streamCollector=eF;var{buildQueryString:kg,HttpResponse:Ng}=Ne(),jo=c("node:https"),{Readable:tF}=c("node:stream"),xu=c("node:http2");function Vo(f){let h=f&&typeof f==="object"&&"reason"in f?f.reason:void 0;if(h){if(h instanceof Error){let w=Error("Request aborted");return w.name="AbortError",w.cause=h,w}let y=Error(String(h));return y.name="AbortError",y}let g=Error("Request aborted");return g.name="AbortError",g}var rF=["ECONNRESET","EPIPE","ETIMEDOUT"],Og=(f)=>{let h={};for(let g in f){if(!vg(f,g))continue;let y=f[g];h[g]=Array.isArray(y)?y.join(","):y}return h},Me={setTimeout:(f,h)=>setTimeout(f,h),clearTimeout:(f)=>clearTimeout(f)},_g=1000,nF=(f,h,g=0)=>{if(!g)return-1;let y=(w)=>{let S=Me.setTimeout(()=>{f.destroy(),h(Object.assign(Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${g} ms.`),{name:"TimeoutError"}))},g-w),x=(_)=>{if(_?.connecting)_.on("connect",()=>{Me.clearTimeout(S)});else Me.clearTimeout(S)};if(f.socket)x(f.socket);else f.on("socket",x)};if(g<2000)return y(0),0;return Me.setTimeout(y.bind(null,_g),_g)},sF=(f,h,g=0,y,w)=>{if(g)return Me.setTimeout(()=>{let S=`@smithy/node-http-handler - [${y?"ERROR":"WARN"}] a request has exceeded the configured ${g} ms requestTimeout.`;if(y){let x=Object.assign(Error(S),{name:"TimeoutError",code:"ETIMEDOUT"});f.destroy(x),h(x)}else S+=" Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.",w?.warn?.(S)},g);return-1},oF=3000,iF=(f,{keepAlive:h,keepAliveMsecs:g},y=oF)=>{if(h!==!0)return-1;let w=()=>{if(f.socket)f.socket.setKeepAlive(h,g||0);else f.on("socket",(S)=>{S.setKeepAlive(h,g||0)})};if(y===0)return w(),0;return Me.setTimeout(w,y)},ds=(f)=>{let h=f?.defaultSocketTimeout;return typeof h==="number"&&Number.isFinite(h)&&h>0?h:void 0},Tg=3000,Ag=(f,h,g=0,y=!1)=>{let w;if(y)f.once("response",(_)=>w=_);let S=(_)=>{let A=g-_,P=()=>{let D=Object.assign(Error(`@smithy/node-http-handler - the request socket timed out after ${g} ms of inactivity (${y?"service default socket timeout":"configured by client requestHandler"}).`),{name:"TimeoutError"});if(y)w?.destroy(D);f.destroy(),h(D)};if(f.socket)f.socket.setTimeout(A,P),f.on("close",()=>f.socket?.removeListener("timeout",P));else f.setTimeout(A,P)};if(0<g&&g<6000)return S(0),0;let x=Me.setTimeout(S.bind(null,g===0?0:Tg),Tg);if(y)return f.once("close",()=>Me.clearTimeout(x)),0;return x},Ig=6000;async function Pg(f,h,g=Ig,y=!1){let w=h.headers,S=w?w.Expect||w.expect:void 0,x=-1,_=!0;if(!y&&S==="100-continue")_=await Promise.race([new Promise((A)=>{x=Number(Me.setTimeout(()=>A(!0),Math.max(Ig,g)))}),new Promise((A)=>{f.on("continue",()=>{Me.clearTimeout(x),A(!0)}),f.on("response",()=>{Me.clearTimeout(x),A(!1)}),f.on("error",()=>{Me.clearTimeout(x),A(!1)})})]);if(_)aF(f,h.body)}function aF(f,h){if(h instanceof tF){h.pipe(f);return}if(h){let g=Buffer.isBuffer(h);if(g||typeof h==="string"){if(g&&h.byteLength===0)f.end();else f.end(h);return}let w=h;if(typeof w==="object"&&w.buffer&&typeof w.byteOffset==="number"&&typeof w.byteLength==="number"){f.end(Buffer.from(w.buffer,w.byteOffset,w.byteLength));return}f.end(Buffer.from(h));return}f.end()}var cF=0,qo=void 0,Cg=void 0;class Wo{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(f){if(typeof f?.handle==="function")return f;return new Wo(f)}static checkSocketUsage(f,h,g=console){let{sockets:y,requests:w,maxSockets:S}=f;if(typeof S!=="number"||S===1/0)return h;let x=15000;if(Date.now()-x<h)return h;if(y&&w)for(let _ in y){if(!vg(y,_))continue;let A=y[_]?.length??0,P=w[_]?.length??0;if(A>=S&&P>=2*S)return g?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${A} and ${P} additional requests are enqueued.
36
+ See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
37
+ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`),Date.now()}return h}constructor(f){this.configProvider=new Promise((h,g)=>{if(typeof f==="function")f().then((y)=>{h(this.resolveDefaultConfig(y))}).catch(g);else h(this.resolveDefaultConfig(f))})}destroy(){this.config?.httpAgent?.destroy(),this.config?.httpsAgent?.destroy()}async handle(f,{abortSignal:h,requestTimeout:g}={}){if(!this.config)this.config=await this.configProvider;let y=this.config,w=y.logger,S=f.protocol==="https:";if(!S&&!this.config.httpAgent)this.config.httpAgent=await this.config.httpAgentProvider();return new Promise((x,_)=>{let A=void 0,P=-1,D=-1,U=-1,B=-1,z=-1,k=()=>{Me.clearTimeout(P),Me.clearTimeout(D),Me.clearTimeout(U),Me.clearTimeout(B),Me.clearTimeout(z)},R=async(se)=>{await A,k(),x(se)},N=async(se)=>{await A,k(),_(se)};if(h?.aborted){let se=Vo(h);N(se);return}let q=f.headers,V=q?(q.Expect??q.expect)==="100-continue":!1,W=S?y.httpsAgent:y.httpAgent;if(V&&!this.externalAgent)W=new(S?jo.Agent:qo)({keepAlive:!1,maxSockets:1/0});P=Me.setTimeout(()=>{this.socketWarningTimestamp=Wo.checkSocketUsage(W,this.socketWarningTimestamp,w)},y.socketAcquisitionWarningTimeout??(y.requestTimeout??2000)+(y.connectionTimeout??1000));let G=f.query?kg(f.query):"",K=void 0;if(f.username!=null||f.password!=null){let se=f.username??"",le=f.password??"";K=`${se}:${le}`}let J=f.path;if(G)J+=`?${G}`;if(f.fragment)J+=`#${f.fragment}`;let re=f.hostname??"";if(re[0]==="["&&re.endsWith("]"))re=f.hostname.slice(1,-1);else re=f.hostname;let Y={headers:f.headers,host:re,method:f.method,path:J,port:f.port,agent:W,auth:K},ie=(S?jo.request:Cg)(Y,(se)=>{let le=new Ng({statusCode:se.statusCode||-1,reason:se.statusMessage,headers:Og(se.headers),body:se});R({response:le})});if(ie.on("error",(se)=>{if(rF.includes(se.code))N(Object.assign(se,{name:"TimeoutError"}));else N(se)}),h){let se=()=>{ie.destroy();let le=Vo(h);N(le)};if(typeof h.addEventListener==="function"){let le=h;le.addEventListener("abort",se,{once:!0}),ie.once("close",()=>le.removeEventListener("abort",se))}else h.onabort=se}let ye=g??y.requestTimeout;D=nF(ie,N,y.connectionTimeout),U=sF(ie,N,ye,y.throwOnRequestTimeout,w??console);let ve=y.socketTimeout===void 0?ds(y):void 0;if(ve)B=Ag(ie,N,ve,!0);else B=Ag(ie,N,y.socketTimeout);let Te=Y.agent;if(typeof Te==="object"&&"keepAlive"in Te)z=iF(ie,{keepAlive:Te.keepAlive,keepAliveMsecs:Te.keepAliveMsecs});A=Pg(ie,f,ye,this.externalAgent).catch((se)=>(k(),_(se)))})}updateHttpClientConfig(f,h){this.config=void 0,this.configProvider=this.configProvider.then((g)=>{switch(f){case Symbol.for("logger"):f="logger",h=g.logger??h;break;case Symbol.for("@smithy/defaultSocketTimeout"):f="defaultSocketTimeout",h=ds(g)??h;break}return{...g,[f]:h}})}httpHandlerConfigs(){return this.config??{}}resolveDefaultConfig(f){let{requestTimeout:h,connectionTimeout:g,socketTimeout:y,socketAcquisitionWarningTimeout:w,httpAgent:S,httpsAgent:x,throwOnRequestTimeout:_,logger:A}=f||{},P=!0,D=50;return{connectionTimeout:g,requestTimeout:h,socketTimeout:y,defaultSocketTimeout:ds(f),socketAcquisitionWarningTimeout:w,throwOnRequestTimeout:_,httpAgentProvider:async()=>{let U=c("node:http"),{Agent:B,request:z}=U.default??U;if(Cg=z,qo=B,S instanceof qo||typeof S?.destroy==="function")return this.externalAgent=!0,S;return new qo({keepAlive:!0,maxSockets:50,...S})},httpsAgent:(()=>{if(x instanceof jo.Agent||typeof x?.destroy==="function")return this.externalAgent=!0,x;return new jo.Agent({keepAlive:!0,maxSockets:50,...x})})(),logger:A}}}var uF=new Uint16Array(1);class Go{id=uF[0]++;total=0;max=0;session;refs=0;constructor(f){f.unref(),this.session=f}retain(){if(this.session.destroyed)throw Error("@smithy/node-http-handler - cannot acquire reference to destroyed session.");this.refs+=1,this.total+=1,this.max=Math.max(this.refs,this.max),this.session.ref()}free(){if(this.session.destroyed)return;if(this.refs-=1,this.refs===0)this.session.unref();if(this.refs<0)throw Error("@smithy/node-http-handler - ClientHttp2Session refcount at zero, cannot decrement.")}deref(){return this.session}close(){if(!this.session.closed)this.session.close()}destroy(){if(this.refs=0,!this.session.destroyed)this.session.setTimeout(0),this.session.destroy()}useCount(){return this.refs}}class Mg{sessions=[];maxConcurrency=0;constructor(f){this.sessions=(f??[]).map((h)=>new Go(h))}poll(){let f=!1;for(let h of this.sessions){if(h.deref().destroyed){f=!0;continue}if(!this.maxConcurrency||h.useCount()<this.maxConcurrency)return h}if(f){for(let h of this.sessions)if(h.deref().destroyed)this.remove(h)}}offerLast(f){this.sessions.push(f)}remove(f){let h=this.sessions.indexOf(f);if(h>-1)this.sessions.splice(h,1)}[Symbol.iterator](){return this.sessions[Symbol.iterator]()}setMaxConcurrency(f){this.maxConcurrency=f}destroy(f){this.remove(f),f.destroy()}}class Dg{config;connectOptions;connectionPools=new Map;constructor(f){if(this.config=f,this.config.maxConcurrency&&this.config.maxConcurrency<=0)throw RangeError("maxConcurrency must be greater than zero.")}lease(f,h){let g=this.getUrlString(f),y=this.getPool(g);if(!this.config.disableConcurrency&&!h.isEventStream){let A=y.poll();if(A)return A.retain(),A}let w=new Go(this.connect(g)),S=w.deref();if(this.config.maxConcurrency)S.settings({maxConcurrentStreams:this.config.maxConcurrency},(A)=>{if(A)throw Error("Fail to set maxConcurrentStreams to "+this.config.maxConcurrency+"when creating new session for "+f.destination.toString())});let x=()=>{this.removeFromPoolAndClose(g,w)},_=()=>{this.removeFromPoolAndCheckedDestroy(g,w)};if(S.on("goaway",x),S.on("error",_),S.on("frameError",_),S.on("close",_),h.requestTimeout)S.setTimeout(h.requestTimeout,_);return y.offerLast(w),w.retain(),w}release(f,h){h.free()}createIsolatedSession(f,h){let g=this.getUrlString(f),y=new Go(this.connect(g)),w=y.deref();w.settings({maxConcurrentStreams:1});let S=()=>{y.destroy()};w.on("error",S),w.on("frameError",S),w.on("close",S);let x=h.requestTimeout??300000;return w.setTimeout(x,S),y.retain(),y}destroy(){for(let[f,h]of this.connectionPools){for(let g of[...h])g.destroy();this.connectionPools.delete(f)}}setMaxConcurrentStreams(f){if(f&&f<=0)throw RangeError("maxConcurrentStreams must be greater than zero.");this.config.maxConcurrency=f;for(let h of this.connectionPools.values())h.setMaxConcurrency(f)}setDisableConcurrentStreams(f){this.config.disableConcurrency=f}setNodeHttp2ConnectOptions(f){this.connectOptions=f}debug(){let f={};for(let[h,g]of this.connectionPools){let y=[];for(let w of g)y.push({id:w.id,active:w.useCount(),maxConcurrent:w.max,totalRequests:w.total});f[h]={sessions:y}}return f}removeFromPoolAndClose(f,h){this.connectionPools.get(f)?.remove(h),h.close()}removeFromPoolAndCheckedDestroy(f,h){this.connectionPools.get(f)?.remove(h),h.destroy()}getPool(f){if(!this.connectionPools.has(f)){let h=new Mg;if(this.config.maxConcurrency)h.setMaxConcurrency(this.config.maxConcurrency);this.connectionPools.set(f,h)}return this.connectionPools.get(f)}getUrlString(f){return f.destination.toString()}connect(f){return this.connectOptions===void 0?xu.connect(f):xu.connect(f,this.connectOptions)}}var{constants:Rg}=xu;class _u{config;configProvider;metadata={handlerProtocol:"h2"};connectionManager=new Dg({});static create(f){if(typeof f?.handle==="function")return f;return new _u(f)}constructor(f){this.configProvider=new Promise((h,g)=>{if(typeof f==="function")f().then((y)=>{h(y||{})}).catch(g);else h(f||{})})}destroy(){this.connectionManager.destroy()}async handle(f,{abortSignal:h,requestTimeout:g,isEventStream:y}={}){if(!this.config){let D=await this.configProvider;this.config={...D,defaultSocketTimeout:ds(D)};let{disableConcurrentStreams:U,maxConcurrentStreams:B,nodeHttp2ConnectOptions:z}=this.config;if(this.connectionManager.setDisableConcurrentStreams(U??!1),B)this.connectionManager.setMaxConcurrentStreams(B);if(z)this.connectionManager.setNodeHttp2ConnectOptions(z)}let{requestTimeout:w,disableConcurrentStreams:S,sessionTimeout:x}=this.config,_=S||y,A=g??w,P=A===void 0&&x===void 0?this.config.defaultSocketTimeout:void 0;return new Promise((D,U)=>{let B=!1,z=void 0,k=async(le)=>{await z,D(le)},R=async(le)=>{await z,U(le)};if(h?.aborted){B=!0;let le=Vo(h);R(le);return}let{hostname:N,method:q,port:V,protocol:W,query:G}=f,K="";if(f.username!=null||f.password!=null){let le=f.username??"",ft=f.password??"";K=`${le}:${ft}@`}let J=`${W}//${K}${N}${V?`:${V}`:""}`,re={destination:new URL(J)},Y={requestTimeout:this.config?.sessionTimeout,isEventStream:y},X=_?this.connectionManager.createIsolatedSession(re,Y):this.connectionManager.lease(re,Y),ie=X.deref(),ye=(le)=>{if(_)X.destroy();B=!0,R(le)},ve=G?kg(G):"",Te=f.path;if(ve)Te+=`?${ve}`;if(f.fragment)Te+=`#${f.fragment}`;let se=ie.request({...f.headers,[Rg.HTTP2_HEADER_PATH]:Te,[Rg.HTTP2_HEADER_METHOD]:q});if(A)se.setTimeout(A,()=>{se.close();let le=Error(`Stream timed out because of no activity for ${A} ms`);le.name="TimeoutError",ye(le)});else if(P)se.setTimeout(P,()=>{let le=Error(`Stream timed out because of no activity for ${P} ms`);if(le.name="TimeoutError",B=!0,R(le),se.destroy(le),_)X.destroy()}),se.once("response",()=>se.setTimeout(P));if(h){let le=()=>{se.close();let ft=Vo(h);ye(ft)};if(typeof h.addEventListener==="function"){let ft=h;ft.addEventListener("abort",le,{once:!0}),se.once("close",()=>ft.removeEventListener("abort",le))}else h.onabort=le}se.on("frameError",(le,ft,we)=>{ye(Error(`Frame type id ${le} in stream id ${we} has failed with code ${ft}.`))}),se.on("error",ye),se.on("aborted",()=>{ye(Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${se.rstCode}.`))}),se.on("response",(le)=>{let ft=new Ng({statusCode:le[":status"]??-1,headers:Og(le),body:se});if(B=!0,k({response:ft}),_)ie.close(),se.on("end",()=>{X.destroy()})}),se.on("close",()=>{if(_)X.destroy();else this.connectionManager.release(re,X);if(!B){let le=Error("Unexpected error: http2 request did not get a response");if(ie.destroyed)le.name="TimeoutError";ye(le)}}),z=Pg(se,f,A)})}updateHttpClientConfig(f,h){this.config=void 0,this.configProvider=this.configProvider.then((g)=>{switch(f){case Symbol.for("@smithy/defaultSocketTimeout"):f="defaultSocketTimeout",h=ds(g)??h;break}return{...g,[f]:h}})}httpHandlerConfigs(){return this.config??{}}}dF.DEFAULT_REQUEST_TIMEOUT=cF;dF.NodeHttp2Handler=_u;dF.NodeHttpHandler=Wo});var Tu=i(function(NF){var{setCredentialFeature:mF}=nt(),{CredentialsProviderError:Cr}=Ce(),{NodeHttpHandler:gF}=pn(),yF=c("node:fs/promises"),{HttpRequest:SF}=Ne(),{sdkStreamMixin:wF,parseRfc3339DateTime:EF}=Ke(),bF=(f,h)=>{if(f.protocol==="https:")return;if(f.hostname==="169.254.170.2"||f.hostname==="169.254.170.23"||f.hostname==="[fd00:ec2::23]")return;if(f.hostname.includes("[")){if(f.hostname==="[::1]"||f.hostname==="[0000:0000:0000:0000:0000:0000:0000:0001]")return}else{if(f.hostname==="localhost")return;let g=f.hostname.split("."),y=(w)=>{let S=parseInt(w,10);return 0<=S&&S<=255};if(g[0]==="127"&&y(g[1])&&y(g[2])&&y(g[3])&&g.length===4)return}throw new Cr(`URL not accepted. It must either be HTTPS or match one of the following:
38
+ - loopback CIDR 127.0.0.0/8 or [::1/128]
39
+ - ECS container host 169.254.170.2
40
+ - EKS container host 169.254.170.23 or [fd00:ec2::23]`,{logger:h})};function xF(f){return new SF({protocol:f.protocol,hostname:f.hostname,port:Number(f.port),path:f.pathname,query:Array.from(f.searchParams.entries()).reduce((h,[g,y])=>(h[g]=y,h),{}),fragment:f.hash})}async function _F(f,h){let y=await wF(f.body).transformToString();if(f.statusCode===200){let w=JSON.parse(y);if(typeof w.AccessKeyId!=="string"||typeof w.SecretAccessKey!=="string"||typeof w.Token!=="string"||typeof w.Expiration!=="string")throw new Cr("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }",{logger:h});return{accessKeyId:w.AccessKeyId,secretAccessKey:w.SecretAccessKey,sessionToken:w.Token,expiration:EF(w.Expiration)}}if(f.statusCode>=400&&f.statusCode<500){let w={};try{w=JSON.parse(y)}catch(S){}throw Object.assign(new Cr(`Server responded with status: ${f.statusCode}`,{logger:h}),{Code:w.Code,Message:w.Message})}throw new Cr(`Server responded with status: ${f.statusCode}`,{logger:h})}var TF=(f,h,g)=>async()=>{for(let y=0;y<h;++y)try{return await f()}catch(w){await new Promise((S)=>setTimeout(S,g))}return await f()},AF="AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",IF="http://169.254.170.2",CF="AWS_CONTAINER_CREDENTIALS_FULL_URI",RF="AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",vF="AWS_CONTAINER_AUTHORIZATION_TOKEN",kF=(f={})=>{f.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");let h,g=f.awsContainerCredentialsRelativeUri??process.env[AF],y=f.awsContainerCredentialsFullUri??process.env[CF],w=f.awsContainerAuthorizationToken??process.env[vF],S=f.awsContainerAuthorizationTokenFile??process.env[RF],x=f.logger?.constructor?.name==="NoOpLogger"||!f.logger?.warn?console.warn:f.logger.warn.bind(f.logger);if(g&&y)x("@aws-sdk/credential-provider-http: you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri."),x("awsContainerCredentialsRelativeUri will take precedence.");if(w&&S)x("@aws-sdk/credential-provider-http: you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile."),x("awsContainerAuthorizationTokenFile will take precedence.");if(g)h=`${IF}${g}`;else if(y)h=y;else throw new Cr(`No HTTP credential provider host provided.
41
+ Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`,{logger:f.logger});let _=new URL(h);bF(_,f.logger);let A=gF.create({connectionTimeout:f.timeout??1000}),P=f.timeout??1000,D=TF(async()=>{let U=xF(_);if(S)U.headers.Authorization=Ug((await yF.readFile(S)).toString());else if(w)U.headers.Authorization=Ug(w);try{let B=await A.handle(U,{requestTimeout:P});return _F(B.response).then((z)=>mF(z,"CREDENTIALS_HTTP","z"))}catch(B){throw new Cr(String(B),{logger:f.logger})}},f.maxRetries??3,f.timeout??1000);return async()=>{try{return await D()}finally{A.destroy?.()}}},Ug=(f)=>{if(f.includes(`\r
42
+ `))throw new Cr("Authorization token contains invalid \\r\\n sequence.");return f};NF.fromHttp=kF});var Du=i(function(VF){var{hasOwn:vr,fromUtf8:Fg,fromHex:PF,toHex:Rr,toUint8Array:ls,writeKey:MF,isArrayBuffer:DF}=Ke(),{normalizeProvider:$g}=ct(),{escapeUri:Ko,HttpRequest:Hg}=Ne();class qg{format(f){let h=[];for(let w in f){if(!vr(f,w))continue;let S=Fg(w);h.push(Uint8Array.from([S.byteLength]),S,this.formatHeaderValue(f[w]))}let g=new Uint8Array(h.reduce((w,S)=>w+S.byteLength,0)),y=0;for(let w of h)g.set(w,y),y+=w.byteLength;return g}formatHeaderValue(f){switch(f.type){case"boolean":return Uint8Array.from([f.value?0:1]);case"byte":return Uint8Array.from([2,f.value]);case"short":let h=new DataView(new ArrayBuffer(3));return h.setUint8(0,3),h.setInt16(1,f.value,!1),new Uint8Array(h.buffer);case"integer":let g=new DataView(new ArrayBuffer(5));return g.setUint8(0,4),g.setInt32(1,f.value,!1),new Uint8Array(g.buffer);case"long":let y=new Uint8Array(9);return y[0]=5,y.set(f.value.bytes,1),y;case"binary":let w=new DataView(new ArrayBuffer(3+f.value.byteLength));w.setUint8(0,6),w.setUint16(1,f.value.byteLength,!1);let S=new Uint8Array(w.buffer);return S.set(f.value,3),S;case"string":let x=Fg(f.value),_=new DataView(new ArrayBuffer(3+x.byteLength));_.setUint8(0,7),_.setUint16(1,x.byteLength,!1);let A=new Uint8Array(_.buffer);return A.set(x,3),A;case"timestamp":let P=new Uint8Array(9);return P[0]=8,P.set(Cu.fromNumber(f.value.valueOf()).bytes,1),P;case"uuid":if(!UF.test(f.value))throw Error(`Invalid UUID received: ${f.value}`);let D=new Uint8Array(17);return D[0]=9,D.set(PF(f.value.replace(/-/g,"")),1),D}}}var Bg;(function(f){f[f.boolTrue=0]="boolTrue",f[f.boolFalse=1]="boolFalse",f[f.byte=2]="byte",f[f.short=3]="short",f[f.integer=4]="integer",f[f.long=5]="long",f[f.byteArray=6]="byteArray",f[f.string=7]="string",f[f.timestamp=8]="timestamp",f[f.uuid=9]="uuid"})(Bg||(Bg={}));var UF=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Cu{bytes;constructor(f){if(this.bytes=f,f.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(f){if(f>9223372036854776000||f<-9223372036854776000)throw Error(`${f} is too large (or, if negative, too small) to represent as an Int64`);let h=new Uint8Array(8);for(let g=7,y=Math.abs(Math.round(f));g>-1&&y>0;g--,y/=256)h[g]=y;if(f<0)Lg(h);return new Cu(h)}valueOf(){let f=this.bytes.slice(0),h=f[0]&128;if(h)Lg(f);return parseInt(Rr(f),16)*(h?-1:1)}toString(){return String(this.valueOf())}}function Lg(f){for(let h=0;h<8;h++)f[h]^=255;for(let h=7;h>-1;h--)if(f[h]++,f[h]!==0)break}var jg="X-Amz-Algorithm",Vg="X-Amz-Credential",Ru="X-Amz-Date",Wg="X-Amz-SignedHeaders",Gg="X-Amz-Expires",vu="X-Amz-Signature",ku="X-Amz-Security-Token",FF="X-Amz-Region-Set",Nu="authorization",Ou=Ru.toLowerCase(),Kg="date",Jg=[Nu,Ou,Kg],Qg=vu.toLowerCase(),Zo="x-amz-content-sha256",Xg=ku.toLowerCase(),$F="host",Yg={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},Zg=/^proxy-/,ey=/^sec-/,BF=[/^proxy-/i,/^sec-/i],Jo="AWS4-HMAC-SHA256",LF="AWS4-ECDSA-P256-SHA256",ty="AWS4-HMAC-SHA256-PAYLOAD",ry="UNSIGNED-PAYLOAD",ny=50,Pu="aws4_request",sy=604800,oy=({query:f={}})=>{let h=[],g={};for(let y in f){if(!vr(f,y))continue;if(y.toLowerCase()===Qg)continue;let w=Ko(y);h.push(w);let S=f[y];if(typeof S==="string")g[w]=`${w}=${Ko(S)}`;else if(Array.isArray(S))g[w]=S.slice(0).reduce((x,_)=>x.concat([`${w}=${Ko(_)}`]),[]).sort().join("&")}return h.sort().map((y)=>g[y]).filter((y)=>y).join("&")},zF=(f)=>HF(f).toISOString().replace(/\.\d{3}Z$/,"Z"),HF=(f)=>{if(typeof f==="number")return new Date(f*1000);if(typeof f==="string"){if(Number(f))return new Date(Number(f)*1000);return new Date(f)}return f};class Mu{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:f,credentials:h,region:g,service:y,sha256:w,uriEscapePath:S=!0}){this.service=y,this.sha256=w,this.uriEscapePath=S,this.applyChecksum=typeof f==="boolean"?f:!0,this.regionProvider=$g(g),this.credentialProvider=$g(h)}createCanonicalRequest(f,h,g){let y=Object.keys(h).sort();return`${f.method}
43
+ ${this.getCanonicalPath(f)}
44
+ ${oy(f)}
45
+ ${y.map((w)=>`${w}:${h[w]}`).join(`
46
+ `)}
47
+
48
+ ${y.join(";")}
49
+ ${g}`}async createStringToSign(f,h,g,y){let w=new this.sha256;w.update(ls(g));let S=await w.digest();return`${y}
50
+ ${f}
51
+ ${h}
52
+ ${Rr(S)}`}getCanonicalPath({path:f}){if(this.uriEscapePath){let h=[];for(let w of f.split("/")){if(w?.length===0)continue;if(w===".")continue;if(w==="..")h.pop();else h.push(w)}let g=`${f?.startsWith("/")?"/":""}${h.join("/")}${h.length>0&&f?.endsWith("/")?"/":""}`;return Ko(g).replace(/%2F/g,"/")}return f}validateResolvedCredentials(f){if(typeof f!=="object"||typeof f.accessKeyId!=="string"||typeof f.secretAccessKey!=="string")throw Error("Resolved credential object is not valid")}formatDate(f){let h=zF(f).replace(/[-:]/g,"");return{longDate:h,shortDate:h.slice(0,8)}}getCanonicalHeaderList(f){return Object.keys(f).sort().join(";")}}var mn={},Qo=[],Xo=(f,h,g)=>`${f}/${h}/${g}/${Pu}`,iy=async(f,h,g,y,w)=>{let S=await zg(f,h.secretAccessKey,h.accessKeyId),x=`${g}:${y}:${w}:${Rr(S)}:${h.sessionToken}`;if(x in mn)return mn[x];Qo.push(x);while(Qo.length>ny)delete mn[Qo.shift()];let _=`AWS4${h.secretAccessKey}`;for(let A of[g,y,w,Pu])_=await zg(f,_,A);return mn[x]=_},qF=()=>{Qo.length=0,Object.keys(mn).forEach((f)=>{delete mn[f]})},zg=(f,h,g)=>{let y=new f(h);return y.update(ls(g)),y.digest()},Au=({headers:f},h,g)=>{let y={};for(let w of Object.keys(f).sort()){if(f[w]==null)continue;let S=w.toLowerCase();if(vr(Yg,S)||h?.has(S)||Zg.test(S)||ey.test(S)){if(!g||g&&!g.has(S))continue}if(S==="__proto__")MF(y);y[S]=f[w].replace(/[\r\n]/g," ").replace(/[ \t]+/g," ").replace(/^ | $/g,"")}return y},Yo=async({headers:f,body:h},g)=>{for(let y in f){if(!vr(f,y))continue;if(y.toLowerCase()===Zo)return f[y]}if(h==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";else if(typeof h==="string"||ArrayBuffer.isView(h)||DF(h)){let y=new g;return y.update(ls(h)),Rr(await y.digest())}return ry},ay=(f,h)=>{f=f.toLowerCase();for(let g in h){if(!vr(h,g))continue;if(f===g.toLowerCase())return!0}return!1},cy=(f,h={})=>{let{headers:g,query:y={}}=Hg.clone(f);for(let w in g){if(!vr(g,w))continue;let S=w.toLowerCase();if(S.slice(0,6)==="x-amz-"&&!h.unhoistableHeaders?.has(S)||h.hoistableHeaders?.has(S))y[w]=g[w],delete g[w]}return{...f,headers:g,query:y}},Iu=(f)=>{f=Hg.clone(f);for(let h in f.headers){if(!vr(f.headers,h))continue;if(Jg.indexOf(h.toLowerCase())>-1)delete f.headers[h]}return f};class uy extends Mu{headerFormatter=new qg;constructor({applyChecksum:f,credentials:h,region:g,service:y,sha256:w,uriEscapePath:S=!0}){super({applyChecksum:f,credentials:h,region:g,service:y,sha256:w,uriEscapePath:S})}async presign(f,h={}){let{signingDate:g=new Date,expiresIn:y=3600,unsignableHeaders:w,unhoistableHeaders:S,signableHeaders:x,hoistableHeaders:_,signingRegion:A,signingService:P}=h,D=await this.credentialProvider();this.validateResolvedCredentials(D);let U=A??await this.regionProvider(),{longDate:B,shortDate:z}=this.formatDate(g);if(y>sy)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let k=Xo(z,U,P??this.service),R=cy(Iu(f),{unhoistableHeaders:S,hoistableHeaders:_});if(D.sessionToken)R.query[ku]=D.sessionToken;R.query[jg]=Jo,R.query[Vg]=`${D.accessKeyId}/${k}`,R.query[Ru]=B,R.query[Gg]=y.toString(10);let N=Au(R,w,x);return R.query[Wg]=this.getCanonicalHeaderList(N),R.query[vu]=await this.getSignature(B,k,this.getSigningKey(D,U,z,P),this.createCanonicalRequest(R,N,await Yo(f,this.sha256))),R}async sign(f,h){if(typeof f==="string")return this.signString(f,h);else if(f.headers&&f.payload)return this.signEvent(f,h);else if(f.message)return this.signMessage(f,h);else return this.signRequest(f,h)}async signEvent({headers:f,payload:h},{signingDate:g=new Date,priorSignature:y,signingRegion:w,signingService:S,eventStreamCredentials:x}){let _=w??await this.regionProvider(),{shortDate:A,longDate:P}=this.formatDate(g),D=Xo(A,_,S??this.service),U=await Yo({headers:{},body:h},this.sha256),B=new this.sha256;B.update(f);let z=Rr(await B.digest()),k=[ty,P,D,y,z,U].join(`
53
+ `);return this.signString(k,{signingDate:g,signingRegion:_,signingService:S,eventStreamCredentials:x})}async signMessage(f,{signingDate:h=new Date,signingRegion:g,signingService:y,eventStreamCredentials:w}){return this.signEvent({headers:this.headerFormatter.format(f.message.headers),payload:f.message.body},{signingDate:h,signingRegion:g,signingService:y,priorSignature:f.priorSignature,eventStreamCredentials:w}).then((x)=>({message:f.message,signature:x}))}async signString(f,{signingDate:h=new Date,signingRegion:g,signingService:y,eventStreamCredentials:w}={}){let S=w??await this.credentialProvider();this.validateResolvedCredentials(S);let x=g??await this.regionProvider(),{shortDate:_}=this.formatDate(h),A=new this.sha256(await this.getSigningKey(S,x,_,y));return A.update(ls(f)),Rr(await A.digest())}async signRequest(f,{signingDate:h=new Date,signableHeaders:g,unsignableHeaders:y,signingRegion:w,signingService:S}={}){let x=await this.credentialProvider();this.validateResolvedCredentials(x);let _=w??await this.regionProvider(),A=Iu(f),{longDate:P,shortDate:D}=this.formatDate(h),U=Xo(D,_,S??this.service);if(A.headers[Ou]=P,x.sessionToken)A.headers[Xg]=x.sessionToken;let B=await Yo(A,this.sha256);if(!ay(Zo,A.headers)&&this.applyChecksum)A.headers[Zo]=B;let z=Au(A,y,g),k=await this.getSignature(P,U,this.getSigningKey(x,_,D,S),this.createCanonicalRequest(A,z,B));return A.headers[Nu]=`${Jo} Credential=${x.accessKeyId}/${U}, SignedHeaders=${this.getCanonicalHeaderList(z)}, Signature=${k}`,A}async getSignature(f,h,g,y){let w=await this.createStringToSign(f,h,y,Jo),S=new this.sha256(await g);return S.update(ls(w)),Rr(await S.digest())}getSigningKey(f,h,g,y){return iy(this.sha256,f,g,h,y||this.service)}}var jF={SignatureV4a:null};VF.ALGORITHM_IDENTIFIER=Jo;VF.ALGORITHM_IDENTIFIER_V4A=LF;VF.ALGORITHM_QUERY_PARAM=jg;VF.ALWAYS_UNSIGNABLE_HEADERS=Yg;VF.AMZ_DATE_HEADER=Ou;VF.AMZ_DATE_QUERY_PARAM=Ru;VF.AUTH_HEADER=Nu;VF.CREDENTIAL_QUERY_PARAM=Vg;VF.DATE_HEADER=Kg;VF.EVENT_ALGORITHM_IDENTIFIER=ty;VF.EXPIRES_QUERY_PARAM=Gg;VF.GENERATED_HEADERS=Jg;VF.HOST_HEADER=$F;VF.KEY_TYPE_IDENTIFIER=Pu;VF.MAX_CACHE_SIZE=ny;VF.MAX_PRESIGNED_TTL=sy;VF.PROXY_HEADER_PATTERN=Zg;VF.REGION_SET_PARAM=FF;VF.SEC_HEADER_PATTERN=ey;VF.SHA256_HEADER=Zo;VF.SIGNATURE_HEADER=Qg;VF.SIGNATURE_QUERY_PARAM=vu;VF.SIGNED_HEADERS_QUERY_PARAM=Wg;VF.SignatureV4=uy;VF.SignatureV4Base=Mu;VF.TOKEN_HEADER=Xg;VF.TOKEN_QUERY_PARAM=ku;VF.UNSIGNABLE_PATTERNS=BF;VF.UNSIGNED_PAYLOAD=ry;VF.clearCredentialCache=qF;VF.createScope=Xo;VF.getCanonicalHeaders=Au;VF.getCanonicalQuery=oy;VF.getPayloadHash=Yo;VF.getSigningKey=iy;VF.hasHeader=ay;VF.moveHeadersToQuery=cy;VF.prepareRequest=Iu;VF.signatureV4aContainer=jF});var yn=i(function(Q$){var{ProviderError:dy,booleanSelector:ly,SelectorType:fy,loadConfig:N$}=Ce(),{setCredentialFeature:O$}=nt(),{normalizeProvider:gn,memoizeIdentityProvider:P$,isIdentityExpired:M$,doesIdentityRequireRefresh:D$}=rr(),{SignatureV4:hy}=Du(),{HttpResponse:by,HttpRequest:xy}=Ne(),{SMITHY_CONTEXT_KEY:U$}=Jt(),py=(f)=>by.isInstance(f)?f.headers?.date??f.headers?.Date:void 0,my=(f)=>by.isInstance(f)?f.headers?.age??f.headers?.Age:void 0,_y=(f)=>new Date(Date.now()+f),gy=(f,h,g,y)=>{if(y!==void 0)return h;let w=Date.parse(f),S=Date.now();if(g!==void 0&&S-g>900000)return h;return g!==void 0?w-(g+S)/2:w-S},fs=(f,h)=>{if(!h)throw Error(`Property \`${f}\` is not resolved for AWS SDK SigV4Auth`);return h},F$=(f)=>f.context?.[U$]?.eventStream?.output===!0,Uu=async(f)=>{let h=fs("context",f.context),g=fs("config",f.config),y=h.endpointV2?.properties?.authSchemes?.[0],S=await fs("signer",g.signer)(y),x=f?.signingRegion,_=f?.signingRegionSet,A=f?.signingName;return{config:g,signer:S,signingRegion:x,signingRegionSet:_,signingName:A}};class ei{async sign(f,h,g){if(!xy.isInstance(f))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let y=await Uu(g),{config:w,signer:S}=y,{signingRegion:x,signingName:_}=y,A=g.context;if(A?.authSchemes?.length??!1){let[B,z]=A.authSchemes;if(B?.name==="sigv4a"&&z?.name==="sigv4")x=z?.signingRegion??x,_=z?.signingName??_}let P=await w.disableClockSkewCorrection?.()===!0;g._disableClockSkewCorrection=P;let D=P||F$(g);if(g._skipClockSkewSampling=D,!D)g._preRequestSystemClockOffset=w.systemClockOffset,g._requestSentAt=Date.now();return await S.sign(f,{signingDate:P?new Date:_y(w.systemClockOffset),signingRegion:x,signingService:_})}errorHandler(f){return(h)=>{let g=h;if(!f._skipClockSkewSampling&&!f._disableClockSkewCorrection){let y=g.ServerTime??py(g.$response);if(y){let w=fs("config",f.config),{_preRequestSystemClockOffset:S,_requestSentAt:x}=f,_=my(g.$response),A=gy(y,w.systemClockOffset,x,_);if(w.systemClockOffset=A,Math.abs(A)>=240000&&(A!==S||S!==void 0&&S!==A)&&g.$metadata)g.$metadata.clockSkewCorrected=!0}}throw h}}successHandler(f,h){if(h._skipClockSkewSampling||h._disableClockSkewCorrection)return;let g=py(f);if(g){let y=fs("config",h.config),w=h._requestSentAt,S=my(f);y.systemClockOffset=gy(g,y.systemClockOffset,w,S)}}}var $$=ei;class Ay extends ei{async sign(f,h,g){if(!xy.isInstance(f))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let{config:y,signer:w,signingRegion:S,signingRegionSet:x,signingName:_}=await Uu(g),P=(await y.sigv4aSigningRegionSet?.()??x??[S]).join(","),D=await y.disableClockSkewCorrection?.()===!0;if(g._disableClockSkewCorrection=D,!D)g._preRequestSystemClockOffset=y.systemClockOffset,g._requestSentAt=Date.now();return await w.sign(f,{signingDate:D?new Date:_y(y.systemClockOffset),signingRegion:P,signingService:_})}}var yy=(f)=>typeof f==="string"&&f.length>0?f.split(",").map((h)=>h.trim()):[],Iy=(f)=>`AWS_BEARER_TOKEN_${f.replace(/[\s-]/g,"_").toUpperCase()}`,Sy="AWS_AUTH_SCHEME_PREFERENCE",Ey="auth_scheme_preference",B$={environmentVariableSelector:(f,h)=>{if(h?.signingName){if(Iy(h.signingName)in f)return["httpBearerAuth"]}if(!(Sy in f))return;return yy(f[Sy])},configFileSelector:(f)=>{if(!(Ey in f))return;return yy(f[Ey])},default:[]},L$=(f)=>(f.sigv4aSigningRegionSet=gn(f.sigv4aSigningRegionSet),f),z$={environmentVariableSelector(f){if(f.AWS_SIGV4A_SIGNING_REGION_SET)return f.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((h)=>h.trim());throw new dy("AWS_SIGV4A_SIGNING_REGION_SET not set in env.",{tryNextLink:!0})},configFileSelector(f){if(f.sigv4a_signing_region_set)return(f.sigv4a_signing_region_set??"").split(",").map((h)=>h.trim());throw new dy("sigv4a_signing_region_set not set in profile.",{tryNextLink:!0})},default:void 0},H$=(f)=>(h)=>{let g=h.credentials,y=!!h.credentials,w=void 0;Object.defineProperty(h,"credentials",{set(D){if(D&&D!==g&&D!==w)y=!0;g=D;let U=q$(h,{credentials:g,credentialDefaultProvider:h.credentialDefaultProvider}),B=j$(h,U);if(y&&!B.attributed){let z=typeof g==="object"&&g!==null;w=async(k)=>{let N=await B(k);if(z&&(!N.$source||Object.keys(N.$source).length===0))return O$(N,"CREDENTIALS_CODE","e");return N},w.memoized=B.memoized,w.configBound=B.configBound,w.attributed=!0}else w=B},get(){return w},enumerable:!0,configurable:!0}),h.credentials=g;let{signingEscapePath:S=!0,systemClockOffset:x=h.systemClockOffset||0,sha256:_}=h,A;if(h.signer)A=gn(h.signer);else if(h.regionInfoProvider)A=()=>gn(h.region)().then(async(D)=>[await h.regionInfoProvider(D,{useFipsEndpoint:await h.useFipsEndpoint(),useDualstackEndpoint:await h.useDualstackEndpoint()})||{},D]).then(([D,U])=>{let{signingRegion:B,signingService:z}=D;h.signingRegion=h.signingRegion||B||U,h.signingName=h.signingName||z||h.serviceId;let k={...h,credentials:h.credentials,region:h.signingRegion,service:h.signingName,sha256:_,uriEscapePath:S};return new(h.signerConstructor||hy)(k)});else A=async(D)=>{D=Object.assign({},{name:"sigv4",signingName:h.signingName||h.defaultSigningName,signingRegion:await gn(h.region)(),properties:{}},D);let U=D.signingRegion,B=D.signingName;h.signingRegion=h.signingRegion||U,h.signingName=h.signingName||B||h.serviceId;let z={...h,credentials:h.credentials,region:h.signingRegion,service:h.signingName,sha256:_,uriEscapePath:S};return new(h.signerConstructor||hy)(z)};return Object.assign(h,{systemClockOffset:x,signingEscapePath:S,signer:A,disableClockSkewCorrection:gn(h.disableClockSkewCorrection??f)})};function q$(f,{credentials:h,credentialDefaultProvider:g}){let y;if(h)if(!h?.memoized)y=P$(h,M$,D$);else y=h;else if(g)y=gn(g(Object.assign({},f,{parentClientConfig:f})));else y=async()=>{throw Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")};return y.memoized=!0,y}function j$(f,h){if(h.configBound)return h;let g=async(y)=>h({...y,callerClientConfig:f});return g.memoized=h.memoized,g.configBound=!0,g}var V$="AWS_DISABLE_CLOCK_SKEW_CORRECTION",W$="disable_clock_skew_correction",G$={environmentVariableSelector:(f)=>ly(f,V$,fy.ENV),configFileSelector:(f)=>ly(f,W$,fy.CONFIG),default:!1},K$=N$(G$),Cy=H$(K$),J$=Cy;Q$.AWSSDKSigV4Signer=$$;Q$.AwsSdkSigV4ASigner=Ay;Q$.AwsSdkSigV4Signer=ei;Q$.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS=B$;Q$.NODE_SIGV4A_CONFIG_OPTIONS=z$;Q$.getBearerTokenEnvKey=Iy;Q$.resolveAWSSDKSigV4Config=J$;Q$.resolveAwsSdkSigV4AConfig=L$;Q$.resolveAwsSdkSigV4Config=Cy;Q$.validateSigningProperties=Uu});var eS=i(function(YB){var{nv:$y,NumericValue:Ss,calculateBodyLength:aB,generateIdempotencyToken:By,fromBase64:Gu,_parseEpochTimestamp:gs}=Ke(),{hasOwn:Je}=at(),{HttpRequest:cB,collectBody:uB,SerdeContext:ws,AbstractRpcV2Protocol:dB}=Ne(),{NormalizedSchema:mt,TypeRegistry:Ry}=Rt();function Tn(f){return typeof Buffer<"u"?Buffer.alloc(f):new Uint8Array(f)}var Es=Symbol("@smithy/core/cbor::tagSymbol");function Ku(f){return f[Es]=!0,f}var Ly=typeof Buffer<"u",Ju=new TextDecoder,he=Tn(0),Qu=!1,Et=new DataView(he.buffer,he.byteOffset,he.byteLength),ue=0;function lB(f){he=f,Qu=Ly&&he instanceof Buffer,Et=new DataView(he.buffer,he.byteOffset,he.byteLength)}function ir(f,h){if(f>=h)throw Error("unexpected end of (decode) payload.");let g=(he[f]&224)>>5,y=he[f]&31;if(y===31&&2<=g&&g<=5)return fB(f,h);switch(g){case 0:case 1:case 6:{let w,S;if(y<24)w=y,S=1;else switch(y){case 24:if(h-f<2)Mt(1);w=he[f+1],S=2;break;case 25:if(h-f<3)Mt(2);w=Et.getUint16(f+1),S=3;break;case 26:if(h-f<5)Mt(4);w=Et.getUint32(f+1),S=5;break;case 27:if(h-f<9)Mt(8);{let x=Et.getUint32(f+1);if(x<2097152)w=x*4294967296+Et.getUint32(f+5);else w=Et.getBigUint64(f+1)}S=9;break;default:Yu(y)}if(g===0)return ue=S,Hu(w);else if(g===1){let x;if(typeof w==="bigint")x=BigInt(-1)-w;else x=-1-w;return ue=S,Hu(x)}else return EB(f,h,y,w,S)}case 3:return ys(f,h);case 5:return pB(f,h);case 4:return yB(f,h);case 2:return Xu(f,h);default:return bB(f,h)}}function fB(f,h){let g=(he[f]&224)>>5;if((he[f]&31)===31)switch(g){case 3:return TB(f,h);case 5:return xB(f,h);case 4:return _B(f,h);case 2:return AB(f,h)}}function hB(f,h){let g=f>>7,y=(f&124)>>2,w=(f&3)<<8|h,S=g===0?1:-1;if(y===0){if(w===0)return 0;return S*(Math.pow(2,-14)*(w/1024))}else if(y===31){if(w===0)return S*(1/0);return NaN}return S*(Math.pow(2,y-15)*(1+w/1024))}function pB(f,h){let g=bs(f,h);if(g<25)return gB(f,h,g);return mB(f,h,g)}function mB(f,h,g){let y=ue;f+=y;let w=f,S=Object.create(null);for(let x=0;x<g;++x){let _=ys(f,h);if(f+=ue,(he[f]&224)>>5===3)S[_]=ys(f,h);else S[_]=ir(f,h);f+=ue}return ue=y+(f-w),Object.setPrototypeOf(S,Object.prototype),S}function gB(f,h,g){let y=ue;f+=y;let w=f,S={};for(let x=0;x<g;++x){let _=ys(f,h);f+=ue,S[_]=ir(f,h),f+=ue}return ue=y+(f-w),S}function yB(f,h){let g=bs(f,h),y=ue;f+=y;let w=f,S=Array(g);for(let x=0;x<g;++x)S[x]=ir(f,h),f+=ue;return ue=y+(f-w),S}function ys(f,h){let g=bs(f,h),y=ue;if(f+=y,h-f<g)Mt(g);if(ue=y+g,g<24)return wB(f,g);if(Qu)return he.toString("utf-8",f,f+g);return Ju.decode(he.subarray(f,f+g))}var vy=Array(2048),Fu=new Uint16Array(2048),hs=0;function SB(){hs=hs+1&65535}function wB(f,h){let g=h;for(let x=0;x<h;++x)g=g*31+he[f+x]|0;let y=g>>>0&2047,w=vy[y];if(w!==void 0){if(w.length===h){let x=!0;for(let _=0;_<h;++_)if(w.charCodeAt(_)!==he[f+_]){x=!1;break}if(x)return Fu[y]=hs,w}}let S=Qu?he.toString("utf-8",f,f+h):Ju.decode(he.subarray(f,f+h));if(Fu[y]!==hs)vy[y]=S,Fu[y]=hs;return S}function Xu(f,h){let g=bs(f,h),y=ue;if(f+=y,h-f<g)Mt(g);let w=he.subarray(f,f+g);return ue=y+g,w}function EB(f,h,g,y,w){if(g===2||g===3){let S=bs(f+w,h),x=BigInt(0),_=f+w+ue;for(let A=_;A<_+S;++A)x=x<<BigInt(8)|BigInt(he[A]);return ue=w+ue+S,g===3?-x-BigInt(1):x}else if(g===4){let S=ir(f+w,h),[x,_]=S,A=_<0?-1:1,P=BigInt(A)*BigInt(_),D=String(P),U=_<0?"-":"",B;if(typeof x==="number"&&Math.abs(x)<=268435456){let k=x,R="0".repeat(Math.abs(k)+1)+D;if(B=k===0?R:R.slice(0,R.length+k)+"."+R.slice(k),B=B.replace(/^0+/g,""),B==="")B="0";if(B[0]===".")B="0"+B;B=U+B}else{let k=BigInt(x);if(D.length===1)B=U+D+"e"+String(k);else{let R=k+BigInt(D.length-1);B=U+D[0]+"."+D.slice(1)+"e"+String(R)}}return ue=w+ue,$y(B)}else{let S=ir(f+w,h);return ue=w+ue,Ku({tag:Hu(y),value:S})}}function bB(f,h){let g=he[f]&31;switch(g){case 21:case 20:return ue=1,g===21;case 22:return ue=1,null;case 23:return ue=1,null;case 25:if(h-f<3)throw Error("incomplete float16 at end of buf.");return ue=3,hB(he[f+1],he[f+2]);case 26:if(h-f<5)throw Error("incomplete float32 at end of buf.");return ue=5,Et.getFloat32(f+1);case 27:if(h-f<9)throw Error("incomplete float64 at end of buf.");return ue=9,Et.getFloat64(f+1);default:Yu(g)}}function bs(f,h){let g=he[f]&31;if(g<24)return ue=1,g;switch(g){case 24:if(h-f<2)Mt(1);return ue=2,he[f+1];case 25:if(h-f<3)Mt(2);return ue=3,Et.getUint16(f+1);case 26:if(h-f<5)Mt(4);return ue=5,Et.getUint32(f+1);case 27:if(h-f<9)Mt(8);return ue=9,IB(Et.getBigUint64(f+1));default:Yu(g)}}function xB(f,h){f+=1;let g=f,y={};for(;f<h;){if(he[f]===255)return ue=f-g+2,y;let w=ys(f,h);f+=ue,y[w]=ir(f,h),f+=ue}throw Error("expected break marker.")}function _B(f,h){f+=1;let g=[];for(let y=f;f<h;){if(he[f]===255)return ue=f-y+2,g;g.push(ir(f,h)),f+=ue}throw Error("expected break marker.")}function TB(f,h){f+=1;let g=[];for(let y=f;f<h;){if(he[f]===255){let A=Tn(g.length);if(A.set(g,0),ue=f-y+2,Ly)return A.toString("utf-8",0,A.length);return Ju.decode(A)}let w=(he[f]&224)>>5,S=he[f]&31;if(w!==3)zy(w);if(S===31)throw Error("nested indefinite string.");let x=Xu(f,h);f+=ue;for(let A=0;A<x.length;++A)g.push(x[A])}throw Error("expected break marker.")}function AB(f,h){f+=1;let g=[];for(let y=f;f<h;){if(he[f]===255){let A=Tn(g.length);return A.set(g,0),ue=f-y+2,A}let w=(he[f]&224)>>5,S=he[f]&31;if(w!==2)zy(w);if(S===31)throw Error("nested indefinite string.");let x=Xu(f,h);f+=ue;for(let A=0;A<x.length;++A)g.push(x[A])}throw Error("expected break marker.")}function Hu(f){if(typeof f==="number")return f;let h=Number(f);if(Number.MIN_SAFE_INTEGER<=h&&h<=Number.MAX_SAFE_INTEGER)return h;return f}function IB(f){let h=Number(f);if(h<Number.MIN_SAFE_INTEGER||Number.MAX_SAFE_INTEGER<h)console.warn(Error(`@smithy/core/cbor - truncating BigInt(${f}) to ${h} with loss of precision.`));return h}function Mt(f){throw Error(`length ${f} greater than remaining buf len.`)}function Yu(f){throw Error(`unexpected minor value ${f}.`)}function zy(f){throw Error(`unexpected major type ${f} in indefinite string.`)}var CB=typeof Buffer<"u",Sn=new Map,ps=0,qu=!1,RB=2048,ae=Tn(RB),ht=new DataView(ae.buffer,ae.byteOffset,ae.byteLength),Z=0;function vB(f){let h=[f];while(h.length){let g=h.pop();if(typeof g==="string"){let y=g.length;if(CB)if(wn(y*3+9),y>23)$u(3,Buffer.byteLength(g)),Z+=ae.write(g,Z);else NB(g);else{let w=y*3;wn(w+9);let S=Z,_=new TextEncoder().encodeInto(g,ae.subarray(Z+9)).written,A;if(_<24)A=1;else if(_<256)A=2;else if(_<65536)A=3;else if(_<4294967296)A=5;else A=9;if(A<9)ae.copyWithin(S+A,S+9,S+9+_);Z=S,kr(3,_),Z+=_}continue}if(ae.byteLength-Z<9)wn(64);if(typeof g==="number"){if(Number.isInteger(g)&&g>=-9007199254740992&&g<=9007199254740991){let y=g>=0,w=y?0:1,S=y?g:-g-1;if(S<24)ae[Z++]=w<<5|S;else if(S<256)ae[Z++]=w<<5|24,ae[Z++]=S;else if(S<65536)ae[Z++]=w<<5|25,ae[Z++]=S>>8,ae[Z++]=S&255;else if(S<4294967296)ae[Z++]=w<<5|26,ht.setUint32(Z,S),Z+=4;else{ae[Z++]=w<<5|27;let x=S/4294967296|0,_=S-x*4294967296|0;ht.setUint32(Z,x),ht.setUint32(Z+4,_),Z+=8}continue}ae[Z++]=251,ht.setFloat64(Z,g),Z+=8;continue}else if(typeof g==="bigint"){let y=g>=0,w=y?0:1,S=y?g:-g-BigInt(1);if(S<BigInt("18446744073709551616")){let x=Number(S);if(x<4294967296)kr(w,x);else ae[Z++]=w<<5|27,ht.setBigUint64(Z,S),Z+=8}else{let x=S.toString(2),_=new Uint8Array(Math.ceil(x.length/8)),A=S,P=0;while(_.byteLength-++P>=0)_[_.byteLength-P]=Number(A&BigInt(255)),A>>=BigInt(8);wn(_.byteLength*2+16),ae[Z++]=y?194:195,$u(2,_.byteLength),ae.set(_,Z),Z+=_.byteLength}continue}else if(g===null){ae[Z++]=246;continue}else if(typeof g==="boolean"){ae[Z++]=224|(g?21:20);continue}else if(typeof g>"u")throw Error("@smithy/core/cbor: client may not serialize undefined value.");else if(Array.isArray(g)){kr(4,g.length),wn(g.length*9+64);for(let y=g.length-1;y>=0;--y)h.push(g[y]);continue}else if(typeof g.byteLength==="number"){wn(g.length*2+9),kr(2,g.length),ae.set(g,Z),Z+=g.byteLength;continue}else if(typeof g==="object"){if(g instanceof Ss){let S=g.string,x=BigInt(0),_=S.search(/[eE]/);if(_!==-1)x=BigInt(S.slice(_+1)),S=S.slice(0,_);let A=S.indexOf("."),P=A===-1?0:S.length-A-1,D=x-BigInt(P),U=BigInt(S.replace(".",""));ae[Z++]=196,kr(4,2),h.push(U),h.push(D>=-0x20000000000000n&&D<=0x1fffffffffffffn?Number(D):D);continue}if(g[Es])if("tag"in g&&"value"in g){h.push(g.value),$u(6,g.tag);continue}else throw Error("tag encountered with missing fields, need 'tag' and 'value', found: "+JSON.stringify(g));let y=Object.keys(g),w=y.length;kr(5,w);for(let S=w-1;S>=0;--S)h.push(g[y[S]]),h.push(y[S]);continue}throw Error(`data type ${g?.constructor?.name??typeof g} not compatible for encoding.`)}}function kB(){ps=ps+1&65535,qu=!1}function ky(){let f=Tn(Z);return f.set(ae.subarray(0,Z),0),Z=0,f}function ju(f){let h=ae;if(ae=Tn(f),h)if(h.copy)h.copy(ae,0,0,h.byteLength);else ae.set(h,0);ht=new DataView(ae.buffer,ae.byteOffset,ae.byteLength)}function NB(f){let h=Sn.get(f);if(h!==void 0){ae.set(h.bytes,Z),Z+=h.bytes.length,h.epoch=ps;return}let g=Z,y=Buffer.byteLength(f);kr(3,y),Z+=ae.write(f,Z);let w=Uint8Array.prototype.slice.call(ae,g,Z);if(Sn.size>=2048){if(qu)return;let S=0;for(let[x,_]of Sn){if(S>=1024)break;if(_.epoch!==ps)Sn.delete(x),S++}if(S===0){qu=!0;return}}if(Sn.size<2048)Sn.set(f,{epoch:ps,bytes:w})}function wn(f){if(ae.byteLength-Z<f)if(Z<16000000)ju(Math.max(ae.byteLength*4,ae.byteLength+f));else ju(ae.byteLength+f+16000000)}function $u(f,h){if(h<24)ae[Z++]=f<<5|h;else if(h<256)ae[Z++]=f<<5|24,ae[Z++]=h;else if(h<65536)ae[Z++]=f<<5|25,ht.setUint16(Z,h),Z+=2;else if(h<4294967296)ae[Z++]=f<<5|26,ht.setUint32(Z,h),Z+=4;else ae[Z++]=f<<5|27,ht.setBigUint64(Z,typeof h==="bigint"?h:BigInt(h)),Z+=8}function kr(f,h){if(h<24)ae[Z++]=f<<5|h;else if(h<256)ae[Z++]=f<<5|24,ae[Z++]=h;else if(h<65536)ae[Z++]=f<<5|25,ae[Z++]=h>>8,ae[Z++]=h&255;else if(h<4294967296)ae[Z++]=f<<5|26,ht.setUint32(Z,h),Z+=4;else{ae[Z++]=f<<5|27;let g=h/4294967296|0,y=h-g*4294967296|0;ht.setUint32(Z,g),ht.setUint32(Z+4,y),Z+=8}}var oi={deserialize(f){return SB(),lB(f),ir(0,f.length)},serialize(f){kB();try{return vB(f),ky()}catch(h){throw ky(),h}},resizeEncodingBuffer(f){ju(f)}},Hy=(f,h)=>uB(f,h).then(async(g)=>{if(g.length)try{return oi.deserialize(g)}catch(y){throw Object.defineProperty(y,"$responseBodyText",{value:h.utf8Encoder(g)}),y}return{}}),ti=(f)=>Ku({tag:1,value:f.getTime()/1000}),OB=async(f,h)=>{let g=await Hy(f,h);return g.message=g.message??g.Message,g},qy=(f,h)=>{let g=(y)=>{let w=y;if(typeof w==="number")w=w.toString();if(w.indexOf(",")>=0)w=w.split(",")[0];if(w.indexOf(":")>=0)w=w.split(":")[0];return w};if(h.__type!==void 0)return g(h.__type)},PB=(f)=>{if(String(f.headers["smithy-protocol"]).toLowerCase()!=="rpc-v2-cbor")throw Error("Malformed RPCv2 CBOR response, status: "+f.statusCode)},MB=async(f,h,g,y,w)=>{let S=await f.endpoint(),{hostname:x,protocol:_="https",port:A,path:P}=S,D={protocol:_,hostname:x,port:A,method:"POST",path:P.endsWith("/")?P.slice(0,-1)+g:P+g,headers:{...h}};if(y!==void 0)D.hostname=y;if(S.headers)for(let U in S.headers){if(!Je(S.headers,U))continue;D.headers[U]=S.headers[U]}if(w!==void 0){D.body=w;try{D.headers["content-length"]=String(aB(w))}catch(U){}}return new cB(D)};class Zu extends ws{write(f,h){ce=0;let g=mt.of(f);bn(g,h,void 0,this.serdeContext)}flush(){let f=de.subarray(0,ce);return ce=0,de=jy(Vu),Nr=new DataView(de.buffer,de.byteOffset,de.byteLength),f}}var Ny=Symbol.for("@smithy/cbor-struct-cache");function ed(f){let h=f.getSchema(),g=h[Ny];if(g)return g;let y=[],w=[];for(let[_,A]of f.structIterator())y.push(_),w.push(A);let S=Array(y.length);for(let _=0;_<y.length;++_)S[_]=DB(y[_]);let x={memberNames:y,memberSchemas:w,encodedKeys:S};return h[Ny]=x,x}function DB(f){let h;if(ii)h=Buffer.from(f,"utf-8");else h=new TextEncoder().encode(f);let g=h.length,y;if(g<24)y=1;else if(g<256)y=2;else y=3;let w=new Uint8Array(y+g);if(y===1)w[0]=96|g;else if(y===2)w[0]=120,w[1]=g;else w[0]=121,w[1]=g>>8,w[2]=g&255;return w.set(h,y),w}var ii=typeof Buffer<"u",UB=new TextEncoder,Vu=2048,de=ii?Buffer.allocUnsafe(Vu):new Uint8Array(Vu),Nr=new DataView(de.buffer,de.byteOffset,de.byteLength),ce=0,Oy=2048,En=new Map,Bu=0,Py=!1;function jy(f){return ii?Buffer.allocUnsafe(f):new Uint8Array(f)}function bn(f,h,g,y){if(h==null){if(h===void 0&&f.isIdempotencyToken()){Dt(By());return}ge(1),de[ce++]=246;return}if(f.isUnitSchema()){ge(1),$e(5,0);return}if(typeof h==="object"){if(f.isBlobSchema()){if(h instanceof Uint8Array){ri(h);return}}if(f.isTimestampSchema()){if(h instanceof Date){Wu(h);return}}if(f.isStructSchema()){FB(f,h,y);return}if(Array.isArray(h)&&(f.isListSchema()||f.isDocumentSchema())){My(f,h,f.isDocumentSchema(),y);return}if(f.isMapSchema()){Lu(f,h,!1,y);return}if(h instanceof Date){Wu(h);return}if(h instanceof Uint8Array){ri(h);return}if(h instanceof Ss){Gy(h);return}if(h[Es]){let S=h;Wy(S.tag,S.value);return}if(f.isDocumentSchema()){if(Array.isArray(h))My(f,h,!0,y);else Lu(f,h,!0,y);return}if(f.isBigDecimalSchema()){xn(h);return}Lu(f,h,!0,y);return}if(typeof h==="string"){if(f.isBlobSchema()){let S=(y?.base64Decoder??Gu)(h);ri(S);return}Dt(h);return}if(typeof h==="number"){if(ge(9),Number.isInteger(h)&&h>=-9007199254740992&&h<=9007199254740991)ai(h);else td(h);return}if(typeof h==="boolean"){ge(1),de[ce++]=224|(h?21:20);return}if(typeof h==="bigint"){si(h);return}Dt(String(h))}function FB(f,h,g){if(f.isUnionSchema()){let U=!1;for(let[B,z]of f.structIterator()){let k=h[B];if(k!=null){ge(9),$e(5,1),Dt(B),bn(z,k,f,g),U=!0;break}}if(!U){let{$unknown:B}=h;if(Array.isArray(B))ge(9),$e(5,1),Dt(B[0]),xn(B[1]);else ge(9),$e(5,0)}return}let y=ed(f),{memberNames:w,memberSchemas:S,encodedKeys:x}=y,_=w.length,A;if(_<24)A=1;else if(_<256)A=2;else A=3;ge(A);let P=ce;ce+=A;let D=0;for(let U=0;U<_;++U){let B=h[w[U]];if(B==null&&!S[U].isIdempotencyToken())continue;let z=x[U];ge(z.length),de.set(z,ce),ce+=z.length,bn(S[U],B,f,g),++D}if(typeof h.__type==="string")for(let U in h){if(!Je(h,U))continue;if(!w.includes(U))Dt(U),xn(h[U]),++D}if(A===1)de[P]=160|D;else if(A===2)de[P]=184,de[P+1]=D;else de[P]=185,de[P+1]=D>>8,de[P+2]=D&255}function My(f,h,g,y){let w=!!f.getMergedTraits().sparse,S=f.getValueSchema();if(g||w){let x=[];for(let _=0;_<h.length;++_){let A=h[_];if(g){if(A!==void 0)x.push(A)}else if(A!=null||w)x.push(A)}ge(9),$e(4,x.length);for(let _=0;_<x.length;++_)bn(S,x[_],void 0,y)}else{let x=0;for(let _=0;_<h.length;++_)if(h[_]!=null)++x;ge(9),$e(4,x);for(let _=0;_<h.length;++_)if(h[_]!=null)bn(S,h[_],void 0,y)}}function Lu(f,h,g,y){let w=!!f.getMergedTraits().sparse,S=f.getValueSchema(),x=[];for(let _ in h){if(!Je(h,_))continue;let A=h[_];if(g?A!==void 0:A!=null||w)x.push(_)}ge(9),$e(5,x.length);for(let _=0;_<x.length;++_){let A=x[_];Dt(A),bn(S,h[A],void 0,y)}}function xn(f){if(f==null){ge(1),de[ce++]=246;return}if(typeof f==="string"){Dt(f);return}if(typeof f==="number"){if(ge(9),Number.isInteger(f)&&f>=-9007199254740992&&f<=9007199254740991)ai(f);else td(f);return}if(typeof f==="boolean"){ge(1),de[ce++]=224|(f?21:20);return}if(typeof f==="bigint"){si(f);return}if(f instanceof Uint8Array){ri(f);return}if(f instanceof Date){Wu(f);return}if(f instanceof Ss){Gy(f);return}if(f[Es]){let h=f;Wy(h.tag,h.value);return}if(Array.isArray(f)){ge(9),$e(4,f.length);for(let h=0;h<f.length;++h)xn(f[h]);return}if(typeof f==="object"){let h=Object.keys(f);ge(9),$e(5,h.length);for(let g=0;g<h.length;++g)Dt(h[g]),xn(f[h[g]]);return}Dt(String(f))}function ge(f){if(ce+f>de.length){let h=de.length*2;while(h<ce+f)h*=2;let g=jy(h);g.set(de.subarray(0,ce)),de=g,Nr=new DataView(g.buffer,g.byteOffset,g.byteLength)}}function $e(f,h){if(h<24)de[ce++]=f<<5|h;else if(h<256)de[ce++]=f<<5|24,de[ce++]=h;else if(h<65536)de[ce++]=f<<5|25,de[ce++]=h>>8,de[ce++]=h&255;else if(h<4294967296)de[ce++]=f<<5|26,Nr.setUint32(ce,h),ce+=4;else{de[ce++]=f<<5|27;let g=h/4294967296|0,y=h-g*4294967296|0;Nr.setUint32(ce,g),Nr.setUint32(ce+4,y),ce+=8}}function Vy(f,h){let g=Number(h);if(g<4294967296){$e(f,g);return}de[ce++]=f<<5|27,Nr.setBigUint64(ce,h),ce+=8}function Dt(f){let h=f.length;if(h<=23){let g=En.get(f);if(g){ge(g.bytes.length),de.set(g.bytes,ce),ce+=g.bytes.length,g.epoch=Bu;return}let y=ce;Dy(f,h);let w=ce,S=Uint8Array.prototype.slice.call(de,y,w);if(En.size>=Oy){if(Py)return;let x=0;for(let[_,A]of En){if(x>=1024)break;if(A.epoch!==Bu)En.delete(_),++x}if(x===0){Py=!0;return}}if(En.size<Oy)En.set(f,{epoch:Bu,bytes:S});return}Dy(f,h)}function Dy(f,h){if(ii){let g=h*3;ge(g+9);let y=Buffer.byteLength(f);$e(3,y),ce+=de.write(f,ce)}else{let g=h*3;ge(g+9);let y=ce,S=UB.encodeInto(f,de.subarray(y+9)).written,x;if(S<24)x=1;else if(S<256)x=2;else if(S<65536)x=3;else if(S<4294967296)x=5;else x=9;if(x<9)de.copyWithin(y+x,y+9,y+9+S);ce=y,$e(3,S),ce+=S}}function td(f){ge(9),de[ce++]=251,Nr.setFloat64(ce,f),ce+=8}function ai(f){ge(9);let h=f>=0,g=h?0:1,y=h?f:-f-1;$e(g,y)}function si(f){let h=f>=0,g=h?0:1,y=h?f:-f-BigInt(1);if(y<BigInt("18446744073709551616"))ge(9),Vy(g,y);else{let w=y.toString(2),S=Math.ceil(w.length/8),x=new Uint8Array(S),_=y;for(let A=S-1;A>=0;--A)x[A]=Number(_&BigInt(255)),_>>=BigInt(8);ge(S+16),de[ce++]=h?194:195,$e(2,S),de.set(x,ce),ce+=S}}function ri(f){ge(f.length+9),$e(2,f.length),de.set(f,ce),ce+=f.length}function Wy(f,h){if(ge(9),typeof f==="bigint")Vy(6,f);else $e(6,f);xn(h)}function Gy(f){let h=f.string,g=BigInt(0),y=h.search(/[eE]/);if(y!==-1)g=BigInt(h.slice(y+1)),h=h.slice(0,y);let w=h.indexOf("."),S=w===-1?0:h.length-w-1,x=g-BigInt(S),_=BigInt(h.replace(".",""));if(ge(9),de[ce++]=196,$e(4,2),ge(9),x>=-0x20000000000000n&&x<=0x1fffffffffffffn)ai(Number(x));else si(x);si(_)}function Wu(f){ge(18),$e(6,1);let h=f.getTime()/1000;if(Number.isInteger(h))ai(h);else td(h)}class rd extends ws{read(f,h){return xe=h,sd=Ky&&h instanceof Buffer,or=new DataView(h.buffer,h.byteOffset,h.byteLength),ne=0,Ue=h.length,ms=ms+1&65535,lt(mt.of(f))}readValue(f,h){return ni(mt.of(f),h)}}var Ky=typeof Buffer<"u",nd=new TextDecoder,xe=new Uint8Array(0),sd=!1,or=new DataView(new ArrayBuffer(0)),ne=0,Ue=0,od=2048,Uy=Array(od),zu=new Uint16Array(od),ms=0;function lt(f){if(ne>=Ue)throw Error("unexpected end of CBOR payload.");let h=(xe[ne]&224)>>5;if((xe[ne]&31)===31&&h>=2&&h<=5)return HB(f,h);switch(h){case 0:return GB();case 1:return KB();case 2:return di();case 3:return _n();case 4:return $B(f);case 5:return BB(f);case 6:return zB();case 7:return QB();default:throw Error(`unexpected CBOR major type ${h}.`)}}function $B(f){let h=ui(),g=f.isListSchema()?f.getValueSchema():f,y=Array(h);for(let w=0;w<h;++w)y[w]=lt(g);return y}function BB(f){let h=ui();if(f.isStructSchema())return LB(f,h,ne);let g=f.isMapSchema()?f.getValueSchema():f,y={};for(let w=0;w<h;++w){let S=_n();y[S]=lt(g)}return y}function LB(f,h,g){let y=f.isUnionSchema(),w=ed(f),{memberSchemas:S,encodedKeys:x,memberNames:_}=w,A=x.length,P={},D,U,B=0,z=!1,k=0;for(let R=0;R<h;++R){let N=Jy(x,A,k);if(N>=0){if(k=N+1,k>=A)k=0;let q=lt(S[N]);if(q!=null)P[_[N]]=q}else{let q=_n(),V=lt(mt.of(15));if(q==="__type"&&typeof V==="string")z=!0;else D=q,U=V,++B}}if(y){let R=!0;for(let N in P){if(!Je(P,N))continue;R=!1;break}if(R&&B===1)P.$unknown=[D,U]}else if(z){ne=g;let R=mt.of(15);for(let N=0;N<h;++N){let q=_n(),V=lt(R);if(!(q in P))P[q]=V}}return P}function zB(f){let h=ci(),g=typeof h==="bigint"?Number(h):h;if(g===1){let S=mt.of(15),x=lt(S);return gs(x)}if(g===2||g===3){let S=di(),x=BigInt(0);for(let _=0;_<S.length;++_)x=x<<BigInt(8)|BigInt(S[_]);return g===3?-x-BigInt(1):x}if(g===4){let S=mt.of(15),x=lt(S),[_,A]=x,P=A<0?-1:1,D=BigInt(P)*BigInt(A),U=String(D),B=A<0?"-":"",z;if(typeof _==="number"&&Math.abs(_)<=268435456){let R=_,N="0".repeat(Math.abs(R)+1)+U;if(z=R===0?N:N.slice(0,N.length+R)+"."+N.slice(R),z=z.replace(/^0+/g,""),z==="")z="0";if(z[0]===".")z="0"+z;z=B+z}else{let R=BigInt(_);if(U.length===1)z=B+U+"e"+String(R);else{let N=R+BigInt(U.length-1);z=B+U[0]+"."+U.slice(1)+"e"+String(N)}}return $y(z)}let y=mt.of(15),w=lt(y);return{tag:Qy(h),value:w}}function HB(f,h){switch(h){case 3:return qB();case 2:return jB();case 4:return VB(f);case 5:return WB(f);default:throw Error(`unexpected indefinite length for major ${h}.`)}}function qB(){ne+=1;let f=[],h=0;while(ne<Ue){if(xe[ne]===255){ne+=1;let y=new Uint8Array(h),w=0;for(let S=0;S<f.length;++S)y.set(f[S],w),w+=f[S].length;if(Ky)return Buffer.from(y.buffer,y.byteOffset,y.byteLength).toString("utf-8");return nd.decode(y)}let g=di();f.push(g),h+=g.length}throw Error("expected break marker.")}function jB(){ne+=1;let f=[],h=0;while(ne<Ue){if(xe[ne]===255){ne+=1;let y=new Uint8Array(h),w=0;for(let S=0;S<f.length;++S)y.set(f[S],w),w+=f[S].length;return y}let g=di();f.push(g),h+=g.length}throw Error("expected break marker.")}function VB(f){ne+=1;let h=f.isListSchema()?f.getValueSchema():f,g=[];while(ne<Ue){if(xe[ne]===255)return ne+=1,g;g.push(lt(h))}throw Error("expected break marker.")}function WB(f){if(ne+=1,f.isStructSchema()){let y=ed(f),{memberSchemas:w,encodedKeys:S,memberNames:x}=y,_=S.length,A=f.isUnionSchema(),P={},D,U,B=0,z=0;while(ne<Ue){if(xe[ne]===255){if(ne+=1,A){let R=!0;for(let N in P){if(!Je(P,N))continue;R=!1;break}if(R&&B===1)P.$unknown=[D,U]}return P}let k=Jy(S,_,z);if(k>=0){if(z=k+1,z>=_)z=0;let R=lt(w[k]);if(R!=null)P[x[k]]=R}else{let R=_n(),N=lt(mt.of(15));if(R!=="__type")D=R,U=N,++B}}throw Error("expected break marker.")}let h=f.isMapSchema()?f.getValueSchema():f,g={};while(ne<Ue){if(xe[ne]===255)return ne+=1,g;let y=_n();g[y]=lt(h)}throw Error("expected break marker.")}function Jy(f,h,g){let y=f[g];if(ne+y.length<=Ue&&Fy(ne,y))return ne+=y.length,g;for(let w=0;w<h;++w){if(w===g)continue;let S=f[w];if(ne+S.length<=Ue&&Fy(ne,S))return ne+=S.length,w}return-1}function Fy(f,h){let g=h.length;if(xe[f]!==h[0])return!1;for(let y=1;y<g;++y)if(xe[f+y]!==h[y])return!1;return!0}function ci(){let f=xe[ne]&31;if(f<24)return ne+=1,f;switch(f){case 24:if(Ue-ne<2)Vt(1);return ne+=2,xe[ne-1];case 25:if(Ue-ne<3)Vt(2);return ne+=3,or.getUint16(ne-2);case 26:if(Ue-ne<5)Vt(4);return ne+=5,or.getUint32(ne-4);case 27:{if(Ue-ne<9)Vt(8);ne+=9;let h=or.getUint32(ne-8);if(h<2097152)return h*4294967296+or.getUint32(ne-4);return or.getBigUint64(ne-8)}default:throw Error(`unexpected minor value ${f}.`)}}function ui(){let f=ci();return typeof f==="bigint"?Number(f):f}function GB(){let f=ci();return Qy(f)}function KB(){let f=ci();if(typeof f==="bigint")return BigInt(-1)-f;return-1-f}function di(){let f=ui();if(Ue-ne<f)Vt(f);let h=ne;return ne+=f,xe.subarray(h,h+f)}function _n(){let f=ui();if(Ue-ne<f)Vt(f);let h=ne;if(ne+=f,f<24)return JB(h,f);if(sd)return xe.toString("utf-8",h,h+f);return nd.decode(xe.subarray(h,h+f))}function JB(f,h){let g=h;for(let x=0;x<h;++x)g=g*31+xe[f+x]|0;let y=g>>>0&od-1,w=Uy[y];if(w!==void 0&&w.length===h){let x=!0;for(let _=0;_<h;++_)if(w.charCodeAt(_)!==xe[f+_]){x=!1;break}if(x)return zu[y]=ms,w}let S=sd?xe.toString("utf-8",f,f+h):nd.decode(xe.subarray(f,f+h));if(zu[y]!==ms)Uy[y]=S,zu[y]=ms;return S}function QB(){let f=ne,h=xe[f]&31;switch(h){case 21:return ne=f+1,!0;case 20:return ne=f+1,!1;case 22:return ne=f+1,null;case 23:return ne=f+1,null;case 25:{if(Ue-f<3)Vt(2);return ne=f+3,XB(xe[f+1],xe[f+2])}case 26:{if(Ue-f<5)Vt(4);return ne=f+5,or.getFloat32(f+1)}case 27:{if(Ue-f<9)Vt(8);return ne=f+9,or.getFloat64(f+1)}default:throw Error(`unexpected minor value ${h} for major 7.`)}}function XB(f,h){let g=f>>7,y=(f&124)>>2,w=(f&3)<<8|h,S=g===0?1:-1;if(y===0){if(w===0)return 0;return S*(Math.pow(2,-14)*(w/1024))}else if(y===31){if(w===0)return S*(1/0);return NaN}return S*(Math.pow(2,y-15)*(1+w/1024))}function Qy(f){if(typeof f==="number")return f;let h=Number(f);if(Number.MIN_SAFE_INTEGER<=h&&h<=Number.MAX_SAFE_INTEGER)return h;return f}function Vt(f){throw Error(`CBOR: length ${f} greater than remaining buffer length.`)}function ni(f,h){if(f.isTimestampSchema()){if(typeof h==="number")return gs(h);if(typeof h==="object"&&h!==null){if(h.tag===1&&"value"in h)return gs(h.value)}}if(f.isBlobSchema())return h;if(typeof h>"u"||typeof h==="boolean"||typeof h==="number"||typeof h==="string"||typeof h==="bigint"||typeof h==="symbol")return h;if(typeof h!=="object"||h===null)return h;if("byteLength"in h)return h;if(h instanceof Date)return h;if(h instanceof Ss)return h;if(f.isDocumentSchema())return h;if(f.isListSchema()){let y=f.getValueSchema(),w=[];for(let S of h)w.push(ni(y,S));return w}let g={};if(f.isMapSchema()){let y=f.getValueSchema();for(let w in h){if(!Je(h,w))continue;g[w]=ni(y,h[w])}}else if(f.isStructSchema()){let y=f.isUnionSchema(),w;if(y){w=new Set;for(let S in h){if(!Je(h,S))continue;if(S!=="__type")w.add(S)}}for(let[S,x]of f.structIterator()){if(y)w.delete(S);if(h[S]!=null)g[S]=ni(x,h[S])}if(y&&w?.size===1){let S=!0;for(let x in g){if(!Je(g,x))continue;S=!1;break}if(S){let x=w.values().next().value;g.$unknown=[x,h[x]]}}else if(typeof h.__type==="string")for(let S in h){if(!Je(h,S))continue;if(!(S in g))g[S]=h[S]}}return g}class id extends ws{createSerializer(){let f=new Zu;return f.setSerdeContext(this.serdeContext),f}createDeserializer(){let f=new rd;return f.setSerdeContext(this.serdeContext),f}}class Xy extends dB{codec=new id;serializer=this.codec.createSerializer();deserializer=this.codec.createDeserializer();getShapeId(){return"smithy.protocols#rpcv2Cbor"}getPayloadCodec(){return this.codec}getSmithyProtocolHeaderValue(){return"rpc-v2-cbor"}applyEmptyBody(f){if(!f.body)this.serializer.write(15,{}),f.body=this.serializer.flush();if(f.body instanceof Uint8Array)f.headers["content-length"]=String(f.body.byteLength)}async handleError(f,h,g,y,w){let S=qy(g,y)??"Unknown",x=["*"],{defaultNamespace:_}=this.options;x.unshift(_);let[A,P]=(()=>{if(S.includes("#"))return S.split("#");return[void 0,S]})();if(A)x.unshift(A);let D={$metadata:w,$fault:g.statusCode<500?"client":"server"},U=[this.compositeErrorRegistry];if(A)U.push(Ry.for(A));U.push(Ry.for(_));let[B,z,k]=this.resolveError(P,x,U);if(k==="native"||k==="synthetic"){if(y.Message)y.message=y.Message;let W=k==="synthetic"?new z({name:P}):Error(P);throw Object.assign(W,D,y)}let R=mt.of(B),N=y.message??y.Message??"Unknown",q=new z({}),V={};for(let[W,G]of R.structIterator())V[W]=this.deserializer.readValue(G,y[W]);throw Object.assign(q,D,{$fault:R.getMergedTraits().error,message:N},V)}getDefaultContentType(){return"application/cbor"}}class Yy extends ws{value;write(f,h){this.value=this.serialize(f,h)}serialize(f,h){let g=mt.of(f);if(h==null){if(g.isIdempotencyToken())return By();return h}if(g.isBlobSchema()){if(typeof h==="string")return(this.serdeContext?.base64Decoder??Gu)(h);return h}if(g.isTimestampSchema()){if(typeof h==="number"||typeof h==="bigint")return ti(new Date(Number(h)/1000|0));return ti(h)}if(typeof h==="function"||typeof h==="object"){let y=h;if(g.isListSchema()&&Array.isArray(y)){let S=!!g.getMergedTraits().sparse,x=[],_=0;for(let A of y){let P=this.serialize(g.getValueSchema(),A);if(P!=null||S)x[_++]=P}return x}if(y instanceof Date)return ti(y);let w={};if(g.isMapSchema()){let S=!!g.getMergedTraits().sparse;for(let x in y){if(!Je(y,x))continue;let _=this.serialize(g.getValueSchema(),y[x]);if(_!=null||S)w[x]=_}}else if(g.isStructSchema()){for(let[x,_]of g.structIterator()){let A=this.serialize(_,y[x]);if(A!=null)w[x]=A}if(g.isUnionSchema()&&Array.isArray(y.$unknown)){let[x,_]=y.$unknown;w[x]=_}else if(typeof y.__type==="string")for(let x in y){if(!Je(y,x))continue;if(!(x in w))w[x]=this.serialize(15,y[x])}}else if(g.isDocumentSchema()){if(Array.isArray(y)){let S=[],x=0;for(let _ of y)S[x++]=this.serialize(g.getValueSchema(),_);return S}for(let S in y){if(!Je(y,S))continue;w[S]=this.serialize(g.getValueSchema(),y[S])}}else if(g.isBigDecimalSchema())return y;return w}return h}flush(){let f=oi.serialize(this.value);return this.value=void 0,f}}class Zy extends ws{read(f,h){let g=oi.deserialize(h);return this.readValue(f,g)}readValue(f,h){let g=mt.of(f);if(g.isTimestampSchema()){if(typeof h==="number")return gs(h);if(typeof h==="object"){if(h.tag===1&&"value"in h)return gs(h.value)}}if(g.isBlobSchema()){if(typeof h==="string")return(this.serdeContext?.base64Decoder??Gu)(h);return h}if(typeof h>"u"||typeof h==="boolean"||typeof h==="number"||typeof h==="string"||typeof h==="bigint"||typeof h==="symbol")return h;else if(typeof h==="object"){if(h===null)return null;if("byteLength"in h)return h;if(h instanceof Date)return h;if(g.isDocumentSchema())return h;if(g.isListSchema()){let w=[],S=g.getValueSchema();for(let x of h){let _=this.readValue(S,x);w.push(_)}return w}let y={};if(g.isMapSchema()){let w=g.getValueSchema();for(let S in h){if(!Je(h,S))continue;let x=this.readValue(w,h[S]);y[S]=x}}else if(g.isStructSchema()){let w=g.isUnionSchema(),S;if(w){S=new Set;for(let x in h){if(!Je(h,x))continue;if(x!=="__type")S.add(x)}}for(let[x,_]of g.structIterator()){if(w)S.delete(x);if(h[x]!=null)y[x]=this.readValue(_,h[x])}if(w&&S?.size===1){let x=!0;for(let _ in y){if(!Je(y,_))continue;x=!1;break}if(x){let _=S.values().next().value;y.$unknown=[_,h[_]]}}else if(typeof h.__type==="string")for(let x in h){if(!Je(h,x))continue;if(!(x in y))y[x]=h[x]}}else if(h instanceof Ss)return h;return y}else return h}}YB.CborCodec=id;YB.CborShapeDeserializer=Zy;YB.CborShapeDeserializer2=rd;YB.CborShapeSerializer=Yy;YB.CborShapeSerializer2=Zu;YB.SmithyRpcV2CborProtocol=Xy;YB.buildHttpRpcRequest=MB;YB.cbor=oi;YB.checkCborResponse=PB;YB.dateToTag=ti;YB.loadSmithyRpcV2CborErrorCode=qy;YB.parseCborBody=Hy;YB.parseCborErrorBody=OB;YB.tag=Ku;YB.tagSymbol=Es});var tS=i(function(bL){var pL=/[&<>"]/g,mL={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function gL(f){return f.replace(pL,(h)=>mL[h])}var yL=/[&"'<>\r\n\u0085\u2028]/g,SL={"&":"&amp;",'"':"&quot;","'":"&apos;","<":"&lt;",">":"&gt;","\r":"&#x0D;","\n":"&#x0A;","…":"&#x85;","\u2028":"&#x2028;"};function wL(f){return f.replace(yL,(h)=>SL[h])}class cd{value;constructor(f){this.value=f}toString(){return wL(""+this.value)}}class xs{name;children;attributes={};static of(f,h,g){let y=new xs(f);if(h!==void 0)y.addChildNode(new cd(h));if(g!==void 0)y.withName(g);return y}constructor(f,h=[]){this.name=f,this.children=h}withName(f){return this.name=f,this}addAttribute(f,h){return this.attributes[f]=h,this}addChildNode(f){return this.children.push(f),this}removeAttribute(f){return delete this.attributes[f],this}n(f){return this.name=f,this}c(f){return this.children.push(f),this}a(f,h){if(h!=null)this.attributes[f]=h;return this}cc(f,h,g=h){if(f[h]!=null){let y=xs.of(h,f[h]).withName(g);this.c(y)}}l(f,h,g,y){if(f[h]!=null)y().map((S)=>{S.withName(g),this.c(S)})}lc(f,h,g,y){if(f[h]!=null){let w=y(),S=new xs(g);w.map((x)=>{S.c(x)}),this.c(S)}}toString(){let f=Boolean(this.children.length),h=`<${this.name}`,g=this.attributes;for(let y of Object.keys(g)){let w=g[y];if(w!=null)h+=` ${y}="${gL(""+w)}"`}return h+=!f?"/>":`>${this.children.map((y)=>y.toString()).join("")}</${this.name}>`}}function ad(f){Object.defineProperty(f,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function EL(f){return new ud(f).parse()}class ud{x;i=0;z;constructor(f){this.x=f,this.x=f.replace(/\r\n?/g,`
54
+ `),this.z=this.x.length}parse(){let f=this,{z:h}=f;while(f.i<h){if(f.trim(),f.i>=h)break;if(f.isNext("<?"))f.readTo("?>"),f.trim();else if(f.isNext("<!--"))f.readTo("-->"),f.trim();else if(f.isNext("<!DOCTYPE",!1))f.skipDoctype(),f.trim();else if(f.x[f.i]==="<"){let g=f.parseTag();return{[g.tag]:g.value}}else throw Error("@aws-sdk XML parse error: unexpected content.")}throw Error("@aws-sdk XML parse error: no root element.")}isNext(f,h=!0){let g=this;if(h)return g.x.startsWith(f,g.i);return g.x.toLowerCase().startsWith(f.toLowerCase(),g.i)}readTo(f){let h=this,g=h.x.indexOf(f,h.i);if(g===-1)throw Error(`@aws-sdk XML parse error: expected "${f}" not found.`);let y=h.x.slice(h.i,g);return h.i=g+f.length,y}trim(){let f=this;while(f.i<f.z&&` \r
55
+ `.includes(f.x[f.i]))++f.i}readAttrValue(){let f=this,h=f.x[f.i];++f.i;let g="";while(f.i<f.z&&f.x[f.i]!==h)g+=f.x[f.i++];return++f.i,f.decodeEntities(g)}parseTag(){let f=this;++f.i;let h="";while(f.i<f.z&&!` \r
56
+ >/`.includes(f.x[f.i]))h+=f.x[f.i++];let g=!1,y={};while(f.i<f.z){if(f.trim(),">/".includes(f.x[f.i]))break;let P="";while(f.i<f.z&&!`= \r
57
+ >/?`.includes(f.x[f.i]))P+=f.x[f.i++];if(f.trim(),f.x[f.i]!=="=")break;if(++f.i,f.trim(),P==="__proto__")ad(y);y[P]=f.readAttrValue(),g=!0}if(f.i>=f.z)throw Error("@aws-sdk XML parse error: unexpected end of input.");if(f.x[f.i]==="/"){if(++f.i,f.i>=f.z||f.x[f.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of self-closing tag.");return++f.i,{tag:h,value:g?y:""}}if(f.x[f.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of opening tag.");++f.i;let w=[],S=[],x=!1;while(f.i<f.z){if(f.isNext("</"))break;if(f.x[f.i]==="<")if(f.isNext("<!--"))f.readTo("-->");else if(f.isNext("<![CDATA["))f.i+=9,w.push(f.readTo("]]>"));else if(f.isNext("<?"))f.readTo("?>");else x=!0,S.push(f.parseTag());else{let P="";while(f.i<f.z&&f.x[f.i]!=="<")P+=f.x[f.i++];w.push(f.decodeEntities(P))}}if(!f.isNext("</"))throw Error(`@aws-sdk XML parse error: missing closing tag </${h}>.`);f.i+=2;let _=f.readTo(">").trim();if(_!==h)throw Error(`@aws-sdk XML parse error: mismatched tags <${h}> and </${_}>.`);if(!g&&w.length===0&&!x)return{tag:h,value:""};if(!g&&!x){let P=w.length===1?w[0]:w.join("");if(P.trim()===""&&P.includes(`
58
+ `))return{tag:h,value:""};return{tag:h,value:P}}let A={};for(let P of w){if(P.trim()===""&&P.includes(`
59
+ `))continue;A["#text"]="#text"in A?A["#text"]+P:P}for(let P of S){if(P.tag==="__proto__")ad(A);if(P.tag in A)if(Array.isArray(A[P.tag]))A[P.tag].push(P.value);else A[P.tag]=[A[P.tag],P.value];else A[P.tag]=P.value}for(let[P,D]of Object.entries(y)){if(P==="__proto__")ad(A);A[P]=D}return{tag:h,value:A}}static ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};skipDoctype(){let f=this;f.i+=9;let h=0;while(f.i<f.z){let g=f.x[f.i];if(g==="[")++h;else if(g==="]")--h;else if(g===">"&&h===0){++f.i;return}++f.i}throw Error("@aws-sdk XML parse error: unclosed DOCTYPE.")}decodeEntities(f){return f.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g,(h,g,y,w)=>{if(g)return String.fromCharCode(parseInt(g,16));if(y)return String.fromCharCode(parseInt(y,10));return ud.ENTITIES[w]??""})}}bL.XmlNode=xs;bL.XmlText=cd;bL.parseXML=EL});var Ts=i(function(WL){var{SmithyRpcV2CborProtocol:AL,loadSmithyRpcV2CborErrorCode:IL}=eS(),{TypeRegistry:rS,NormalizedSchema:qe,deref:iS}=Rt(),{decorateServiceException:nS,getValueFromTextNode:aS}=ct(),{RpcProtocol:cS,JsonCodec2:fd,loadJsonRpcErrorCode:uS,HttpBindingProtocol:dS,HttpInterceptingShapeSerializer:lS,HttpInterceptingShapeDeserializer:fS,loadRestJsonErrorCode:hS,SmithyRpcV2JsonProtocol:CL,loadSmithyRpcV2JsonErrorCode:RL,FromStringShapeDeserializer:vL,determineTimestampFormat:pS,extendedEncodeURIComponent:sS,collectBody:dd}=Ne(),{JsonCodec:kL,JsonShapeDeserializer:NL,JsonShapeDeserializer2:OL,JsonShapeSerializer:PL,JsonShapeSerializer2:ML,parseJsonBody:DL,parseJsonErrorBody:UL}=Ne();WL.JsonCodec=kL;WL.JsonCodec2=fd;WL.JsonShapeDeserializer=NL;WL.JsonShapeDeserializer2=OL;WL.JsonShapeSerializer=PL;WL.JsonShapeSerializer2=ML;WL.loadJsonRpcErrorCode=uS;WL.loadRestJsonErrorCode=hS;WL.parseJsonBody=DL;WL.parseJsonErrorBody=UL;var{parseXML:mS,XmlNode:bt,XmlText:oS}=tS(),{toUtf8:gS,toBase64:yS,generateIdempotencyToken:SS,NumericValue:wS,dateToUtcString:ld,fromBase64:FL,expectUnion:$L}=Ke();class Or{queryCompat;errorRegistry;constructor(f=!1){this.queryCompat=f}resolveRestContentType(f,h){let g=h.getMemberSchemas(),y=Object.values(g).find((w)=>!!w.getMergedTraits().httpPayload);if(y){let w=y.getMergedTraits().mediaType;if(w)return w;else if(y.isStringSchema())return"text/plain";else if(y.isBlobSchema())return"application/octet-stream";else return f}else if(!h.isUnitSchema()){if(Object.values(g).find((S)=>{let{httpQuery:x,httpQueryParams:_,httpHeader:A,httpLabel:P,httpPrefixHeaders:D}=S.getMergedTraits();return!x&&!_&&!A&&!P&&D===void 0}))return f}}async getErrorSchemaOrThrowBaseException(f,h,g,y,w,S){let x=f;if(f.includes("#"))[,x]=f.split("#");let _={$metadata:w,$fault:g.statusCode<500?"client":"server"};if(!this.errorRegistry)throw Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:S?.(this.errorRegistry,x)??this.errorRegistry.getSchema(f),errorMetadata:_}}catch(A){y.message=y.message??y.Message??"UnknownError";let P=this.errorRegistry,D=P.getBaseException();if(D){let z=P.getErrorCtor(D)??Error;throw this.decorateServiceException(Object.assign(new z({name:x}),_),y)}let U=y,B=U?.message??U?.Message??U?.Error?.Message??U?.Error?.message;throw this.decorateServiceException(Object.assign(Error(B),{name:x},_),y)}}compose(f,h,g){let y=g;if(h.includes("#"))[y]=h.split("#");let w=rS.for(y),S=rS.for("smithy.ts.sdk.synthetic."+g);f.copyFrom(w),f.copyFrom(S),this.errorRegistry=f}decorateServiceException(f,h={}){if(this.queryCompat){let g=f.Message??h.Message,y=nS(f,h);if(g)y.message=g;let w=y.Error??{};w.Type=y.Error?.Type,w.Code=y.Error?.Code,w.Message=y.Error?.message??y.Error?.Message??g,y.Error=w;let S=y.$metadata.requestId;if(S)y.RequestId=S;return y}return nS(f,h)}setQueryCompatError(f,h){let g=h.headers?.["x-amzn-query-error"];if(f!==void 0&&g!=null){let[y,w]=g.split(";"),S=Object.keys(f),x={Code:y,Type:w};f.Code=y,f.Type=w;for(let _=0;_<S.length;_++){let A=S[_];x[A==="message"?"Message":A]=f[A]}delete x.__type,f.Error=x}}queryCompatOutput(f,h){if(f.Error)h.Error=f.Error;if(f.Type)h.Type=f.Type;if(f.Code)h.Code=f.Code}findQueryCompatibleError(f,h){try{return f.getSchema(h)}catch(g){return f.find((y)=>qe.of(y).getMergedTraits().awsQueryError?.[0]===h)}}}class ES extends AL{awsQueryCompatible;mixin;constructor({defaultNamespace:f,errorTypeRegistries:h,awsQueryCompatible:g}){super({defaultNamespace:f,errorTypeRegistries:h});this.awsQueryCompatible=!!g,this.mixin=new Or(this.awsQueryCompatible)}async serializeRequest(f,h,g){let y=await super.serializeRequest(f,h,g);if(this.awsQueryCompatible)y.headers["x-amzn-query-mode"]="true";return y}async handleError(f,h,g,y,w){if(this.awsQueryCompatible)this.mixin.setQueryCompatError(y,g);let S=(()=>{let z=g.headers["x-amzn-query-error"];if(z&&this.awsQueryCompatible)return z.split(";")[0];return IL(g,y)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,S,this.options.defaultNamespace);let{errorSchema:x,errorMetadata:_}=await this.mixin.getErrorSchemaOrThrowBaseException(S,this.options.defaultNamespace,g,y,w,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),A=qe.of(x),P=y.message??y.Message??"UnknownError",U=new(this.compositeErrorRegistry.getErrorCtor(x)??Error)({}),B={};for(let[z,k]of A.structIterator())if(y[z]!=null)B[z]=this.deserializer.readValue(k,y[z]);if(this.awsQueryCompatible)this.mixin.queryCompatOutput(y,B);throw this.mixin.decorateServiceException(Object.assign(U,_,{$fault:A.getMergedTraits().error,message:P},B),y)}}class li extends cS{serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:f,errorTypeRegistries:h,serviceTarget:g,awsQueryCompatible:y,jsonCodec:w}){super({defaultNamespace:f,errorTypeRegistries:h});this.serviceTarget=g,this.codec=w??new fd({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!y,this.mixin=new Or(this.awsQueryCompatible)}async serializeRequest(f,h,g){let y=await super.serializeRequest(f,h,g);if(!y.path.endsWith("/"))y.path+="/";if(y.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,y.headers["x-amz-target"]=`${this.serviceTarget}.${f.name}`,this.awsQueryCompatible)y.headers["x-amzn-query-mode"]="true";if(iS(f.input)==="unit"||!y.body)y.body="{}";return y}getPayloadCodec(){return this.codec}async handleError(f,h,g,y,w){let{awsQueryCompatible:S}=this;if(S)this.mixin.setQueryCompatError(y,g);let x=uS(g,y,S)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,x,this.options.defaultNamespace);let{errorSchema:_,errorMetadata:A}=await this.mixin.getErrorSchemaOrThrowBaseException(x,this.options.defaultNamespace,g,y,w,S?this.mixin.findQueryCompatibleError:void 0),P=qe.of(_),D=y.message??y.Message??"UnknownError",B=new(this.compositeErrorRegistry.getErrorCtor(_)??Error)({}),z={},k=this.codec.createDeserializer();for(let[R,N]of P.structIterator())if(y[R]!=null)z[R]=k.readObject(N,y[R]);if(S)this.mixin.queryCompatOutput(y,z);throw this.mixin.decorateServiceException(Object.assign(B,A,{$fault:P.getMergedTraits().error,message:D},z),y)}}class bS extends li{constructor({defaultNamespace:f,errorTypeRegistries:h,serviceTarget:g,awsQueryCompatible:y,jsonCodec:w}){super({defaultNamespace:f,errorTypeRegistries:h,serviceTarget:g,awsQueryCompatible:y,jsonCodec:w})}getShapeId(){return"aws.protocols#awsJson1_0"}getJsonRpcVersion(){return"1.0"}getDefaultContentType(){return"application/x-amz-json-1.0"}}class xS extends li{constructor({defaultNamespace:f,errorTypeRegistries:h,serviceTarget:g,awsQueryCompatible:y,jsonCodec:w}){super({defaultNamespace:f,errorTypeRegistries:h,serviceTarget:g,awsQueryCompatible:y,jsonCodec:w})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}class _S extends dS{serializer;deserializer;codec;mixin=new Or;constructor({defaultNamespace:f,errorTypeRegistries:h,jsonCodec:g}){super({defaultNamespace:f,errorTypeRegistries:h});let y={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=g??new fd(y),this.serializer=new lS(this.codec.createSerializer(),y),this.deserializer=new fS(this.codec.createDeserializer(),y)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(f){this.codec.setSerdeContext(f),super.setSerdeContext(f)}async serializeRequest(f,h,g){let y=await super.serializeRequest(f,h,g),w=qe.of(f.input);if(!y.headers["content-type"]){let S=this.mixin.resolveRestContentType(this.getDefaultContentType(),w);if(S)y.headers["content-type"]=S}if(y.body==null&&y.headers["content-type"]===this.getDefaultContentType())y.body="{}";return y}async deserializeResponse(f,h,g){let y=await super.deserializeResponse(f,h,g),w=qe.of(f.output);for(let[S,x]of w.structIterator())if(x.getMemberTraits().httpPayload&&!(S in y))y[S]=null;return y}async handleError(f,h,g,y,w){let S=hS(g,y)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,S,this.options.defaultNamespace);let{errorSchema:x,errorMetadata:_}=await this.mixin.getErrorSchemaOrThrowBaseException(S,this.options.defaultNamespace,g,y,w),A=qe.of(x),P=y.message??y.Message??"UnknownError",U=new(this.compositeErrorRegistry.getErrorCtor(x)??Error)({});await this.deserializeHttpMessage(x,h,g,y);let B={},z=this.codec.createDeserializer();for(let[k,R]of A.structIterator()){let N=R.getMergedTraits().jsonName??k;B[k]=z.readObject(R,y[N])}throw this.mixin.decorateServiceException(Object.assign(U,_,{$fault:A.getMergedTraits().error,message:P},B),y)}getDefaultContentType(){return"application/json"}}class TS extends CL{awsQueryCompatible;mixin;constructor({defaultNamespace:f,errorTypeRegistries:h,awsQueryCompatible:g}){super({defaultNamespace:f,errorTypeRegistries:h});this.awsQueryCompatible=!!g,this.mixin=new Or(this.awsQueryCompatible)}async serializeRequest(f,h,g){let y=await super.serializeRequest(f,h,g);if(this.awsQueryCompatible)y.headers["x-amzn-query-mode"]="true";return y}async handleError(f,h,g,y,w){if(this.awsQueryCompatible)this.mixin.setQueryCompatError(y,g);let S=(()=>{let k=g.headers["x-amzn-query-error"];if(k&&this.awsQueryCompatible)return k.split(";")[0];return RL(g,y)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,S,this.options.defaultNamespace);let{errorSchema:x,errorMetadata:_}=await this.mixin.getErrorSchemaOrThrowBaseException(S,this.options.defaultNamespace,g,y,w,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),A=qe.of(x),P=y.message??y.Message??"UnknownError",U=new(this.compositeErrorRegistry.getErrorCtor(x)??Error)({}),B={},z=this.getPayloadCodec().createDeserializer();for(let[k,R]of A.structIterator())if(y[k]!=null)B[k]=z.readObject(R,y[k]);if(this.awsQueryCompatible)this.mixin.queryCompatOutput(y,B);throw this.mixin.decorateServiceException(Object.assign(U,_,{$fault:A.getMergedTraits().error,message:P},B),y)}}class _s{serdeContext;setSerdeContext(f){this.serdeContext=f}}class AS{from;to;keys;constructor(f,h){this.from=f,this.to=h;let g=Object.keys(this.from),y=new Set(g);y.delete("__type"),this.keys=y}mark(f){this.keys.delete(f)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){let f=this.keys.values().next().value,h=this.from[f];this.to.$unknown=[f,h]}}}function BL(f){Object.defineProperty(f,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0})}class fi extends _s{settings;stringDeserializer;constructor(f){super();this.settings=f,this.stringDeserializer=new vL(f)}setSerdeContext(f){this.serdeContext=f,this.stringDeserializer.setSerdeContext(f)}read(f,h,g){let y=qe.of(f),w=y.getMemberSchemas();if(y.isStructSchema()&&y.isMemberSchema()&&!!Object.values(w).find((A)=>!!A.getMemberTraits().eventPayload)){let A={},P=Object.keys(w)[0];if(w[P].isBlobSchema())A[P]=h;else A[P]=this.read(w[P],h);return A}let x=(this.serdeContext?.utf8Encoder??gS)(h),_=this.parseXml(x);return this.readSchema(f,g?_[g]:_)}readSchema(f,h){let g=qe.of(f);if(g.isUnitSchema())return;let y=g.getMergedTraits();if(g.isListSchema()&&!Array.isArray(h))return this.readSchema(g,[h]);if(h==null)return h;if(typeof h==="object"){let w=!!y.xmlFlattened;if(g.isListSchema()){let x=g.getValueSchema(),_=[],A=x.getMergedTraits().xmlName??"member",P=w?h:(h[0]??h)[A];if(P==null)return _;let D=Array.isArray(P)?P:[P];for(let U of D)_.push(this.readSchema(x,U));return _}let S={};if(g.isMapSchema()){let x=g.getKeySchema(),_=g.getValueSchema(),A;if(w)A=Array.isArray(h)?h:[h];else A=Array.isArray(h.entry)?h.entry:[h.entry];let P=x.getMergedTraits().xmlName??"key",D=_.getMergedTraits().xmlName??"value";for(let U of A){let B=U[P],z=U[D];if(B==="__proto__")BL(S);S[B]=this.readSchema(_,z)}return S}if(g.isStructSchema()){let x=g.isUnionSchema(),_;if(x)_=new AS(h,S);for(let[A,P]of g.structIterator()){let D=P.getMergedTraits(),U=!D.httpPayload?P.getMemberTraits().xmlName??A:D.xmlName??P.getName();if(x)_.mark(U);if(h[U]!=null)S[A]=this.readSchema(P,h[U])}if(x)_.writeUnknown();return S}if(g.isDocumentSchema())return h;throw Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${g.getName(!0)}`)}if(g.isListSchema())return[];if(g.isMapSchema()||g.isStructSchema())return{};return this.stringDeserializer.read(g,h)}parseXml(f){if(f.length){let h;try{h=mS(f)}catch(S){if(S&&typeof S==="object")Object.defineProperty(S,"$responseBodyText",{value:f});throw S}let g="#text",y=Object.keys(h)[0],w=h[y];if(w[g])w[y]=w[g],delete w[g];return aS(w)}return{}}}class hd extends _s{settings;buffer;constructor(f){super();this.settings=f}write(f,h,g=""){if(this.buffer===void 0)this.buffer="";let y=qe.of(f);if(g&&!g.endsWith("."))g+=".";if(y.isBlobSchema()){if(typeof h==="string"||h instanceof Uint8Array)this.writeKey(g),this.writeValue((this.serdeContext?.base64Encoder??yS)(h))}else if(y.isBooleanSchema()||y.isNumericSchema()||y.isStringSchema()){if(h!=null)this.writeKey(g),this.writeValue(String(h));else if(y.isIdempotencyToken())this.writeKey(g),this.writeValue(SS())}else if(y.isBigIntegerSchema()){if(h!=null)this.writeKey(g),this.writeValue(String(h))}else if(y.isBigDecimalSchema()){if(h!=null)this.writeKey(g),this.writeValue(h instanceof wS?h.string:String(h))}else if(y.isTimestampSchema()){if(h instanceof Date)switch(this.writeKey(g),pS(y,this.settings)){case 5:this.writeValue(h.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(ld(h));break;case 7:this.writeValue(String(h.getTime()/1000));break}}else if(y.isDocumentSchema())if(Array.isArray(h))this.write(79,h,g);else if(h instanceof Date)this.write(4,h,g);else if(h instanceof Uint8Array)this.write(21,h,g);else if(h&&typeof h==="object")this.write(143,h,g);else this.writeKey(g),this.writeValue(String(h));else if(y.isListSchema()){if(Array.isArray(h))if(h.length===0){if(this.settings.serializeEmptyLists)this.writeKey(g),this.writeValue("")}else{let w=y.getValueSchema(),S=this.settings.flattenLists||y.getMergedTraits().xmlFlattened,x=1;for(let _ of h){if(_==null)continue;let A=w.getMergedTraits(),P=this.getKey("member",A.xmlName,A.ec2QueryName),D=S?`${g}${x}`:`${g}${P}.${x}`;this.write(w,_,D),++x}}}else if(y.isMapSchema()){if(h&&typeof h==="object"){let w=y.getKeySchema(),S=y.getValueSchema(),x=y.getMergedTraits().xmlFlattened,_=1;for(let A in h){let P=h[A];if(P==null)continue;let D=w.getMergedTraits(),U=this.getKey("key",D.xmlName,D.ec2QueryName),B=x?`${g}${_}.${U}`:`${g}entry.${_}.${U}`,z=S.getMergedTraits(),k=this.getKey("value",z.xmlName,z.ec2QueryName),R=x?`${g}${_}.${k}`:`${g}entry.${_}.${k}`;this.write(w,A,B),this.write(S,P,R),++_}}}else if(y.isStructSchema()){if(h&&typeof h==="object"){let w=!1;for(let[S,x]of y.structIterator()){if(h[S]==null&&!x.isIdempotencyToken())continue;let _=x.getMergedTraits(),A=this.getKey(S,_.xmlName,_.ec2QueryName,"struct"),P=`${g}${A}`;this.write(x,h[S],P),w=!0}if(!w&&y.isUnionSchema()){let{$unknown:S}=h;if(Array.isArray(S)){let[x,_]=S,A=`${g}${x}`;this.write(15,_,A)}}}}else if(y.isUnitSchema());else throw Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${y.getName(!0)}`)}flush(){if(this.buffer===void 0)throw Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.");let f=this.buffer;return delete this.buffer,f}getKey(f,h,g,y){let{ec2:w,capitalizeKeys:S}=this.settings;if(w&&g)return g;let x=h??f;if(S&&y==="struct")return x[0].toUpperCase()+x.slice(1);return x}writeKey(f){if(f.endsWith("."))f=f.slice(0,f.length-1);this.buffer+=`&${sS(f)}=`}writeValue(f){this.buffer+=sS(f)}}class pd extends cS{options;serializer;deserializer;mixin=new Or;constructor(f){super({defaultNamespace:f.defaultNamespace,errorTypeRegistries:f.errorTypeRegistries});this.options=f;let h={timestampFormat:{useTrait:!0,default:5},httpBindings:!1,xmlNamespace:f.xmlNamespace,serviceNamespace:f.defaultNamespace,serializeEmptyLists:!0};this.serializer=new hd(h),this.deserializer=new fi(h)}getShapeId(){return"aws.protocols#awsQuery"}setSerdeContext(f){this.serializer.setSerdeContext(f),this.deserializer.setSerdeContext(f)}getPayloadCodec(){throw Error("AWSQuery protocol has no payload codec.")}async serializeRequest(f,h,g){let y=await super.serializeRequest(f,h,g);if(!y.path.endsWith("/"))y.path+="/";if(y.headers["content-type"]="application/x-www-form-urlencoded",iS(f.input)==="unit"||!y.body)y.body="";let w=f.name.split("#")[1]??f.name;if(y.body=`Action=${w}&Version=${this.options.version}`+y.body,y.body.endsWith("&"))y.body=y.body.slice(-1);return y}async deserializeResponse(f,h,g){let y=this.deserializer,w=qe.of(f.output),S={};if(g.statusCode>=300){let P=await dd(g.body,h);if(P.byteLength>0)Object.assign(S,await y.read(15,P));await this.handleError(f,h,g,S,this.deserializeMetadata(g))}for(let P in g.headers){let D=g.headers[P];delete g.headers[P],g.headers[P.toLowerCase()]=D}let x=f.name.split("#")[1]??f.name,_=w.isStructSchema()&&this.useNestedResult()?x+"Result":void 0,A=await dd(g.body,h);if(A.byteLength>0)Object.assign(S,await y.read(w,A,_));return S.$metadata=this.deserializeMetadata(g),S}useNestedResult(){return!0}async handleError(f,h,g,y,w){let S=this.loadQueryErrorCode(g,y)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,S,this.options.defaultNamespace);let x=this.loadQueryError(y)??{},_=this.loadQueryErrorMessage(y);x.message=_,x.Error={Type:x.Type,Code:x.Code,Message:_};let{errorSchema:A,errorMetadata:P}=await this.mixin.getErrorSchemaOrThrowBaseException(S,this.options.defaultNamespace,g,x,w,this.mixin.findQueryCompatibleError),D=qe.of(A),B=new(this.compositeErrorRegistry.getErrorCtor(A)??Error)({}),z={Type:x.Error.Type,Code:x.Error.Code,Error:x.Error};for(let[k,R]of D.structIterator()){let N=R.getMergedTraits().xmlName??k,q=x[N]??y[N];z[k]=this.deserializer.readSchema(R,q)}throw this.mixin.decorateServiceException(Object.assign(B,P,{$fault:D.getMergedTraits().error,message:_},z),y)}loadQueryErrorCode(f,h){let g=(h.Errors?.[0]?.Error??h.Errors?.Error??h.Error)?.Code;if(g!==void 0)return g;if(f.statusCode==404)return"NotFound"}loadQueryError(f){return f.Errors?.[0]?.Error??f.Errors?.Error??f.Error}loadQueryErrorMessage(f){let h=this.loadQueryError(f);return h?.message??h?.Message??f.message??f.Message??"Unknown"}getDefaultContentType(){return"application/x-www-form-urlencoded"}}class IS extends pd{options;constructor(f){super(f);this.options=f;let h={capitalizeKeys:!0,flattenLists:!0,serializeEmptyLists:!1,ec2:!0};Object.assign(this.serializer.settings,h)}getShapeId(){return"aws.protocols#ec2Query"}useNestedResult(){return!1}}var LL=(f,h)=>dd(f,h).then((g)=>(h?.utf8Encoder??gS)(g)),CS=(f,h)=>LL(f,h).then((g)=>{if(g.length){let y;try{y=mS(g)}catch(_){if(_&&typeof _==="object")Object.defineProperty(_,"$responseBodyText",{value:g});throw _}let w="#text",S=Object.keys(y)[0],x=y[S];if(x[w])x[S]=x[w],delete x[w];return aS(x)}return{}}),zL=async(f,h)=>{let g=await CS(f,h);if(g.Error)g.Error.message=g.Error.message??g.Error.Message;return g},RS=(f,h)=>{if(h?.Error?.Code!==void 0)return h.Error.Code;if(h?.Code!==void 0)return h.Code;if(f.statusCode==404)return"NotFound"};class md extends _s{settings;stringBuffer;byteBuffer;buffer;constructor(f){super();this.settings=f}write(f,h){let g=qe.of(f);if(g.isStringSchema()&&typeof h==="string")this.stringBuffer=h;else if(g.isBlobSchema())this.byteBuffer="byteLength"in h?h:(this.serdeContext?.base64Decoder??FL)(h);else{this.buffer=this.writeStruct(g,h,void 0);let y=g.getMergedTraits();if(y.httpPayload&&!y.xmlName)this.buffer.withName(g.getName())}}flush(){if(this.byteBuffer!==void 0){let h=this.byteBuffer;return delete this.byteBuffer,h}if(this.stringBuffer!==void 0){let h=this.stringBuffer;return delete this.stringBuffer,h}let f=this.buffer;if(this.settings.xmlNamespace){if(!f?.attributes?.xmlns)f.addAttribute("xmlns",this.settings.xmlNamespace)}return delete this.buffer,f.toString()}writeStruct(f,h,g){let y=f.getMergedTraits(),w=f.isMemberSchema()&&!y.httpPayload?f.getMemberTraits().xmlName??f.getMemberName():y.xmlName??f.getName();if(!w||!f.isStructSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${f.getName(!0)}.`);let S=bt.of(w),[x,_]=this.getXmlnsAttribute(f,g);for(let[P,D]of f.structIterator()){let U=h[P];if(U!=null||D.isIdempotencyToken()){if(D.getMergedTraits().xmlAttribute){S.addAttribute(D.getMergedTraits().xmlName??P,this.writeSimple(D,U));continue}if(D.isListSchema())this.writeList(D,U,S,_);else if(D.isMapSchema())this.writeMap(D,U,S,_);else if(D.isStructSchema())S.addChildNode(this.writeStruct(D,U,_));else{let B=bt.of(D.getMergedTraits().xmlName??D.getMemberName());this.writeSimpleInto(D,U,B,_),S.addChildNode(B)}}}let{$unknown:A}=h;if(A&&f.isUnionSchema()&&Array.isArray(A)&&Object.keys(h).length===1){let[P,D]=A,U=bt.of(P);if(typeof D!=="string")if(h instanceof bt||h instanceof oS)S.addChildNode(h);else throw Error("@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.");this.writeSimpleInto(0,D,U,_),S.addChildNode(U)}if(_)S.addAttribute(x,_);return S}writeList(f,h,g,y){if(!f.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${f.getName(!0)}`);let w=f.getMergedTraits(),S=f.getValueSchema(),x=S.getMergedTraits(),_=!!x.sparse,A=!!w.xmlFlattened,[P,D]=this.getXmlnsAttribute(f,y),U=(B,z)=>{if(S.isListSchema())this.writeList(S,Array.isArray(z)?z:[z],B,D);else if(S.isMapSchema())this.writeMap(S,z,B,D);else if(S.isStructSchema()){let k=this.writeStruct(S,z,D);B.addChildNode(k.withName(A?w.xmlName??f.getMemberName():x.xmlName??"member"))}else{let k=bt.of(A?w.xmlName??f.getMemberName():x.xmlName??"member");this.writeSimpleInto(S,z,k,D),B.addChildNode(k)}};if(A){for(let B of h)if(_||B!=null)U(g,B)}else{let B=bt.of(w.xmlName??f.getMemberName());if(D)B.addAttribute(P,D);for(let z of h)if(_||z!=null)U(B,z);g.addChildNode(B)}}writeMap(f,h,g,y,w=!1){if(!f.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${f.getName(!0)}`);let S=f.getMergedTraits(),x=f.getKeySchema(),A=x.getMergedTraits().xmlName??"key",P=f.getValueSchema(),D=P.getMergedTraits(),U=D.xmlName??"value",B=!!D.sparse,z=!!S.xmlFlattened,[k,R]=this.getXmlnsAttribute(f,y),N=(q,V,W)=>{let G=bt.of(A,V),[K,J]=this.getXmlnsAttribute(x,R);if(J)G.addAttribute(K,J);q.addChildNode(G);let re=bt.of(U);if(P.isListSchema())this.writeList(P,W,re,R);else if(P.isMapSchema())this.writeMap(P,W,re,R,!0);else if(P.isStructSchema())re=this.writeStruct(P,W,R);else this.writeSimpleInto(P,W,re,R);q.addChildNode(re)};if(z)for(let q in h){let V=h[q];if(B||V!=null){let W=bt.of(S.xmlName??f.getMemberName());N(W,q,V),g.addChildNode(W)}}else{let q;if(!w){if(q=bt.of(S.xmlName??f.getMemberName()),R)q.addAttribute(k,R);g.addChildNode(q)}for(let V in h){let W=h[V];if(B||W!=null){let G=bt.of("entry");N(G,V,W),(w?g:q).addChildNode(G)}}}}writeSimple(f,h){if(h===null)throw Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let g=qe.of(f),y=null;if(h&&typeof h==="object")if(g.isBlobSchema())y=(this.serdeContext?.base64Encoder??yS)(h);else if(g.isTimestampSchema()&&h instanceof Date)switch(pS(g,this.settings)){case 5:y=h.toISOString().replace(".000Z","Z");break;case 6:y=ld(h);break;case 7:y=String(h.getTime()/1000);break;default:console.warn("Missing timestamp format, using http date",h),y=ld(h);break}else if(g.isBigDecimalSchema()&&h){if(h instanceof wS)return h.string;return String(h)}else if(g.isMapSchema()||g.isListSchema())throw Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead.");else throw Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${g.getName(!0)}`);if(g.isBooleanSchema()||g.isNumericSchema()||g.isBigIntegerSchema()||g.isBigDecimalSchema())y=String(h);if(g.isStringSchema())if(h===void 0&&g.isIdempotencyToken())y=SS();else y=String(h);if(y===null)throw Error(`Unhandled schema-value pair ${g.getName(!0)}=${h}`);return y}writeSimpleInto(f,h,g,y){let w=this.writeSimple(f,h),S=qe.of(f),x=new oS(w),[_,A]=this.getXmlnsAttribute(S,y);if(A)g.addAttribute(_,A);g.addChildNode(x)}getXmlnsAttribute(f,h){let g=f.getMergedTraits(),[y,w]=g.xmlNamespace??[];if(w&&w!==h)return[y?`xmlns:${y}`:"xmlns",w];return[void 0,void 0]}}class gd extends _s{settings;constructor(f){super();this.settings=f}createSerializer(){let f=new md(this.settings);return f.setSerdeContext(this.serdeContext),f}createDeserializer(){let f=new fi(this.settings);return f.setSerdeContext(this.serdeContext),f}}class vS extends dS{codec;serializer;deserializer;mixin=new Or;constructor(f){super(f);let h={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:f.xmlNamespace,serviceNamespace:f.defaultNamespace};this.codec=new gd(h),this.serializer=new lS(this.codec.createSerializer(),h),this.deserializer=new fS(this.codec.createDeserializer(),h)}getPayloadCodec(){return this.codec}getShapeId(){return"aws.protocols#restXml"}async serializeRequest(f,h,g){let y=await super.serializeRequest(f,h,g),w=qe.of(f.input);if(!y.headers["content-type"]){let S=this.mixin.resolveRestContentType(this.getDefaultContentType(),w);if(S)y.headers["content-type"]=S}if(typeof y.body==="string"&&y.headers["content-type"]===this.getDefaultContentType()&&!y.body.startsWith("<?xml ")&&!this.hasUnstructuredPayloadBinding(w))y.body='<?xml version="1.0" encoding="UTF-8"?>'+y.body;return y}async deserializeResponse(f,h,g){return super.deserializeResponse(f,h,g)}async handleError(f,h,g,y,w){let S=RS(g,y)??"Unknown";if(this.mixin.compose(this.compositeErrorRegistry,S,this.options.defaultNamespace),y.Error&&typeof y.Error==="object"){for(let k of Object.keys(y.Error))if(y[k]=y.Error[k],k.toLowerCase()==="message")y.message=y.Error[k]}if(y.RequestId&&!w.requestId)w.requestId=y.RequestId;let{errorSchema:x,errorMetadata:_}=await this.mixin.getErrorSchemaOrThrowBaseException(S,this.options.defaultNamespace,g,y,w),A=qe.of(x),P=y.Error?.message??y.Error?.Message??y.message??y.Message??"UnknownError",U=new(this.compositeErrorRegistry.getErrorCtor(x)??Error)({});await this.deserializeHttpMessage(x,h,g,y);let B={},z=this.codec.createDeserializer();for(let[k,R]of A.structIterator()){let N=R.getMergedTraits().xmlName??k,q=y.Error?.[N]??y[N];B[k]=z.readSchema(R,q)}throw this.mixin.decorateServiceException(Object.assign(U,_,{$fault:A.getMergedTraits().error,message:P},B),y)}getDefaultContentType(){return"application/xml"}hasUnstructuredPayloadBinding(f){for(let[,h]of f.structIterator())if(h.getMergedTraits().httpPayload)return!(h.isStructSchema()||h.isMapSchema()||h.isListSchema());return!1}}var HL=(f)=>{if(f==null)return;if(typeof f==="object"&&"__type"in f)delete f.__type;return $L(f)},qL=(f)=>{if(f==null)return f;if(typeof f==="number"||typeof f==="bigint"){let h=Error(`Received number ${f} where a string was expected.`);return h.name="Warning",console.warn(h),String(f)}if(typeof f==="boolean"){let h=Error(`Received boolean ${f} where a string was expected.`);return h.name="Warning",console.warn(h),String(f)}return f},jL=(f)=>{if(f==null)return f;if(typeof f==="string"){let h=f.toLowerCase();if(f!==""&&h!=="false"&&h!=="true"){let g=Error(`Received string "${f}" where a boolean was expected.`);g.name="Warning",console.warn(g)}return f!==""&&h!=="false"}return f},VL=(f)=>{if(f==null)return f;if(typeof f==="string"){let h=Number(f);if(h.toString()!==f){let g=Error(`Received string "${f}" where a number was expected.`);return g.name="Warning",console.warn(g),f}return h}return f};WL.AwsEc2QueryProtocol=IS;WL.AwsJson1_0Protocol=bS;WL.AwsJson1_1Protocol=xS;WL.AwsJsonRpcProtocol=li;WL.AwsQueryProtocol=pd;WL.AwsRestJsonProtocol=_S;WL.AwsRestXmlProtocol=vS;WL.AwsSmithyRpcV2CborProtocol=ES;WL.AwsSmithyRpcV2JsonProtocol=TS;WL.QueryShapeSerializer=hd;WL.XmlCodec=gd;WL.XmlShapeDeserializer=fi;WL.XmlShapeSerializer=md;WL._toBool=jL;WL._toNum=VL;WL._toStr=qL;WL.awsExpectUnion=HL;WL.loadRestXmlErrorCode=RS;WL.parseXmlBody=CS;WL.parseXmlErrorBody=zL});var xd=i(function(Fz){var{awsEndpointFunctions:_2,emitWarningIfUnsupportedVersion:T2,createDefaultUserAgentProvider:A2,NODE_APP_ID_CONFIG_OPTIONS:I2,getAwsRegionExtensionConfiguration:C2,resolveAwsRegionExtensionConfiguration:R2,resolveUserAgentConfig:v2,resolveHostHeaderConfig:k2,getUserAgentPlugin:N2,getHostHeaderPlugin:O2,getLoggerPlugin:P2,getRecursionDetectionPlugin:M2}=nt(),{NoAuthSigner:D2,getHttpAuthSchemeEndpointRuleSetPlugin:U2,DefaultIdentityProviderConfig:F2,getHttpSigningPlugin:$2}=rr(),{normalizeProvider:MS,getSmithyContext:B2,ServiceException:L2,NoOpLogger:z2,emitWarningIfUnsupportedVersion:H2,loadConfigsForDefaultMode:q2,getDefaultExtensionConfiguration:j2,resolveDefaultRuntimeConfig:V2,Client:DS,makeBuilder:W2,createAggregatedClient:G2}=ct(),{Command:K2}=ct();Fz.$Command=K2;Fz.__Client=DS;var{resolveDefaultsModeConfig:J2,loadConfig:Pr,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:Q2,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:X2,NODE_REGION_CONFIG_OPTIONS:Y2,NODE_REGION_CONFIG_FILE_OPTIONS:Z2,resolveRegionConfig:e4}=Ce(),{BinaryDecisionDiagram:t4,EndpointCache:r4,decideEndpoint:n4,customEndpointFunctions:s4,resolveEndpointConfig:o4,getEndpointPlugin:i4}=Yt(),{parseUrl:a4,getHttpHandlerExtensionConfiguration:c4,resolveHttpHandlerRuntimeConfig:u4,getContentLengthPlugin:d4}=Ne(),{DEFAULT_RETRY_MODE:l4,NODE_RETRY_MODE_CONFIG_OPTIONS:f4,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:h4,resolveRetryConfig:p4,getRetryPlugin:m4}=fn(),{TypeRegistry:US,getSchemaSerdePlugin:g4}=Rt(),{resolveAwsSdkSigV4Config:y4,AwsSdkSigV4Signer:S4,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:w4}=yn(),{toUtf8:E4,fromUtf8:b4,toBase64:x4,fromBase64:_4,calculateBodyLength:T4}=Ke(),{streamCollector:A4,NodeHttpHandler:I4}=pn(),{AwsRestJsonProtocol:C4}=Ts(),{Sha256:R4}=tn(),v4=async(f,h,g)=>({operation:B2(h).operation,region:await MS(f.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function k4(f){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:f.region},propertiesExtractor:(h,g)=>({signingProperties:{config:h,context:g}})}}function N4(f){return{schemeId:"smithy.api#noAuth"}}var O4=(f)=>{let h=[];switch(f.operation){case"CreateToken":{h.push(N4());break}default:h.push(k4(f))}return h},P4=(f)=>{let h=y4(f);return Object.assign(h,{authSchemePreference:MS(f.authSchemePreference??[])})},M4=(f)=>Object.assign(f,{useDualstackEndpoint:f.useDualstackEndpoint??!1,useFipsEndpoint:f.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"}),D4={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},U4="3.997.52",F4={version:U4},As="ref",Mr=-1,hi=!0,kS="isSet",FS="PartitionResult",pi="booleanEquals",yd="getAttr",NS={[As]:"Endpoint"},Sd={[As]:FS},An={},OS=[{[As]:"Region"}],PS={conditions:[[kS,[NS]],[kS,OS],["aws.partition",OS,FS],[pi,[{[As]:"UseFIPS"},hi]],[pi,[{[As]:"UseDualStack"},hi]],[pi,[{fn:yd,argv:[Sd,"supportsDualStack"]},hi]],[pi,[{fn:yd,argv:[Sd,"supportsFIPS"]},hi]],["stringEquals",[{fn:yd,argv:[Sd,"name"]},"aws-us-gov"]]],results:[[Mr],[Mr,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Mr,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[NS,An],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",An],[Mr,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",An],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",An],[Mr,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",An],[Mr,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",An],[Mr,"Invalid Configuration: Missing Region"]]},$4=2,st=1e8,B4=new Int32Array([-1,1,-1,0,13,3,1,4,st+12,2,5,st+12,3,8,6,4,7,st+11,5,st+9,st+10,4,11,9,6,10,st+8,7,st+6,st+7,5,12,st+5,6,st+4,st+5,3,st+1,14,4,st+2,st+3]),L4=t4.from(B4,$4,PS.conditions,PS.results),z4=new r4({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),H4=(f,h={})=>z4.get(f,()=>n4(L4,{endpointParams:f,logger:h.logger}));s4.aws=_2;class et extends L2{static shapeId="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc#SSOOIDCServiceException";constructor(f){super(f);Object.setPrototypeOf(this,et.prototype)}}class mi extends et{static shapeId="com.amazonaws.ssooidc#AccessDeniedException";name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(f){super({name:"AccessDeniedException",$fault:"client",...f});Object.setPrototypeOf(this,mi.prototype),this.error=f.error,this.reason=f.reason,this.error_description=f.error_description}}class gi extends et{static shapeId="com.amazonaws.ssooidc#AuthorizationPendingException";name="AuthorizationPendingException";$fault="client";error;error_description;constructor(f){super({name:"AuthorizationPendingException",$fault:"client",...f});Object.setPrototypeOf(this,gi.prototype),this.error=f.error,this.error_description=f.error_description}}class Si extends et{static shapeId="com.amazonaws.ssooidc#ExpiredTokenException";name="ExpiredTokenException";$fault="client";error;error_description;constructor(f){super({name:"ExpiredTokenException",$fault:"client",...f});Object.setPrototypeOf(this,Si.prototype),this.error=f.error,this.error_description=f.error_description}}class wi extends et{static shapeId="com.amazonaws.ssooidc#InternalServerException";name="InternalServerException";$fault="server";error;error_description;constructor(f){super({name:"InternalServerException",$fault:"server",...f});Object.setPrototypeOf(this,wi.prototype),this.error=f.error,this.error_description=f.error_description}}class Ei extends et{static shapeId="com.amazonaws.ssooidc#InvalidClientException";name="InvalidClientException";$fault="client";error;error_description;constructor(f){super({name:"InvalidClientException",$fault:"client",...f});Object.setPrototypeOf(this,Ei.prototype),this.error=f.error,this.error_description=f.error_description}}class bi extends et{static shapeId="com.amazonaws.ssooidc#InvalidGrantException";name="InvalidGrantException";$fault="client";error;error_description;constructor(f){super({name:"InvalidGrantException",$fault:"client",...f});Object.setPrototypeOf(this,bi.prototype),this.error=f.error,this.error_description=f.error_description}}class xi extends et{static shapeId="com.amazonaws.ssooidc#InvalidRequestException";name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(f){super({name:"InvalidRequestException",$fault:"client",...f});Object.setPrototypeOf(this,xi.prototype),this.error=f.error,this.reason=f.reason,this.error_description=f.error_description}}class _i extends et{static shapeId="com.amazonaws.ssooidc#InvalidScopeException";name="InvalidScopeException";$fault="client";error;error_description;constructor(f){super({name:"InvalidScopeException",$fault:"client",...f});Object.setPrototypeOf(this,_i.prototype),this.error=f.error,this.error_description=f.error_description}}class Ti extends et{static shapeId="com.amazonaws.ssooidc#SlowDownException";name="SlowDownException";$fault="client";error;error_description;constructor(f){super({name:"SlowDownException",$fault:"client",...f});Object.setPrototypeOf(this,Ti.prototype),this.error=f.error,this.error_description=f.error_description}}class Ai extends et{static shapeId="com.amazonaws.ssooidc#UnauthorizedClientException";name="UnauthorizedClientException";$fault="client";error;error_description;constructor(f){super({name:"UnauthorizedClientException",$fault:"client",...f});Object.setPrototypeOf(this,Ai.prototype),this.error=f.error,this.error_description=f.error_description}}class Ii extends et{static shapeId="com.amazonaws.ssooidc#UnsupportedGrantTypeException";name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(f){super({name:"UnsupportedGrantTypeException",$fault:"client",...f});Object.setPrototypeOf(this,Ii.prototype),this.error=f.error,this.error_description=f.error_description}}var q4="AccessDeniedException",j4="AuthorizationPendingException",V4="AccessToken",W4="ClientSecret",G4="CreateToken",K4="CreateTokenRequest",J4="CreateTokenResponse",Q4="CodeVerifier",X4="ExpiredTokenException",Y4="InvalidClientException",Z4="InvalidGrantException",ez="InvalidRequestException",tz="InternalServerException",rz="InvalidScopeException",nz="IdToken",sz="RefreshToken",oz="SlowDownException",iz="UnauthorizedClientException",az="UnsupportedGrantTypeException",cz="accessToken",Ut="client",uz="clientId",dz="clientSecret",lz="codeVerifier",fz="code",hz="deviceCode",_e="error",pz="expiresIn",xt="error_description",mz="grantType",gz="http",_t="httpError",yz="idToken",$S="reason",BS="refreshToken",Sz="redirectUri",LS="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",wz="scope",Ez="server",bz="tokenType",Re="com.amazonaws.ssooidc",zS=new US(LS),HS=[-3,LS,"SSOOIDCServiceException",0,[],[]];zS.registerError(HS,et);var gt=new US(Re),qS=[-3,Re,q4,{[_e]:Ut,[_t]:400},[_e,$S,xt],[0,0,0]];gt.registerError(qS,mi);var jS=[-3,Re,j4,{[_e]:Ut,[_t]:400},[_e,xt],[0,0]];gt.registerError(jS,gi);var VS=[-3,Re,X4,{[_e]:Ut,[_t]:400},[_e,xt],[0,0]];gt.registerError(VS,Si);var WS=[-3,Re,tz,{[_e]:Ez,[_t]:500},[_e,xt],[0,0]];gt.registerError(WS,wi);var GS=[-3,Re,Y4,{[_e]:Ut,[_t]:401},[_e,xt],[0,0]];gt.registerError(GS,Ei);var KS=[-3,Re,Z4,{[_e]:Ut,[_t]:400},[_e,xt],[0,0]];gt.registerError(KS,bi);var JS=[-3,Re,ez,{[_e]:Ut,[_t]:400},[_e,$S,xt],[0,0,0]];gt.registerError(JS,xi);var QS=[-3,Re,rz,{[_e]:Ut,[_t]:400},[_e,xt],[0,0]];gt.registerError(QS,_i);var XS=[-3,Re,oz,{[_e]:Ut,[_t]:400},[_e,xt],[0,0]];gt.registerError(XS,Ti);var YS=[-3,Re,iz,{[_e]:Ut,[_t]:400},[_e,xt],[0,0]];gt.registerError(YS,Ai);var ZS=[-3,Re,az,{[_e]:Ut,[_t]:400},[_e,xt],[0,0]];gt.registerError(ZS,Ii);var ew=[zS,gt],xz=[0,Re,V4,8,0],_z=[0,Re,W4,8,0],Tz=[0,Re,Q4,8,0],Az=[0,Re,nz,8,0],tw=[0,Re,sz,8,0],rw=[3,Re,K4,0,[uz,dz,mz,hz,fz,BS,wz,Sz,lz],[0,[()=>_z,0],0,0,0,[()=>tw,0],64,0,[()=>Tz,0]],3],nw=[3,Re,J4,0,[cz,bz,pz,BS,yz],[[()=>xz,0],0,1,[()=>tw,0],[()=>Az,0]]],sw=[9,Re,G4,{[gz]:["POST","/token",200]},()=>rw,()=>nw],Iz=(f)=>({apiVersion:"2019-06-10",base64Decoder:f?.base64Decoder??_4,base64Encoder:f?.base64Encoder??x4,disableHostPrefix:f?.disableHostPrefix??!1,endpointProvider:f?.endpointProvider??H4,extensions:f?.extensions??[],httpAuthSchemeProvider:f?.httpAuthSchemeProvider??O4,httpAuthSchemes:f?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(h)=>h.getIdentityProvider("aws.auth#sigv4"),signer:new S4},{schemeId:"smithy.api#noAuth",identityProvider:(h)=>h.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new D2}],logger:f?.logger??new z2,protocol:f?.protocol??C4,protocolSettings:f?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:ew,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:f?.serviceId??"SSO OIDC",sha256:f?.sha256??R4,urlParser:f?.urlParser??a4,utf8Decoder:f?.utf8Decoder??b4,utf8Encoder:f?.utf8Encoder??E4}),Cz=(f)=>{H2(process.version);let h=J2(f),g=()=>h().then(q2),y=Iz(f);T2(process.version);let w={profile:f?.profile,logger:y.logger};return{...y,...f,runtime:"node",defaultsMode:h,authSchemePreference:f?.authSchemePreference??Pr(w4,w),bodyLengthChecker:f?.bodyLengthChecker??T4,defaultUserAgentProvider:f?.defaultUserAgentProvider??A2({serviceId:y.serviceId,clientVersion:F4.version}),maxAttempts:f?.maxAttempts??Pr(h4,f),region:f?.region??Pr(Y2,{...Z2,...w}),requestHandler:I4.create(f?.requestHandler??g),retryMode:f?.retryMode??Pr({...f4,default:async()=>(await g()).retryMode||l4},f),streamCollector:f?.streamCollector??A4,useDualstackEndpoint:f?.useDualstackEndpoint??Pr(X2,w),useFipsEndpoint:f?.useFipsEndpoint??Pr(Q2,w),userAgentAppId:f?.userAgentAppId??Pr(I2,w)}},Rz=(f)=>{let{httpAuthSchemes:h,httpAuthSchemeProvider:g,credentials:y}=f;return{setHttpAuthScheme(w){let S=h.findIndex((x)=>x.schemeId===w.schemeId);if(S===-1)h.push(w);else h.splice(S,1,w)},httpAuthSchemes(){return h},setHttpAuthSchemeProvider(w){g=w},httpAuthSchemeProvider(){return g},setCredentials(w){y=w},credentials(){return y}}},vz=(f)=>({httpAuthSchemes:f.httpAuthSchemes(),httpAuthSchemeProvider:f.httpAuthSchemeProvider(),credentials:f.credentials()}),kz=(f,h)=>{let g=Object.assign(C2(f),j2(f),c4(f),Rz(f));return h.forEach((y)=>y.configure(g)),Object.assign(f,R2(g),V2(g),u4(g),vz(g))};class wd extends DS{config;constructor(...[f]){let h=Cz(f||{});super(h);this.initConfig=h;let g=M4(h),y=v2(g),w=p4(y),S=e4(w),x=k2(S),_=o4(x),A=P4(_),P=kz(A,f?.extensions||[]);this.config=P,this.middlewareStack.use(g4(this.config)),this.middlewareStack.use(N2(this.config)),this.middlewareStack.use(m4(this.config)),this.middlewareStack.use(d4(this.config)),this.middlewareStack.use(O2(this.config)),this.middlewareStack.use(P2(this.config)),this.middlewareStack.use(M2(this.config)),this.middlewareStack.use(U2(this.config,{httpAuthSchemeParametersProvider:v4,identityProviderConfigProvider:async(D)=>new F2({"aws.auth#sigv4":D.credentials})})),this.middlewareStack.use($2(this.config))}destroy(){super.destroy()}}var Nz=W2(D4,"AWSSSOOIDCService","SSOOIDCClient",i4),Oz={},Pz=(f,h,g,y)=>[];class Ed extends Nz(Oz,Pz,"CreateToken",sw){}var Mz={CreateTokenCommand:Ed};class bd extends wd{}G2(Mz,bd);var Dz={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},Uz={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};Fz.AccessDeniedException=mi;Fz.AccessDeniedException$=qS;Fz.AccessDeniedExceptionReason=Dz;Fz.AuthorizationPendingException=gi;Fz.AuthorizationPendingException$=jS;Fz.CreateToken$=sw;Fz.CreateTokenCommand=Ed;Fz.CreateTokenRequest$=rw;Fz.CreateTokenResponse$=nw;Fz.ExpiredTokenException=Si;Fz.ExpiredTokenException$=VS;Fz.InternalServerException=wi;Fz.InternalServerException$=WS;Fz.InvalidClientException=Ei;Fz.InvalidClientException$=GS;Fz.InvalidGrantException=bi;Fz.InvalidGrantException$=KS;Fz.InvalidRequestException=xi;Fz.InvalidRequestException$=JS;Fz.InvalidRequestExceptionReason=Uz;Fz.InvalidScopeException=_i;Fz.InvalidScopeException$=QS;Fz.SSOOIDC=bd;Fz.SSOOIDCClient=wd;Fz.SSOOIDCServiceException=et;Fz.SSOOIDCServiceException$=HS;Fz.SlowDownException=Ti;Fz.SlowDownException$=XS;Fz.UnauthorizedClientException=Ai;Fz.UnauthorizedClientException$=YS;Fz.UnsupportedGrantTypeException=Ii;Fz.UnsupportedGrantTypeException$=ZS;Fz.errorTypeRegistries=ew});var cw=i(function(UH){var{setTokenFeature:wH}=nt(),{getBearerTokenEnvKey:EH}=yn(),{TokenProviderError:Tt,getSSOTokenFilepath:bH,parseKnownFiles:xH,getProfileName:_H,loadSsoSessionData:TH,getSSOTokenFromFile:AH,memoize:IH,chain:CH}=Ce(),{promises:RH}=c("node:fs"),vH=({logger:f,signingName:h}={})=>async()=>{if(f?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"),!h)throw new Tt("Please pass 'signingName' to compute environment variable key",{logger:f});let g=EH(h);if(!(g in process.env))throw new Tt(`Token not present in '${g}' environment variable`,{logger:f});let y={token:process.env[g]};return wH(y,"BEARER_SERVICE_ENV_VARS","3"),y},kH=async(f,h={},g)=>{let{SSOOIDCClient:y}=xd(),w=(x)=>h.clientConfig?.[x]??h.parentClientConfig?.[x]??g?.[x];return new y(Object.assign({},h.clientConfig??{},{region:f??h.clientConfig?.region,logger:w("logger"),userAgentAppId:w("userAgentAppId")}))},NH=async(f,h,g={},y)=>{let{CreateTokenCommand:w}=xd();return(await kH(h,g,y)).send(new w({clientId:f.clientId,clientSecret:f.clientSecret,refreshToken:f.refreshToken,grantType:"refresh_token"}))},ow=(f)=>{if(f.expiration&&f.expiration.getTime()<Date.now())throw new Tt("Token is expired. To refresh this SSO session run 'aws sso login' with the corresponding profile.",!1)},Dr=(f,h,g=!1)=>{if(typeof h>"u")throw new Tt(`Value not present for '${f}' in SSO Token${g?". Cannot refresh":""}. To refresh this SSO session run 'aws sso login' with the corresponding profile.`,!1)},{writeFile:OH}=RH,PH=(f,h)=>{let g=bH(f),y=JSON.stringify(h,null,2);return OH(g,y)},iw=new Map,Ci=new Map,aw=(f={})=>async({callerClientConfig:h}={})=>{f.logger?.debug("@aws-sdk/token-providers - fromSso");let g=await xH(f),y=_H({profile:f.profile??h?.profile}),w=g[y];if(!w)throw new Tt(`Profile '${y}' could not be found in shared credentials file.`,!1);else if(!w.sso_session)throw new Tt(`Profile '${y}' is missing required property 'sso_session'.`);let S=w.sso_session,x=Ci.get(S);if(x)return await x;let A=(await TH(f))[S];if(!A)throw new Tt(`Sso session '${S}' could not be found in shared credentials file.`,!1);for(let q of["sso_start_url","sso_region"])if(!A[q])throw new Tt(`Sso session '${S}' is missing required property '${q}'.`,!1);A.sso_start_url;let P=A.sso_region,D;try{D=await AH(S)}catch(q){throw new Tt(`The SSO session token associated with profile=${y} was not found or is invalid. To refresh this SSO session run 'aws sso login' with the corresponding profile.`,!1)}Dr("accessToken",D.accessToken),Dr("expiresAt",D.expiresAt);let{accessToken:U,expiresAt:B}=D,z={token:U,expiration:new Date(B)};if(z.expiration.getTime()-Date.now()>300000)return z;let k=Ci.get(S);if(k)return await k;let R=iw.get(S)??0;if(Date.now()-R<30000)return ow(z),z;Dr("clientId",D.clientId,!0),Dr("clientSecret",D.clientSecret,!0),Dr("refreshToken",D.refreshToken,!0);let N=(async()=>{try{iw.set(S,Date.now());let q=await NH(D,P,f,h);Dr("accessToken",q.accessToken),Dr("expiresIn",q.expiresIn);let V=new Date(Date.now()+q.expiresIn*1000);try{await PH(S,{...D,accessToken:q.accessToken,expiresAt:V.toISOString(),refreshToken:q.refreshToken})}catch(W){}return{token:q.accessToken,expiration:V}}catch(q){return ow(z),z}})();Ci.set(S,N);try{return await N}finally{Ci.delete(S)}},MH=({token:f,logger:h})=>async()=>{if(h?.debug("@aws-sdk/token-providers - fromStatic"),!f||!f.token)throw new Tt("Please pass a valid token to fromStatic",!1);return f},DH=(f={})=>IH(CH(aw(f),async()=>{throw new Tt("Could not load token from any providers",!1)}),(h)=>h.expiration!==void 0&&h.expiration.getTime()-Date.now()<300000,(h)=>h.expiration!==void 0);UH.fromEnvSigningName=vH;UH.fromSso=aw;UH.fromStatic=MH;UH.nodeProvider=DH});var kw=i(function(qj){var{awsEndpointFunctions:zH,emitWarningIfUnsupportedVersion:HH,createDefaultUserAgentProvider:qH,NODE_APP_ID_CONFIG_OPTIONS:jH,getAwsRegionExtensionConfiguration:VH,resolveAwsRegionExtensionConfiguration:WH,resolveUserAgentConfig:GH,resolveHostHeaderConfig:KH,getUserAgentPlugin:JH,getHostHeaderPlugin:QH,getLoggerPlugin:XH,getRecursionDetectionPlugin:YH}=nt(),{NoAuthSigner:ZH,getHttpAuthSchemeEndpointRuleSetPlugin:eq,DefaultIdentityProviderConfig:tq,getHttpSigningPlugin:rq}=rr(),{normalizeProvider:pw,getSmithyContext:nq,ServiceException:sq,NoOpLogger:oq,emitWarningIfUnsupportedVersion:iq,loadConfigsForDefaultMode:aq,getDefaultExtensionConfiguration:cq,resolveDefaultRuntimeConfig:uq,Client:mw,makeBuilder:dq,createAggregatedClient:lq}=ct(),{Command:fq}=ct();qj.$Command=fq;qj.__Client=mw;var{resolveDefaultsModeConfig:hq,loadConfig:Fr,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:pq,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:mq,NODE_REGION_CONFIG_OPTIONS:gq,NODE_REGION_CONFIG_FILE_OPTIONS:yq,resolveRegionConfig:Sq}=Ce(),{BinaryDecisionDiagram:wq,EndpointCache:Eq,decideEndpoint:bq,customEndpointFunctions:xq,resolveEndpointConfig:_q,getEndpointPlugin:Tq}=Yt(),{parseUrl:Aq,getHttpHandlerExtensionConfiguration:Iq,resolveHttpHandlerRuntimeConfig:Cq,getContentLengthPlugin:Rq}=Ne(),{DEFAULT_RETRY_MODE:vq,NODE_RETRY_MODE_CONFIG_OPTIONS:kq,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:Nq,resolveRetryConfig:Oq,getRetryPlugin:Pq}=fn(),{TypeRegistry:gw,getSchemaSerdePlugin:Mq}=Rt(),{resolveAwsSdkSigV4Config:Dq,AwsSdkSigV4Signer:Uq,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:Fq}=yn(),{toUtf8:$q,fromUtf8:Bq,toBase64:Lq,fromBase64:zq,calculateBodyLength:Hq}=Ke(),{streamCollector:qq,NodeHttpHandler:jq}=pn(),{AwsRestJsonProtocol:Vq}=Ts(),{Sha256:Wq}=tn(),Gq=async(f,h,g)=>({operation:nq(h).operation,region:await pw(f.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function Kq(f){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"awsssoportal",region:f.region},propertiesExtractor:(h,g)=>({signingProperties:{config:h,context:g}})}}function Jq(f){return{schemeId:"smithy.api#noAuth"}}var Qq=(f)=>{let h=[];switch(f.operation){case"GetRoleCredentials":{h.push(Jq());break}default:h.push(Kq(f))}return h},Xq=(f)=>{let h=Dq(f);return Object.assign(h,{authSchemePreference:pw(f.authSchemePreference??[])})},Yq=(f)=>Object.assign(f,{useDualstackEndpoint:f.useDualstackEndpoint??!1,useFipsEndpoint:f.useFipsEndpoint??!1,defaultSigningName:"awsssoportal"}),Zq={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},ej="3.997.52",tj={version:ej},Is="ref",$r=-1,Ri=!0,uw="isSet",yw="PartitionResult",vi="booleanEquals",_d="getAttr",dw={[Is]:"Endpoint"},Td={[Is]:yw},In={},lw=[{[Is]:"Region"}],fw={conditions:[[uw,[dw]],[uw,lw],["aws.partition",lw,yw],[vi,[{[Is]:"UseFIPS"},Ri]],[vi,[{[Is]:"UseDualStack"},Ri]],[vi,[{fn:_d,argv:[Td,"supportsDualStack"]},Ri]],[vi,[{fn:_d,argv:[Td,"supportsFIPS"]},Ri]],["stringEquals",[{fn:_d,argv:[Td,"name"]},"aws-us-gov"]]],results:[[$r],[$r,"Invalid Configuration: FIPS and custom endpoint are not supported"],[$r,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[dw,In],["https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",In],[$r,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://portal.sso.{Region}.amazonaws.com",In],["https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}",In],[$r,"FIPS is enabled but this partition does not support FIPS"],["https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}",In],[$r,"DualStack is enabled but this partition does not support DualStack"],["https://portal.sso.{Region}.{PartitionResult#dnsSuffix}",In],[$r,"Invalid Configuration: Missing Region"]]},rj=2,ot=1e8,nj=new Int32Array([-1,1,-1,0,13,3,1,4,ot+12,2,5,ot+12,3,8,6,4,7,ot+11,5,ot+9,ot+10,4,11,9,6,10,ot+8,7,ot+6,ot+7,5,12,ot+5,6,ot+4,ot+5,3,ot+1,14,4,ot+2,ot+3]),sj=wq.from(nj,rj,fw.conditions,fw.results),oj=new Eq({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),ij=(f,h={})=>oj.get(f,()=>bq(sj,{endpointParams:f,logger:h.logger}));xq.aws=zH;class ar extends sq{static shapeId="smithy.ts.sdk.synthetic.com.amazonaws.sso#SSOServiceException";constructor(f){super(f);Object.setPrototypeOf(this,ar.prototype)}}class ki extends ar{static shapeId="com.amazonaws.sso#InvalidRequestException";name="InvalidRequestException";$fault="client";constructor(f){super({name:"InvalidRequestException",$fault:"client",...f});Object.setPrototypeOf(this,ki.prototype)}}class Ni extends ar{static shapeId="com.amazonaws.sso#ResourceNotFoundException";name="ResourceNotFoundException";$fault="client";constructor(f){super({name:"ResourceNotFoundException",$fault:"client",...f});Object.setPrototypeOf(this,Ni.prototype)}}class Mi extends ar{static shapeId="com.amazonaws.sso#TooManyRequestsException";name="TooManyRequestsException";$fault="client";constructor(f){super({name:"TooManyRequestsException",$fault:"client",...f});Object.setPrototypeOf(this,Mi.prototype)}}class Ui extends ar{static shapeId="com.amazonaws.sso#UnauthorizedException";name="UnauthorizedException";$fault="client";constructor(f){super({name:"UnauthorizedException",$fault:"client",...f});Object.setPrototypeOf(this,Ui.prototype)}}var aj="AccessTokenType",cj="GetRoleCredentials",uj="GetRoleCredentialsRequest",dj="GetRoleCredentialsResponse",lj="InvalidRequestException",fj="RoleCredentials",hj="ResourceNotFoundException",pj="SecretAccessKeyType",mj="SessionTokenType",gj="TooManyRequestsException",yj="UnauthorizedException",Sj="accountId",wj="accessKeyId",Ej="accessToken",bj="account_id",Fi="client",$i="error",xj="expiration",_j="http",Bi="httpError",Tj="httpHeader",hw="httpQuery",Li="message",Aj="roleCredentials",Ij="roleName",Cj="role_name",Sw="smithy.ts.sdk.synthetic.com.amazonaws.sso",Rj="secretAccessKey",vj="sessionToken",kj="x-amz-sso_bearer_token",St="com.amazonaws.sso",ww=new gw(Sw),Ew=[-3,Sw,"SSOServiceException",0,[],[]];ww.registerError(Ew,ar);var Cs=new gw(St),bw=[-3,St,lj,{[$i]:Fi,[Bi]:400},[Li],[0]];Cs.registerError(bw,ki);var xw=[-3,St,hj,{[$i]:Fi,[Bi]:404},[Li],[0]];Cs.registerError(xw,Ni);var _w=[-3,St,gj,{[$i]:Fi,[Bi]:429},[Li],[0]];Cs.registerError(_w,Mi);var Tw=[-3,St,yj,{[$i]:Fi,[Bi]:401},[Li],[0]];Cs.registerError(Tw,Ui);var Aw=[ww,Cs],Nj=[0,St,aj,8,0],Oj=[0,St,pj,8,0],Pj=[0,St,mj,8,0],Iw=[3,St,uj,0,[Ij,Sj,Ej],[[0,{[hw]:Cj}],[0,{[hw]:bj}],[()=>Nj,{[Tj]:kj}]],3],Cw=[3,St,dj,0,[Aj],[[()=>Rw,0]]],Rw=[3,St,fj,0,[wj,Rj,vj,xj],[0,[()=>Oj,0],[()=>Pj,0],1]],vw=[9,St,cj,{[_j]:["GET","/federation/credentials",200]},()=>Iw,()=>Cw],Mj=(f)=>({apiVersion:"2019-06-10",base64Decoder:f?.base64Decoder??zq,base64Encoder:f?.base64Encoder??Lq,disableHostPrefix:f?.disableHostPrefix??!1,endpointProvider:f?.endpointProvider??ij,extensions:f?.extensions??[],httpAuthSchemeProvider:f?.httpAuthSchemeProvider??Qq,httpAuthSchemes:f?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(h)=>h.getIdentityProvider("aws.auth#sigv4"),signer:new Uq},{schemeId:"smithy.api#noAuth",identityProvider:(h)=>h.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new ZH}],logger:f?.logger??new oq,protocol:f?.protocol??Vq,protocolSettings:f?.protocolSettings??{defaultNamespace:"com.amazonaws.sso",errorTypeRegistries:Aw,version:"2019-06-10",serviceTarget:"SWBPortalService"},serviceId:f?.serviceId??"SSO",sha256:f?.sha256??Wq,urlParser:f?.urlParser??Aq,utf8Decoder:f?.utf8Decoder??Bq,utf8Encoder:f?.utf8Encoder??$q}),Dj=(f)=>{iq(process.version);let h=hq(f),g=()=>h().then(aq),y=Mj(f);HH(process.version);let w={profile:f?.profile,logger:y.logger};return{...y,...f,runtime:"node",defaultsMode:h,authSchemePreference:f?.authSchemePreference??Fr(Fq,w),bodyLengthChecker:f?.bodyLengthChecker??Hq,defaultUserAgentProvider:f?.defaultUserAgentProvider??qH({serviceId:y.serviceId,clientVersion:tj.version}),maxAttempts:f?.maxAttempts??Fr(Nq,f),region:f?.region??Fr(gq,{...yq,...w}),requestHandler:jq.create(f?.requestHandler??g),retryMode:f?.retryMode??Fr({...kq,default:async()=>(await g()).retryMode||vq},f),streamCollector:f?.streamCollector??qq,useDualstackEndpoint:f?.useDualstackEndpoint??Fr(mq,w),useFipsEndpoint:f?.useFipsEndpoint??Fr(pq,w),userAgentAppId:f?.userAgentAppId??Fr(jH,w)}},Uj=(f)=>{let{httpAuthSchemes:h,httpAuthSchemeProvider:g,credentials:y}=f;return{setHttpAuthScheme(w){let S=h.findIndex((x)=>x.schemeId===w.schemeId);if(S===-1)h.push(w);else h.splice(S,1,w)},httpAuthSchemes(){return h},setHttpAuthSchemeProvider(w){g=w},httpAuthSchemeProvider(){return g},setCredentials(w){y=w},credentials(){return y}}},Fj=(f)=>({httpAuthSchemes:f.httpAuthSchemes(),httpAuthSchemeProvider:f.httpAuthSchemeProvider(),credentials:f.credentials()}),$j=(f,h)=>{let g=Object.assign(VH(f),cq(f),Iq(f),Uj(f));return h.forEach((y)=>y.configure(g)),Object.assign(f,WH(g),uq(g),Cq(g),Fj(g))};class Ad extends mw{config;constructor(...[f]){let h=Dj(f||{});super(h);this.initConfig=h;let g=Yq(h),y=GH(g),w=Oq(y),S=Sq(w),x=KH(S),_=_q(x),A=Xq(_),P=$j(A,f?.extensions||[]);this.config=P,this.middlewareStack.use(Mq(this.config)),this.middlewareStack.use(JH(this.config)),this.middlewareStack.use(Pq(this.config)),this.middlewareStack.use(Rq(this.config)),this.middlewareStack.use(QH(this.config)),this.middlewareStack.use(XH(this.config)),this.middlewareStack.use(YH(this.config)),this.middlewareStack.use(eq(this.config,{httpAuthSchemeParametersProvider:Gq,identityProviderConfigProvider:async(D)=>new tq({"aws.auth#sigv4":D.credentials})})),this.middlewareStack.use(rq(this.config))}destroy(){super.destroy()}}var Bj=dq(Zq,"SWBPortalService","SSOClient",Tq),Lj={},zj=(f,h,g,y)=>[];class Id extends Bj(Lj,zj,"GetRoleCredentials",vw){}var Hj={GetRoleCredentialsCommand:Id};class Cd extends Ad{}lq(Hj,Cd);qj.GetRoleCredentials$=vw;qj.GetRoleCredentialsCommand=Id;qj.GetRoleCredentialsRequest$=Iw;qj.GetRoleCredentialsResponse$=Cw;qj.InvalidRequestException=ki;qj.InvalidRequestException$=bw;qj.ResourceNotFoundException=Ni;qj.ResourceNotFoundException$=xw;qj.RoleCredentials$=Rw;qj.SSO=Cd;qj.SSOClient=Ad;qj.SSOServiceException=ar;qj.SSOServiceException$=Ew;qj.TooManyRequestsException=Mi;qj.TooManyRequestsException$=_w;qj.UnauthorizedException=Ui;qj.UnauthorizedException$=Tw;qj.errorTypeRegistries=Aw});var Nw=i(function(fV){var{GetRoleCredentialsCommand:dV,SSOClient:lV}=kw();fV.GetRoleCredentialsCommand=dV;fV.SSOClient=lV});var Rd=i(function(bV){var{CredentialsProviderError:It,getSSOTokenFromFile:mV,getProfileName:gV,parseKnownFiles:yV,loadSsoSessionData:SV}=Ce(),{setCredentialFeature:Ow}=nt(),{fromSso:wV}=cw(),Mw=(f)=>f&&(typeof f.sso_start_url==="string"||typeof f.sso_account_id==="string"||typeof f.sso_session==="string"||typeof f.sso_region==="string"||typeof f.sso_role_name==="string"),Pw=async({ssoStartUrl:f,ssoSession:h,ssoAccountId:g,ssoRegion:y,ssoRoleName:w,ssoClient:S,clientConfig:x,parentClientConfig:_,callerClientConfig:A,profile:P,filepath:D,configFilepath:U,ignoreCache:B,logger:z})=>{let k,R="To refresh this SSO session run aws sso login with the corresponding profile.";if(h)try{let ve=await wV({profile:P,filepath:D,configFilepath:U,ignoreCache:B,clientConfig:x,parentClientConfig:_,logger:z})({callerClientConfig:A});k={accessToken:ve.token,expiresAt:new Date(ve.expiration).toISOString()}}catch(ve){throw new It(ve.message,{tryNextLink:!1,logger:z})}else try{k=await mV(f)}catch(ve){throw new It("The SSO session associated with this profile is invalid. To refresh this SSO session run aws sso login with the corresponding profile.",{tryNextLink:!1,logger:z})}if(new Date(k.expiresAt).getTime()-Date.now()<=0)throw new It("The SSO session associated with this profile has expired. To refresh this SSO session run aws sso login with the corresponding profile.",{tryNextLink:!1,logger:z});let{accessToken:N}=k,{SSOClient:q,GetRoleCredentialsCommand:V}=Nw(),W=S||new q(Object.assign({},x??{},{logger:x?.logger??A?.logger??_?.logger,region:x?.region??y,userAgentAppId:x?.userAgentAppId??A?.userAgentAppId??_?.userAgentAppId})),G;try{G=await W.send(new V({accountId:g,roleName:w,accessToken:N}))}catch(ve){throw new It(ve,{tryNextLink:!1,logger:z})}let{roleCredentials:{accessKeyId:K,secretAccessKey:J,sessionToken:re,expiration:Y,credentialScope:X,accountId:ie}={}}=G;if(!K||!J||!re||!Y)throw new It("SSO returns an invalid temporary credential.",{tryNextLink:!1,logger:z});let ye={accessKeyId:K,secretAccessKey:J,sessionToken:re,expiration:new Date(Y),...X&&{credentialScope:X},...ie&&{accountId:ie}};if(h)Ow(ye,"CREDENTIALS_SSO","s");else Ow(ye,"CREDENTIALS_SSO_LEGACY","u");return ye},Dw=(f,h)=>{let{sso_start_url:g,sso_account_id:y,sso_region:w,sso_role_name:S}=f;if(!g||!y||!w||!S)throw new It(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(f).join(", ")}
60
+ Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`,{tryNextLink:!1,logger:h});return f},EV=(f={})=>async({callerClientConfig:h}={})=>{f.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO");let{ssoStartUrl:g,ssoAccountId:y,ssoRegion:w,ssoRoleName:S,ssoSession:x}=f,{ssoClient:_}=f,A=gV({profile:f.profile??h?.profile});if(!g&&!y&&!w&&!S&&!x){let D=(await yV(f))[A];if(!D)throw new It(`Profile ${A} was not found.`,{logger:f.logger});if(!Mw(D))throw new It(`Profile ${A} is not configured with SSO credentials.`,{logger:f.logger});if(D?.sso_session){let q=(await SV(f))[D.sso_session],V=` configurations in profile ${A} and sso-session ${D.sso_session}`;if(w&&w!==q.sso_region)throw new It("Conflicting SSO region"+V,{tryNextLink:!1,logger:f.logger});if(g&&g!==q.sso_start_url)throw new It("Conflicting SSO start_url"+V,{tryNextLink:!1,logger:f.logger});D.sso_region=q.sso_region,D.sso_start_url=q.sso_start_url}let{sso_start_url:U,sso_account_id:B,sso_region:z,sso_role_name:k,sso_session:R}=Dw(D,f.logger);return Pw({ssoStartUrl:U,ssoSession:R,ssoAccountId:B,ssoRegion:z,ssoRoleName:k,ssoClient:_,clientConfig:f.clientConfig,parentClientConfig:f.parentClientConfig,callerClientConfig:f.callerClientConfig,profile:A,filepath:f.filepath,configFilepath:f.configFilepath,ignoreCache:f.ignoreCache,logger:f.logger})}else if(!g||!y||!w||!S)throw new It('Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"',{tryNextLink:!1,logger:f.logger});else return Pw({ssoStartUrl:g,ssoSession:x,ssoAccountId:y,ssoRegion:w,ssoRoleName:S,ssoClient:_,clientConfig:f.clientConfig,parentClientConfig:f.parentClientConfig,callerClientConfig:f.callerClientConfig,profile:A,filepath:f.filepath,configFilepath:f.configFilepath,ignoreCache:f.ignoreCache,logger:f.logger})};bV.fromSSO=EV;bV.isSsoProfile=Mw;bV.validateSsoProfile=Dw});var zw=i(function(IV){var{SignatureV4:AV,signatureV4aContainer:Uw}=Du(),Rs={CrtSignerV4:null},Fw="X-Amz-S3session-Token".toLowerCase();class vd extends AV{async signWithCredentials(f,h,g){let y=$w(h);f.headers[Fw]=h.sessionToken;let w=this;return Bw(w,y),w.signRequest(f,g??{})}async presignWithCredentials(f,h,g){let y=$w(h);return delete f.headers[Fw],f.headers["X-Amz-S3session-Token"]=h.sessionToken,f.query=f.query??{},f.query["X-Amz-S3session-Token"]=h.sessionToken,Bw(this,y),this.presign(f,g)}}function $w(f){return{accessKeyId:f.accessKeyId,secretAccessKey:f.secretAccessKey,expiration:f.expiration}}function Bw(f,h){let g=f.credentialProvider;f.credentialProvider=()=>(f.credentialProvider=g,Promise.resolve(h))}class Lw{sigv4aSigner;sigv4Signer;signerOptions;static sigv4aDependency(){if(typeof Rs.CrtSignerV4==="function")return"crt";else if(typeof Uw.SignatureV4a==="function")return"js";return"none"}constructor(f){this.sigv4Signer=new vd(f),this.signerOptions=f}async sign(f,h={}){if(h.signingRegion==="*")return this.getSigv4aSigner().sign(f,h);return this.sigv4Signer.sign(f,h)}async signWithCredentials(f,h,g={}){if(g.signingRegion==="*"){let y=this.getSigv4aSigner(),w=Rs.CrtSignerV4;if(w&&y instanceof w)return y.signWithCredentials(f,h,g);else throw Error(`signWithCredentials with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`)}return this.sigv4Signer.signWithCredentials(f,h,g)}async presign(f,h={}){if(h.signingRegion==="*"){let g=this.getSigv4aSigner(),y=Rs.CrtSignerV4;if(y&&g instanceof y)return g.presign(f,h);else throw Error(`presign with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`)}return this.sigv4Signer.presign(f,h)}async presignWithCredentials(f,h,g={}){if(g.signingRegion==="*")throw Error("Method presignWithCredentials is not supported for [signingRegion=*].");return this.sigv4Signer.presignWithCredentials(f,h,g)}getSigv4aSigner(){if(!this.sigv4aSigner){let f=Rs.CrtSignerV4,h=Uw.SignatureV4a;if(this.signerOptions.runtime==="node"){if(!f&&!h)throw Error("Neither CRT nor JS SigV4a implementation is available. Please load either @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt");if(f&&typeof f==="function")this.sigv4aSigner=new f({...this.signerOptions,signingAlgorithm:1});else if(h&&typeof h==="function")this.sigv4aSigner=new h({...this.signerOptions});else throw Error("Available SigV4a implementation is not a valid constructor. Please ensure you've properly imported @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a.For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt")}else{if(!h||typeof h!=="function")throw Error("JS SigV4a implementation is not available or not a valid constructor. Please check whether you have installed the @aws-sdk/signature-v4a package explicitly. The CRT implementation is not available for browsers. You must also register the package by calling [require('@aws-sdk/signature-v4a');] or an ESM equivalent such as [import '@aws-sdk/signature-v4a';]. For more information please go to https://github.com/aws/aws-sdk-js-v3#using-javascript-non-crt-implementation-of-sigv4a");this.sigv4aSigner=new h({...this.signerOptions})}}return this.sigv4aSigner}}IV.SignatureV4MultiRegion=Lw;IV.SignatureV4SignWithCredentials=vd;IV.signatureV4CrtContainer=Rs});var Ld=i(function(eW){var{awsEndpointFunctions:kV,emitWarningIfUnsupportedVersion:NV,createDefaultUserAgentProvider:OV,NODE_APP_ID_CONFIG_OPTIONS:PV,getAwsRegionExtensionConfiguration:MV,resolveAwsRegionExtensionConfiguration:DV,resolveUserAgentConfig:UV,resolveHostHeaderConfig:FV,getUserAgentPlugin:$V,getHostHeaderPlugin:BV,getLoggerPlugin:LV,getRecursionDetectionPlugin:zV,setCredentialFeature:Od,stsRegionDefaultResolver:HV}=nt(),{NoAuthSigner:Xw,getHttpAuthSchemeEndpointRuleSetPlugin:qV,DefaultIdentityProviderConfig:jV,getHttpSigningPlugin:VV}=rr(),{normalizeProvider:Yw,getSmithyContext:Zw,ServiceException:WV,NoOpLogger:GV,emitWarningIfUnsupportedVersion:KV,loadConfigsForDefaultMode:JV,getDefaultExtensionConfiguration:QV,resolveDefaultRuntimeConfig:XV,Client:eE,makeBuilder:YV,createAggregatedClient:ZV}=ct(),{Command:e6}=ct();eW.$Command=e6;eW.__Client=eE;var{resolveDefaultsModeConfig:t6,loadConfig:cr,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:r6,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:n6,NODE_REGION_CONFIG_OPTIONS:s6,NODE_REGION_CONFIG_FILE_OPTIONS:o6,resolveRegionConfig:i6}=Ce(),{BinaryDecisionDiagram:a6,EndpointCache:c6,decideEndpoint:u6,customEndpointFunctions:d6,resolveParams:l6,resolveEndpointConfig:f6,getEndpointPlugin:h6}=Yt(),{parseUrl:p6,getHttpHandlerExtensionConfiguration:m6,resolveHttpHandlerRuntimeConfig:g6,getContentLengthPlugin:y6}=Ne(),{DEFAULT_RETRY_MODE:S6,NODE_RETRY_MODE_CONFIG_OPTIONS:w6,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:E6,resolveRetryConfig:b6,getRetryPlugin:x6}=fn(),{TypeRegistry:tE,getSchemaSerdePlugin:_6}=Rt(),{resolveAwsSdkSigV4Config:T6,resolveAwsSdkSigV4AConfig:A6,AwsSdkSigV4Signer:rE,AwsSdkSigV4ASigner:nE,NODE_SIGV4A_CONFIG_OPTIONS:I6,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:C6}=yn(),{SignatureV4MultiRegion:sE}=zw(),{toUtf8:R6,fromUtf8:v6,toBase64:k6,fromBase64:N6,calculateBodyLength:O6}=Ke(),{streamCollector:P6,NodeHttpHandler:M6}=pn(),{AwsQueryProtocol:D6}=Ts(),{Sha256:U6}=tn(),Rn="ref",Br=-1,vs=!0,Hw="isSet",oE="PartitionResult",ks="booleanEquals",je="stringEquals",kd="getAttr",qw="us-east-1",Vw="sigv4",Ww="sts",Gw="https://sts.{Region}.{PartitionResult#dnsSuffix}",Kw={[Rn]:"Endpoint"},Ve={[Rn]:"Region"},Nd={[Rn]:oE},Cn={},Jw=[Ve],Qw={conditions:[[Hw,[Kw]],[Hw,Jw],["aws.partition",Jw,oE],[ks,[{[Rn]:"UseFIPS"},vs]],[ks,[{[Rn]:"UseDualStack"},vs]],[je,[Ve,"aws-global"]],[ks,[{[Rn]:"UseGlobalEndpoint"},vs]],[je,[Ve,"eu-central-1"]],[ks,[{fn:kd,argv:[Nd,"supportsDualStack"]},vs]],[ks,[{fn:kd,argv:[Nd,"supportsFIPS"]},vs]],[je,[Ve,"ap-south-1"]],[je,[Ve,"eu-north-1"]],[je,[Ve,"eu-west-1"]],[je,[Ve,"eu-west-2"]],[je,[Ve,"eu-west-3"]],[je,[Ve,"sa-east-1"]],[je,[Ve,qw]],[je,[Ve,"us-east-2"]],[je,[Ve,"us-west-2"]],[je,[Ve,"us-west-1"]],[je,[Ve,"ca-central-1"]],[je,[Ve,"ap-southeast-1"]],[je,[Ve,"ap-northeast-1"]],[je,[Ve,"ap-southeast-2"]],[je,[{fn:kd,argv:[Nd,"name"]},"aws-us-gov"]]],results:[[Br],["https://sts.amazonaws.com",{authSchemes:[{name:Vw,signingName:Ww,signingRegion:qw}]}],[Gw,{authSchemes:[{name:Vw,signingName:Ww,signingRegion:"{Region}"}]}],[Br,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Br,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[Kw,Cn],["https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Cn],[Br,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://sts.{Region}.amazonaws.com",Cn],["https://sts-fips.{Region}.{PartitionResult#dnsSuffix}",Cn],[Br,"FIPS is enabled but this partition does not support FIPS"],["https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}",Cn],[Br,"DualStack is enabled but this partition does not support DualStack"],[Gw,Cn],[Br,"Invalid Configuration: Missing Region"]]},F6=2,me=1e8,$6=new Int32Array([-1,1,-1,0,30,3,1,4,me+14,2,5,me+14,3,25,6,4,24,7,5,me+1,8,6,9,me+13,7,me+1,10,10,me+1,11,11,me+1,12,12,me+1,13,13,me+1,14,14,me+1,15,15,me+1,16,16,me+1,17,17,me+1,18,18,me+1,19,19,me+1,20,20,me+1,21,21,me+1,22,22,me+1,23,23,me+1,me+2,8,me+11,me+12,4,28,26,9,27,me+10,24,me+8,me+9,8,29,me+7,9,me+6,me+7,3,me+3,31,4,me+4,me+5]),B6=a6.from($6,F6,Qw.conditions,Qw.results),L6=new c6({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS","UseGlobalEndpoint"]}),iE=(f,h={})=>L6.get(f,()=>u6(B6,{endpointParams:f,logger:h.logger}));d6.aws=kV;var z6=(f)=>async(h,g,y)=>{if(!y)throw Error("Could not find `input` for `defaultEndpointRuleSetHttpAuthSchemeParametersProvider`");let w=await f(h,g,y),S=Zw(g)?.commandInstance?.constructor?.getEndpointParameterInstructions;if(!S)throw Error(`getEndpointParameterInstructions() is not defined on '${g.commandName}'`);let x=await l6(y,{getEndpointParameterInstructions:S},h);return Object.assign(w,x)},H6=async(f,h,g)=>({operation:Zw(h).operation,region:await Yw(f.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}),q6=z6(H6);function aE(f){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:f.region},propertiesExtractor:(h,g)=>({signingProperties:{config:h,context:g}})}}function Pd(f){return{schemeId:"aws.auth#sigv4a",signingProperties:{name:"sts",region:f.region},propertiesExtractor:(h,g)=>({signingProperties:{config:h,context:g}})}}function cE(f){return{schemeId:"smithy.api#noAuth"}}var j6=(f,h,g)=>(w)=>{let x=f(w).properties?.authSchemes;if(!x)return h(w);let _=[];for(let A of x){let{name:P,properties:D={},...U}=A,B=P.toLowerCase();if(P!==B)console.warn(`HttpAuthScheme has been normalized with lowercasing: '${P}' to '${B}'`);let z;if(B==="sigv4a"){z="aws.auth#sigv4a";let N=x.find((q)=>{let V=q.name.toLowerCase();return V!=="sigv4a"&&V.startsWith("sigv4")});if(sE.sigv4aDependency()==="none"&&N)continue}else if(B.startsWith("sigv4"))z="aws.auth#sigv4";else throw Error(`Unknown HttpAuthScheme found in '@smithy.rules#endpointRuleSet': '${B}'`);let k=g[z];if(!k)throw Error(`Could not find HttpAuthOption create function for '${z}'`);let R=k(w);R.schemeId=z,R.signingProperties={...R.signingProperties||{},...U,...D},_.push(R)}return _},V6=(f)=>{let h=[];switch(f.operation){case"AssumeRoleWithWebIdentity":{h.push(cE()),h.push(Pd(f));break}default:h.push(aE(f)),h.push(Pd(f))}return h},W6=j6(iE,V6,{"aws.auth#sigv4":aE,"aws.auth#sigv4a":Pd,"smithy.api#noAuth":cE}),G6=(f)=>{let h=T6(f),g=A6(h);return Object.assign(g,{authSchemePreference:Yw(f.authSchemePreference??[])})},K6=(f)=>Object.assign(f,{useDualstackEndpoint:f.useDualstackEndpoint??!1,useFipsEndpoint:f.useFipsEndpoint??!1,useGlobalEndpoint:f.useGlobalEndpoint??!1,defaultSigningName:"sts"}),J6={UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},Q6="3.997.52",X6={version:Q6};class Ct extends WV{static shapeId="smithy.ts.sdk.synthetic.com.amazonaws.sts#STSServiceException";constructor(f){super(f);Object.setPrototypeOf(this,Ct.prototype)}}class zi extends Ct{static shapeId="com.amazonaws.sts#ExpiredTokenException";name="ExpiredTokenException";$fault="client";constructor(f){super({name:"ExpiredTokenException",$fault:"client",...f});Object.setPrototypeOf(this,zi.prototype)}}class Hi extends Ct{static shapeId="com.amazonaws.sts#MalformedPolicyDocumentException";name="MalformedPolicyDocumentException";$fault="client";constructor(f){super({name:"MalformedPolicyDocumentException",$fault:"client",...f});Object.setPrototypeOf(this,Hi.prototype)}}class qi extends Ct{static shapeId="com.amazonaws.sts#PackedPolicyTooLargeException";name="PackedPolicyTooLargeException";$fault="client";constructor(f){super({name:"PackedPolicyTooLargeException",$fault:"client",...f});Object.setPrototypeOf(this,qi.prototype)}}class ji extends Ct{static shapeId="com.amazonaws.sts#RegionDisabledException";name="RegionDisabledException";$fault="client";constructor(f){super({name:"RegionDisabledException",$fault:"client",...f});Object.setPrototypeOf(this,ji.prototype)}}class Vi extends Ct{static shapeId="com.amazonaws.sts#IDPRejectedClaimException";name="IDPRejectedClaimException";$fault="client";constructor(f){super({name:"IDPRejectedClaimException",$fault:"client",...f});Object.setPrototypeOf(this,Vi.prototype)}}class Wi extends Ct{static shapeId="com.amazonaws.sts#InvalidIdentityTokenException";name="InvalidIdentityTokenException";$fault="client";constructor(f){super({name:"InvalidIdentityTokenException",$fault:"client",...f});Object.setPrototypeOf(this,Wi.prototype)}}class Gi extends Ct{static shapeId="com.amazonaws.sts#IDPCommunicationErrorException";name="IDPCommunicationErrorException";$fault="client";$retryable={};constructor(f){super({name:"IDPCommunicationErrorException",$fault:"client",...f});Object.setPrototypeOf(this,Gi.prototype)}}var Y6="Arn",Z6="AccessKeyId",e3="AssumeRole",t3="AssumedRoleId",r3="AssumeRoleRequest",n3="AssumeRoleResponse",Md="AssumedRoleUser",s3="AssumeRoleWithWebIdentity",o3="AssumeRoleWithWebIdentityRequest",i3="AssumeRoleWithWebIdentityResponse",a3="Audience",Dd="Credentials",c3="ContextAssertion",uE="DurationSeconds",u3="Expiration",d3="ExternalId",l3="ExpiredTokenException",f3="IDPCommunicationErrorException",h3="IDPRejectedClaimException",p3="InvalidIdentityTokenException",m3="Key",g3="MalformedPolicyDocumentException",dE="MinimumSessionTokenSize",lE="Policy",fE="PolicyArns",y3="ProviderArn",S3="ProvidedContexts",w3="ProvidedContextsListType",E3="ProvidedContext",b3="PolicyDescriptorType",x3="ProviderId",hE="PackedPolicySize",_3="PackedPolicyTooLargeException",T3="Provider",pE="RoleArn",A3="RegionDisabledException",mE="RoleSessionName",I3="SecretAccessKey",C3="SubjectFromWebIdentityToken",Ud="SourceIdentity",R3="SerialNumber",v3="SessionToken",gE="SessionTokenSize",yE="SessionTokenUtilization",k3="Tags",N3="TokenCode",O3="TransitiveTagKeys",P3="Tag",M3="Value",D3="WebIdentityToken",U3="arn",F3="accessKeySecretType",Lr="awsQueryError",zr="client",$3="clientTokenType",Hr="error",qr="httpError",jr="message",B3="policyDescriptorListType",SE="smithy.ts.sdk.synthetic.com.amazonaws.sts",L3="tagListType",be="com.amazonaws.sts",wE=new tE(SE),EE=[-3,SE,"STSServiceException",0,[],[]];wE.registerError(EE,Ct);var ur=new tE(be),bE=[-3,be,l3,{[Lr]:["ExpiredTokenException",400],[Hr]:zr,[qr]:400},[jr],[0]];ur.registerError(bE,zi);var xE=[-3,be,f3,{[Lr]:["IDPCommunicationError",400],[Hr]:zr,[qr]:400},[jr],[0]];ur.registerError(xE,Gi);var _E=[-3,be,h3,{[Lr]:["IDPRejectedClaim",403],[Hr]:zr,[qr]:403},[jr],[0]];ur.registerError(_E,Vi);var TE=[-3,be,p3,{[Lr]:["InvalidIdentityToken",400],[Hr]:zr,[qr]:400},[jr],[0]];ur.registerError(TE,Wi);var AE=[-3,be,g3,{[Lr]:["MalformedPolicyDocument",400],[Hr]:zr,[qr]:400},[jr],[0]];ur.registerError(AE,Hi);var IE=[-3,be,_3,{[Lr]:["PackedPolicyTooLarge",400],[Hr]:zr,[qr]:400},[jr],[0]];ur.registerError(IE,qi);var CE=[-3,be,A3,{[Lr]:["RegionDisabledException",403],[Hr]:zr,[qr]:403},[jr],[0]];ur.registerError(CE,ji);var RE=[wE,ur],z3=[0,be,F3,8,0],H3=[0,be,$3,8,0],Fd=[3,be,Md,0,[t3,Y6],[0,0],2],vE=[3,be,r3,0,[pE,mE,fE,lE,uE,k3,O3,d3,R3,N3,Ud,S3,dE],[0,0,()=>UE,0,1,()=>j3,64,0,0,0,0,()=>q3,1],2],kE=[3,be,n3,0,[Dd,Md,hE,Ud,yE,gE],[[()=>$d,0],()=>Fd,1,0,1,1]],NE=[3,be,o3,0,[pE,mE,D3,x3,fE,lE,uE,dE],[0,0,[()=>H3,0],0,()=>UE,0,1,1],3],OE=[3,be,i3,0,[Dd,C3,Md,hE,T3,a3,Ud,yE,gE],[[()=>$d,0],0,()=>Fd,1,0,0,0,1,1]],$d=[3,be,Dd,0,[Z6,I3,v3,u3],[0,[()=>z3,0],0,4],4],PE=[3,be,b3,0,[U3],[0]],ME=[3,be,E3,0,[y3,c3],[0,0]],DE=[3,be,P3,0,[m3,M3],[0,0],2],UE=[1,be,B3,0,()=>PE],q3=[1,be,w3,0,()=>ME],j3=[1,be,L3,0,()=>DE],FE=[9,be,e3,0,()=>vE,()=>kE],$E=[9,be,s3,0,()=>NE,()=>OE],V3=(f)=>({apiVersion:"2011-06-15",base64Decoder:f?.base64Decoder??N6,base64Encoder:f?.base64Encoder??k6,disableHostPrefix:f?.disableHostPrefix??!1,endpointProvider:f?.endpointProvider??iE,extensions:f?.extensions??[],httpAuthSchemeProvider:f?.httpAuthSchemeProvider??W6,httpAuthSchemes:f?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(h)=>h.getIdentityProvider("aws.auth#sigv4"),signer:new rE},{schemeId:"aws.auth#sigv4a",identityProvider:(h)=>h.getIdentityProvider("aws.auth#sigv4a"),signer:new nE},{schemeId:"smithy.api#noAuth",identityProvider:(h)=>h.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new Xw}],logger:f?.logger??new GV,protocol:f?.protocol??D6,protocolSettings:f?.protocolSettings??{defaultNamespace:"com.amazonaws.sts",errorTypeRegistries:RE,xmlNamespace:"https://sts.amazonaws.com/doc/2011-06-15/",version:"2011-06-15",serviceTarget:"AWSSecurityTokenServiceV20110615"},serviceId:f?.serviceId??"STS",sha256:f?.sha256??U6,signerConstructor:f?.signerConstructor??sE,urlParser:f?.urlParser??p6,utf8Decoder:f?.utf8Decoder??v6,utf8Encoder:f?.utf8Encoder??R6}),W3=(f)=>{KV(process.version);let h=t6(f),g=()=>h().then(JV),y=V3(f);NV(process.version);let w={profile:f?.profile,logger:y.logger};return{...y,...f,runtime:"node",defaultsMode:h,authSchemePreference:f?.authSchemePreference??cr(C6,w),bodyLengthChecker:f?.bodyLengthChecker??O6,defaultUserAgentProvider:f?.defaultUserAgentProvider??OV({serviceId:y.serviceId,clientVersion:X6.version}),httpAuthSchemes:f?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(S)=>S.getIdentityProvider("aws.auth#sigv4")||(async(x)=>await f.credentialDefaultProvider(x?.__config||{})()),signer:new rE},{schemeId:"aws.auth#sigv4a",identityProvider:(S)=>S.getIdentityProvider("aws.auth#sigv4a"),signer:new nE},{schemeId:"smithy.api#noAuth",identityProvider:(S)=>S.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new Xw}],maxAttempts:f?.maxAttempts??cr(E6,f),region:f?.region??cr(s6,{...o6,...w}),requestHandler:M6.create(f?.requestHandler??g),retryMode:f?.retryMode??cr({...w6,default:async()=>(await g()).retryMode||S6},f),sigv4aSigningRegionSet:f?.sigv4aSigningRegionSet??cr(I6,w),streamCollector:f?.streamCollector??P6,useDualstackEndpoint:f?.useDualstackEndpoint??cr(n6,w),useFipsEndpoint:f?.useFipsEndpoint??cr(r6,w),userAgentAppId:f?.userAgentAppId??cr(PV,w)}},G3=(f)=>{let{httpAuthSchemes:h,httpAuthSchemeProvider:g,credentials:y}=f;return{setHttpAuthScheme(w){let S=h.findIndex((x)=>x.schemeId===w.schemeId);if(S===-1)h.push(w);else h.splice(S,1,w)},httpAuthSchemes(){return h},setHttpAuthSchemeProvider(w){g=w},httpAuthSchemeProvider(){return g},setCredentials(w){y=w},credentials(){return y}}},K3=(f)=>({httpAuthSchemes:f.httpAuthSchemes(),httpAuthSchemeProvider:f.httpAuthSchemeProvider(),credentials:f.credentials()}),J3=(f,h)=>{let g=Object.assign(MV(f),QV(f),m6(f),G3(f));return h.forEach((y)=>y.configure(g)),Object.assign(f,DV(g),XV(g),g6(g),K3(g))};class Os extends eE{config;constructor(...[f]){let h=W3(f||{});super(h);this.initConfig=h;let g=K6(h),y=UV(g),w=b6(y),S=i6(w),x=FV(S),_=f6(x),A=G6(_),P=J3(A,f?.extensions||[]);this.config=P,this.middlewareStack.use(_6(this.config)),this.middlewareStack.use($V(this.config)),this.middlewareStack.use(x6(this.config)),this.middlewareStack.use(y6(this.config)),this.middlewareStack.use(BV(this.config)),this.middlewareStack.use(LV(this.config)),this.middlewareStack.use(zV(this.config)),this.middlewareStack.use(qV(this.config,{httpAuthSchemeParametersProvider:q6,identityProviderConfigProvider:async(D)=>new jV({"aws.auth#sigv4":D.credentials,"aws.auth#sigv4a":D.credentials})})),this.middlewareStack.use(VV(this.config))}destroy(){super.destroy()}}var BE=YV(J6,"AWSSecurityTokenServiceV20110615","STSClient",h6),LE={},zE=(f,h,g,y)=>[];class Ki extends BE(LE,zE,"AssumeRole",FE){}class Ji extends BE(LE,zE,"AssumeRoleWithWebIdentity",$E){}var Q3={AssumeRoleCommand:Ki,AssumeRoleWithWebIdentityCommand:Ji};class Bd extends Os{}ZV(Q3,Bd);var HE=(f)=>{if(typeof f?.Arn==="string"){let h=f.Arn.split(":");if(h.length>4&&h[4]!=="")return h[4]}return},qE=async(f,h,g,y={})=>{let w=typeof f==="function"?await f():f,S=typeof h==="function"?await h():h,x="",_=w??S??(x=await HV(y)());return g?.debug?.("@aws-sdk/client-sts::resolveRegion","accepting first of:",`${w} (credential provider clientConfig)`,`${S} (contextual client)`,`${x} (STS default: AWS_REGION, profile region, or us-east-1)`),_},X3=(f,h)=>{let g,y;return async(w,S)=>{if(y=w,!g){let{logger:D=f?.parentClientConfig?.logger,profile:U=f?.parentClientConfig?.profile,region:B,requestHandler:z=f?.parentClientConfig?.requestHandler,credentialProviderLogger:k,userAgentAppId:R=f?.parentClientConfig?.userAgentAppId}=f,N=await qE(B,f?.parentClientConfig?.region,k,{logger:D,profile:U}),q=!jE(z);g=new h({...f,userAgentAppId:R,profile:U,credentialDefaultProvider:()=>async()=>y,region:N,requestHandler:q?z:void 0,logger:D})}let{Credentials:x,AssumedRoleUser:_}=await g.send(new Ki(S));if(!x||!x.AccessKeyId||!x.SecretAccessKey)throw Error(`Invalid response from STS.assumeRole call with role ${S.RoleArn}`);let A=HE(_),P={accessKeyId:x.AccessKeyId,secretAccessKey:x.SecretAccessKey,sessionToken:x.SessionToken,expiration:x.Expiration,...x.CredentialScope&&{credentialScope:x.CredentialScope},...A&&{accountId:A}};return Od(P,"CREDENTIALS_STS_ASSUME_ROLE","i"),P}},Y3=(f,h)=>{let g;return async(y)=>{if(!g){let{logger:A=f?.parentClientConfig?.logger,profile:P=f?.parentClientConfig?.profile,region:D,requestHandler:U=f?.parentClientConfig?.requestHandler,credentialProviderLogger:B,userAgentAppId:z=f?.parentClientConfig?.userAgentAppId}=f,k=await qE(D,f?.parentClientConfig?.region,B,{logger:A,profile:P}),R=!jE(U);g=new h({...f,userAgentAppId:z,profile:P,region:k,requestHandler:R?U:void 0,logger:A})}let{Credentials:w,AssumedRoleUser:S}=await g.send(new Ji(y));if(!w||!w.AccessKeyId||!w.SecretAccessKey)throw Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${y.RoleArn}`);let x=HE(S),_={accessKeyId:w.AccessKeyId,secretAccessKey:w.SecretAccessKey,sessionToken:w.SessionToken,expiration:w.Expiration,...w.CredentialScope&&{credentialScope:w.CredentialScope},...x&&{accountId:x}};if(x)Od(_,"RESOLVED_ACCOUNT_ID","T");return Od(_,"CREDENTIALS_STS_ASSUME_ROLE_WEB_ID","k"),_}},jE=(f)=>f?.metadata?.handlerProtocol==="h2",VE=(f,h)=>{if(!h)return f;else return class extends f{constructor(y){super(y);for(let w of h)this.middlewareStack.use(w)}}},WE=(f={},h)=>X3(f,VE(Os,h)),GE=(f={},h)=>Y3(f,VE(Os,h)),Z3=(f)=>(h)=>f({roleAssumer:WE(h),roleAssumerWithWebIdentity:GE(h),...h});eW.AssumeRole$=FE;eW.AssumeRoleCommand=Ki;eW.AssumeRoleRequest$=vE;eW.AssumeRoleResponse$=kE;eW.AssumeRoleWithWebIdentity$=$E;eW.AssumeRoleWithWebIdentityCommand=Ji;eW.AssumeRoleWithWebIdentityRequest$=NE;eW.AssumeRoleWithWebIdentityResponse$=OE;eW.AssumedRoleUser$=Fd;eW.Credentials$=$d;eW.ExpiredTokenException=zi;eW.ExpiredTokenException$=bE;eW.IDPCommunicationErrorException=Gi;eW.IDPCommunicationErrorException$=xE;eW.IDPRejectedClaimException=Vi;eW.IDPRejectedClaimException$=_E;eW.InvalidIdentityTokenException=Wi;eW.InvalidIdentityTokenException$=TE;eW.MalformedPolicyDocumentException=Hi;eW.MalformedPolicyDocumentException$=AE;eW.PackedPolicyTooLargeException=qi;eW.PackedPolicyTooLargeException$=IE;eW.PolicyDescriptorType$=PE;eW.ProvidedContext$=ME;eW.RegionDisabledException=ji;eW.RegionDisabledException$=CE;eW.STS=Bd;eW.STSClient=Os;eW.STSServiceException=Ct;eW.STSServiceException$=EE;eW.Tag$=DE;eW.decorateDefaultCredentialProvider=Z3;eW.errorTypeRegistries=RE;eW.getDefaultRoleAssumer=WE;eW.getDefaultRoleAssumerWithWebIdentity=GE});var Mb=i(function($5){var{awsEndpointFunctions:$W,emitWarningIfUnsupportedVersion:BW,createDefaultUserAgentProvider:LW,NODE_APP_ID_CONFIG_OPTIONS:zW,getAwsRegionExtensionConfiguration:HW,resolveAwsRegionExtensionConfiguration:qW,resolveUserAgentConfig:jW,resolveHostHeaderConfig:VW,getUserAgentPlugin:WW,getHostHeaderPlugin:GW,getLoggerPlugin:KW,getRecursionDetectionPlugin:JW}=nt(),{NoAuthSigner:QW,getHttpAuthSchemeEndpointRuleSetPlugin:XW,DefaultIdentityProviderConfig:YW,getHttpSigningPlugin:ZW}=rr(),{normalizeProvider:ub,getSmithyContext:e8,ServiceException:t8,NoOpLogger:r8,emitWarningIfUnsupportedVersion:n8,loadConfigsForDefaultMode:s8,getDefaultExtensionConfiguration:o8,resolveDefaultRuntimeConfig:i8,Client:db,makeBuilder:a8,createAggregatedClient:c8}=ct(),{Command:u8}=ct();$5.$Command=u8;$5.__Client=db;var{resolveDefaultsModeConfig:d8,loadConfig:Vr,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:l8,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:f8,NODE_REGION_CONFIG_OPTIONS:h8,NODE_REGION_CONFIG_FILE_OPTIONS:p8,resolveRegionConfig:m8}=Ce(),{BinaryDecisionDiagram:g8,EndpointCache:y8,decideEndpoint:S8,customEndpointFunctions:w8,resolveEndpointConfig:E8,getEndpointPlugin:b8}=Yt(),{parseUrl:x8,getHttpHandlerExtensionConfiguration:_8,resolveHttpHandlerRuntimeConfig:T8,getContentLengthPlugin:A8}=Ne(),{DEFAULT_RETRY_MODE:I8,NODE_RETRY_MODE_CONFIG_OPTIONS:C8,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:R8,resolveRetryConfig:v8,getRetryPlugin:k8}=fn(),{TypeRegistry:lb,getSchemaSerdePlugin:N8}=Rt(),{resolveAwsSdkSigV4Config:O8,AwsSdkSigV4Signer:P8,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:M8}=yn(),{toUtf8:D8,fromUtf8:U8,toBase64:F8,fromBase64:$8,calculateBodyLength:B8}=Ke(),{streamCollector:L8,NodeHttpHandler:z8}=pn(),{AwsRestJsonProtocol:H8}=Ts(),{Sha256:q8}=tn(),j8=async(f,h,g)=>({operation:e8(h).operation,region:await ub(f.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function V8(f){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"signin",region:f.region},propertiesExtractor:(h,g)=>({signingProperties:{config:h,context:g}})}}function W8(f){return{schemeId:"smithy.api#noAuth"}}var G8=(f)=>{let h=[];switch(f.operation){case"CreateOAuth2Token":{h.push(W8());break}default:h.push(V8(f))}return h},K8=(f)=>{let h=O8(f);return Object.assign(h,{authSchemePreference:ub(f.authSchemePreference??[])})},J8=(f)=>Object.assign(f,{useDualstackEndpoint:f.useDualstackEndpoint??!1,useFipsEndpoint:f.useFipsEndpoint??!1,defaultSigningName:"signin"}),Q8={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},X8="3.997.52",Y8={version:X8},fr="ref",dr=-1,KE=!1,vn=!0,JE="isSet",kn="booleanEquals",QE="coalesce",Wd="PartitionResult",Wt="stringEquals",zd="getAttr",XE="https://signin.{Region}.{PartitionResult#dualStackDnsSuffix}",YE={[fr]:"Endpoint"},lr={fn:zd,argv:[{[fr]:Wd},"name"]},fb={[fr]:"Region"},ZE={[fr]:Wd},Qi={authSchemes:[{name:"sigv4",signingName:"signin",signingRegion:"{Region}"}]},Qe={},eb=[fb],tb={conditions:[[JE,eb],[kn,[{fn:QE,argv:[{[fr]:"IsControlPlane"},KE]},vn]],[JE,[YE]],["aws.partition",eb,Wd],[kn,[{[fr]:"UseFIPS"},vn]],[Wt,[lr,"aws"]],[kn,[{fn:QE,argv:[{[fr]:"IsOAuthEndpoint"},KE]},vn]],[kn,[{[fr]:"UseDualStack"},vn]],[Wt,[lr,"aws-cn"]],[Wt,[fb,"us-gov-west-1"]],[Wt,[lr,"aws-us-gov"]],[kn,[{fn:zd,argv:[ZE,"supportsFIPS"]},vn]],[Wt,[lr,"aws-iso"]],[Wt,[lr,"aws-iso-b"]],[Wt,[lr,"aws-iso-f"]],[Wt,[lr,"aws-iso-e"]],[Wt,[lr,"aws-eusc"]],[kn,[{fn:zd,argv:[ZE,"supportsDualStack"]},vn]]],results:[[dr],["https://signin.{Region}.api.aws",Qi],["https://signin.{Region}.api.amazonwebservices.com.cn",Qi],[XE,Qi],[dr,"FIPS endpoints are not supported for OAuth operations. Disable FIPS or use a non-OAuth operation."],["https://{Region}.oauth.signin.aws",Qi],["https://{Region}.signin.aws.amazon.com",Qe],["https://{Region}.signin.amazonaws.cn",Qe],["https://{Region}.signin.amazonaws-us-gov.com",Qe],["https://{Region}.signin.c2shome.ic.gov",Qe],["https://{Region}.signin.sc2shome.sgov.gov",Qe],["https://{Region}.signin.csphome.hci.ic.gov",Qe],["https://{Region}.signin.csphome.adc-e.uk",Qe],["https://{Region}.signin.amazonaws-eusc.eu",Qe],["https://signin-fips.amazonaws-us-gov.com",Qe],["https://{Region}.signin-fips.amazonaws-us-gov.com",Qe],["https://{Region}.signin.{PartitionResult#dnsSuffix}",Qe],[dr,"Invalid Configuration: FIPS and custom endpoint are not supported"],[dr,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[YE,Qe],["https://signin-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Qe],[dr,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://signin-fips.{Region}.{PartitionResult#dnsSuffix}",Qe],[dr,"FIPS is enabled but this partition does not support FIPS"],[XE,Qe],[dr,"DualStack is enabled but this partition does not support DualStack"],["https://signin.{Region}.{PartitionResult#dnsSuffix}",Qe],[dr,"Invalid Configuration: Missing Region"]]},Z8=2,pe=1e8,e5=new Int32Array([-1,1,-1,0,6,3,2,36,4,4,5,pe+27,6,pe+4,pe+27,1,29,7,2,36,8,3,9,31,4,22,10,5,19,11,7,21,12,8,pe+7,13,10,pe+8,14,12,pe+9,15,13,pe+10,16,14,pe+11,17,15,pe+12,18,16,pe+13,pe+16,6,pe+5,20,7,21,pe+6,17,pe+24,pe+25,6,pe+4,23,7,27,24,9,pe+14,25,10,pe+15,26,11,pe+22,pe+23,11,28,pe+21,17,pe+20,pe+21,2,35,30,3,39,31,4,32,pe+27,6,pe+4,33,7,pe+27,34,9,pe+14,pe+27,3,39,36,4,38,37,7,pe+18,pe+19,6,pe+4,pe+17,5,pe+1,40,8,pe+2,pe+3]),t5=g8.from(e5,Z8,tb.conditions,tb.results),r5=new y8({size:50,params:["Endpoint","IsControlPlane","IsOAuthEndpoint","Region","UseDualStack","UseFIPS"]}),n5=(f,h={})=>r5.get(f,()=>S8(t5,{endpointParams:f,logger:h.logger}));w8.aws=$W;class pr extends t8{static shapeId="smithy.ts.sdk.synthetic.com.amazonaws.signin#SigninServiceException";constructor(f){super(f);Object.setPrototypeOf(this,pr.prototype)}}class Yi extends pr{static shapeId="com.amazonaws.signin#AccessDeniedException";name="AccessDeniedException";$fault="client";error;constructor(f){super({name:"AccessDeniedException",$fault:"client",...f});Object.setPrototypeOf(this,Yi.prototype),this.error=f.error}}class Zi extends pr{static shapeId="com.amazonaws.signin#InternalServerException";name="InternalServerException";$fault="server";error;constructor(f){super({name:"InternalServerException",$fault:"server",...f});Object.setPrototypeOf(this,Zi.prototype),this.error=f.error}}class ea extends pr{static shapeId="com.amazonaws.signin#TooManyRequestsError";name="TooManyRequestsError";$fault="client";error;constructor(f){super({name:"TooManyRequestsError",$fault:"client",...f});Object.setPrototypeOf(this,ea.prototype),this.error=f.error}}class ta extends pr{static shapeId="com.amazonaws.signin#ValidationException";name="ValidationException";$fault="client";error;constructor(f){super({name:"ValidationException",$fault:"client",...f});Object.setPrototypeOf(this,ta.prototype),this.error=f.error}}var s5="AccessDeniedException",o5="AccessToken",i5="CreateOAuth2Token",a5="CreateOAuth2TokenRequest",c5="CreateOAuth2TokenRequestBody",u5="CreateOAuth2TokenResponseBody",d5="CreateOAuth2TokenResponse",l5="CreateOAuth2TokenWithIAM",f5="CreateOAuth2TokenWithIAMRequest",h5="CreateOAuth2TokenWithIAMResponse",p5="InternalServerException",m5="OAuthAccessToken",g5="RefreshToken",y5="TooManyRequestsError",S5="ValidationException",rb="accessKeyId",Hd="accessToken",w5="access_token",Gd="client",nb="clientId",sb="codeVerifier",E5="code",hr="error",qd="expiresIn",b5="expires_in",jd="grantType",x5="grant_type",hb="http",Kd="httpError",ob="idToken",We="jsonName",ra="message",_5="resource",Xi="refreshToken",ib="redirectUri",pb="smithy.ts.sdk.synthetic.com.amazonaws.signin",ab="secretAccessKey",cb="sessionToken",T5="server",A5="tokenInput",I5="tokenOutput",Vd="tokenType",C5="token_type",Xe="com.amazonaws.signin",mb=new lb(pb),gb=[-3,pb,"SigninServiceException",0,[],[]];mb.registerError(gb,pr);var Ps=new lb(Xe),yb=[-3,Xe,s5,{[hr]:Gd},[hr,ra],[0,0],2];Ps.registerError(yb,Yi);var Sb=[-3,Xe,p5,{[hr]:T5,[Kd]:500},[hr,ra],[0,0],2];Ps.registerError(Sb,Zi);var wb=[-3,Xe,y5,{[hr]:Gd,[Kd]:429},[hr,ra],[0,0],2];Ps.registerError(wb,ea);var Eb=[-3,Xe,S5,{[hr]:Gd,[Kd]:400},[hr,ra],[0,0],2];Ps.registerError(Eb,ta);var bb=[mb,Ps],R5=[0,Xe,m5,8,0],xb=[0,Xe,g5,8,0],_b=[3,Xe,o5,8,[rb,ab,cb],[[0,{[We]:rb}],[0,{[We]:ab}],[0,{[We]:cb}]],3],Tb=[3,Xe,a5,0,[A5],[[()=>Ab,16]],1],Ab=[3,Xe,c5,0,[nb,jd,E5,ib,sb,Xi],[[0,{[We]:nb}],[0,{[We]:jd}],0,[0,{[We]:ib}],[0,{[We]:sb}],[()=>xb,{[We]:Xi}]],2],Ib=[3,Xe,d5,0,[I5],[[()=>Cb,16]],1],Cb=[3,Xe,u5,0,[Hd,Vd,qd,Xi,ob],[[()=>_b,{[We]:Hd}],[0,{[We]:Vd}],[1,{[We]:qd}],[()=>xb,{[We]:Xi}],[0,{[We]:ob}]],4],Rb=[3,Xe,f5,0,[jd,_5],[[0,{[We]:x5}],0],2],vb=[3,Xe,h5,0,[Hd,Vd,qd],[[()=>R5,{[We]:w5}],[0,{[We]:C5}],[1,{[We]:b5}]],3],kb=[9,Xe,i5,{[hb]:["POST","/v1/token",200]},()=>Tb,()=>Ib],Nb=[9,Xe,l5,{[hb]:["POST","/v1/token?x-amz-client-auth-method=iam",200]},()=>Rb,()=>vb],v5=(f)=>({apiVersion:"2023-01-01",base64Decoder:f?.base64Decoder??$8,base64Encoder:f?.base64Encoder??F8,disableHostPrefix:f?.disableHostPrefix??!1,endpointProvider:f?.endpointProvider??n5,extensions:f?.extensions??[],httpAuthSchemeProvider:f?.httpAuthSchemeProvider??G8,httpAuthSchemes:f?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(h)=>h.getIdentityProvider("aws.auth#sigv4"),signer:new P8},{schemeId:"smithy.api#noAuth",identityProvider:(h)=>h.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new QW}],logger:f?.logger??new r8,protocol:f?.protocol??H8,protocolSettings:f?.protocolSettings??{defaultNamespace:"com.amazonaws.signin",errorTypeRegistries:bb,version:"2023-01-01",serviceTarget:"Signin"},serviceId:f?.serviceId??"Signin",sha256:f?.sha256??q8,urlParser:f?.urlParser??x8,utf8Decoder:f?.utf8Decoder??U8,utf8Encoder:f?.utf8Encoder??D8}),k5=(f)=>{n8(process.version);let h=d8(f),g=()=>h().then(s8),y=v5(f);BW(process.version);let w={profile:f?.profile,logger:y.logger};return{...y,...f,runtime:"node",defaultsMode:h,authSchemePreference:f?.authSchemePreference??Vr(M8,w),bodyLengthChecker:f?.bodyLengthChecker??B8,defaultUserAgentProvider:f?.defaultUserAgentProvider??LW({serviceId:y.serviceId,clientVersion:Y8.version}),maxAttempts:f?.maxAttempts??Vr(R8,f),region:f?.region??Vr(h8,{...p8,...w}),requestHandler:z8.create(f?.requestHandler??g),retryMode:f?.retryMode??Vr({...C8,default:async()=>(await g()).retryMode||I8},f),streamCollector:f?.streamCollector??L8,useDualstackEndpoint:f?.useDualstackEndpoint??Vr(f8,w),useFipsEndpoint:f?.useFipsEndpoint??Vr(l8,w),userAgentAppId:f?.userAgentAppId??Vr(zW,w)}},N5=(f)=>{let{httpAuthSchemes:h,httpAuthSchemeProvider:g,credentials:y}=f;return{setHttpAuthScheme(w){let S=h.findIndex((x)=>x.schemeId===w.schemeId);if(S===-1)h.push(w);else h.splice(S,1,w)},httpAuthSchemes(){return h},setHttpAuthSchemeProvider(w){g=w},httpAuthSchemeProvider(){return g},setCredentials(w){y=w},credentials(){return y}}},O5=(f)=>({httpAuthSchemes:f.httpAuthSchemes(),httpAuthSchemeProvider:f.httpAuthSchemeProvider(),credentials:f.credentials()}),P5=(f,h)=>{let g=Object.assign(HW(f),o8(f),_8(f),N5(f));return h.forEach((y)=>y.configure(g)),Object.assign(f,qW(g),i8(g),T8(g),O5(g))};class Jd extends db{config;constructor(...[f]){let h=k5(f||{});super(h);this.initConfig=h;let g=J8(h),y=jW(g),w=v8(y),S=m8(w),x=VW(S),_=E8(x),A=K8(_),P=P5(A,f?.extensions||[]);this.config=P,this.middlewareStack.use(N8(this.config)),this.middlewareStack.use(WW(this.config)),this.middlewareStack.use(k8(this.config)),this.middlewareStack.use(A8(this.config)),this.middlewareStack.use(GW(this.config)),this.middlewareStack.use(KW(this.config)),this.middlewareStack.use(JW(this.config)),this.middlewareStack.use(XW(this.config,{httpAuthSchemeParametersProvider:j8,identityProviderConfigProvider:async(D)=>new YW({"aws.auth#sigv4":D.credentials})})),this.middlewareStack.use(ZW(this.config))}destroy(){super.destroy()}}var Ob=a8(Q8,"Signin","SigninClient",b8),M5={IsControlPlane:{type:"staticContextParams",value:!1}},D5={IsOAuthEndpoint:{type:"staticContextParams",value:!0}},Pb=(f,h,g,y)=>[];class Qd extends Ob(M5,Pb,"CreateOAuth2Token",kb){}class Xd extends Ob(D5,Pb,"CreateOAuth2TokenWithIAM",Nb){}var U5={CreateOAuth2TokenCommand:Qd,CreateOAuth2TokenWithIAMCommand:Xd};class Yd extends Jd{}c8(U5,Yd);var F5={AUTHCODE_EXPIRED:"AUTHCODE_EXPIRED",CONFLICT:"CONFLICT",INSUFFICIENT_PERMISSIONS:"INSUFFICIENT_PERMISSIONS",INVALID_REQUEST:"INVALID_REQUEST",RESOURCE_NOT_FOUND:"RESOURCE_NOT_FOUND",SERVER_ERROR:"server_error",SERVICE_QUOTA_EXCEEDED:"SERVICE_QUOTA_EXCEEDED",TOKEN_EXPIRED:"TOKEN_EXPIRED",USER_CREDENTIALS_CHANGED:"USER_CREDENTIALS_CHANGED"};$5.AccessDeniedException=Yi;$5.AccessDeniedException$=yb;$5.AccessToken$=_b;$5.CreateOAuth2Token$=kb;$5.CreateOAuth2TokenCommand=Qd;$5.CreateOAuth2TokenRequest$=Tb;$5.CreateOAuth2TokenRequestBody$=Ab;$5.CreateOAuth2TokenResponse$=Ib;$5.CreateOAuth2TokenResponseBody$=Cb;$5.CreateOAuth2TokenWithIAM$=Nb;$5.CreateOAuth2TokenWithIAMCommand=Xd;$5.CreateOAuth2TokenWithIAMRequest$=Rb;$5.CreateOAuth2TokenWithIAMResponse$=vb;$5.InternalServerException=Zi;$5.InternalServerException$=Sb;$5.OAuth2ErrorCode=F5;$5.Signin=Yd;$5.SigninClient=Jd;$5.SigninServiceException=pr;$5.SigninServiceException$=gb;$5.TooManyRequestsError=ea;$5.TooManyRequestsError$=wb;$5.ValidationException=ta;$5.ValidationException$=Eb;$5.errorTypeRegistries=bb});var Ub=i(function(_G){var{setCredentialFeature:fG}=nt(),{CredentialsProviderError:mr,parseKnownFiles:hG,getProfileName:pG}=Ce(),{HttpRequest:mG}=Ne(),{createHash:gG,createPrivateKey:yG,createPublicKey:SG,sign:wG}=c("node:crypto"),{promises:Zd}=c("node:fs"),{homedir:EG}=c("node:os"),{dirname:bG,join:Db}=c("node:path");class na{profileData;init;callerClientConfig;static REFRESH_THRESHOLD=300000;constructor(f,h,g){this.profileData=f,this.init=h,this.callerClientConfig=g}async loadCredentials(){let f=await this.loadToken();if(!f)throw new mr(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`,{tryNextLink:!1,logger:this.logger});let h=f.accessToken,g=Date.now();if(new Date(h.expiresAt).getTime()-g<=na.REFRESH_THRESHOLD)return this.refresh(f);return this.toCredentials(f.accessToken)}get logger(){return this.init?.logger}get loginSession(){return this.profileData.login_session}toCredentials(f){return{accessKeyId:f.accessKeyId,secretAccessKey:f.secretAccessKey,sessionToken:f.sessionToken,accountId:f.accountId,expiration:new Date(f.expiresAt)}}async refresh(f){let h=await this.loadToken().catch(()=>f),g=Date.now(),y=new Date(h.accessToken.expiresAt).getTime(),w=new Date(f.accessToken.expiresAt).getTime(),S=y<=g&&w>g?f:h;if(new Date(S.accessToken.expiresAt).getTime()-Date.now()>na.REFRESH_THRESHOLD)return this.toCredentials(S.accessToken);let{SigninClient:_,CreateOAuth2TokenCommand:A}=Mb(),{logger:P,userAgentAppId:D}=this.callerClientConfig??{},B=((N)=>N?.metadata?.handlerProtocol==="h2")(this.callerClientConfig?.requestHandler)?void 0:this.callerClientConfig?.requestHandler,z=this.profileData.region??await this.callerClientConfig?.region?.()??process.env.AWS_REGION,k=new _({credentials:{accessKeyId:"",secretAccessKey:""},region:z,requestHandler:B,logger:P,userAgentAppId:D,...this.init?.clientConfig});this.createDPoPInterceptor(k.middlewareStack);let R={tokenInput:{clientId:S.clientId,refreshToken:S.refreshToken,grantType:"refresh_token"}};try{let N=await k.send(new A(R)),{accessKeyId:q,secretAccessKey:V,sessionToken:W}=N.tokenOutput?.accessToken??{},{refreshToken:G,expiresIn:K}=N.tokenOutput??{};if(!q||!V||!W||!G)throw new mr("Token refresh response missing required fields",{logger:this.logger,tryNextLink:!1});let J=(K??900)*1000,re=new Date(Date.now()+J),Y={...S,accessToken:{...S.accessToken,accessKeyId:q,secretAccessKey:V,sessionToken:W,expiresAt:re.toISOString()},refreshToken:G};return await this.saveToken(Y),this.toCredentials(Y.accessToken)}catch(N){if(N.name==="AccessDeniedException"){let V=N.error,W;switch(V){case"TOKEN_EXPIRED":W="Your session has expired. Please reauthenticate.";break;case"USER_CREDENTIALS_CHANGED":W="Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.";break;case"INSUFFICIENT_PERMISSIONS":W="Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.";break;default:W=`Failed to refresh token: ${String(N)}. Please re-authenticate using \`aws login\``}throw new mr(W,{logger:this.logger,tryNextLink:!1})}if(new Date(S.accessToken.expiresAt).getTime()>Date.now())return this.logger?.warn?.(`Failed to refresh token: ${String(N)}. Using existing token until expiry.`),this.toCredentials(S.accessToken);throw new mr(`Failed to refresh token: ${String(N)}. Please re-authenticate using aws login`,{logger:this.logger})}}async loadToken(){let f=this.getTokenFilePath();try{let h=await Zd.readFile(f,"utf8"),g=JSON.parse(h),y=["accessToken","clientId","refreshToken","dpopKey"].filter((w)=>!g[w]);if(!g.accessToken?.accountId)y.push("accountId");if(y.length>0)throw new mr(`Token validation failed, missing fields: ${y.join(", ")}`,{logger:this.logger,tryNextLink:!1});return g}catch(h){throw new mr(`Failed to load token from ${f}: ${String(h)}`,{logger:this.logger,tryNextLink:!1})}}async saveToken(f){let h=this.getTokenFilePath(),g=bG(h);try{await Zd.mkdir(g,{recursive:!0})}catch(y){}await Zd.writeFile(h,JSON.stringify(f,null,2),"utf8")}getTokenFilePath(){let f=process.env.AWS_LOGIN_CACHE_DIRECTORY??Db(EG(),".aws","login","cache"),h=Buffer.from(this.loginSession,"utf8"),g=gG("sha256").update(h).digest("hex");return Db(f,`${g}.json`)}derToRawSignature(f){let h=2;if(f[h]!==2)throw Error("Invalid DER signature");h++;let g=f[h++],y=f.subarray(h,h+g);if(h+=g,f[h]!==2)throw Error("Invalid DER signature");h++;let w=f[h++],S=f.subarray(h,h+w);y=y[0]===0?y.subarray(1):y,S=S[0]===0?S.subarray(1):S;let x=Buffer.concat([Buffer.alloc(32-y.length),y]),_=Buffer.concat([Buffer.alloc(32-S.length),S]);return Buffer.concat([x,_])}createDPoPInterceptor(f){f.add((h)=>async(g)=>{if(mG.isInstance(g.request)){let y=g.request,w=`${y.protocol}//${y.hostname}${y.port?`:${y.port}`:""}${y.path}`,S=await this.generateDpop(y.method,w);y.headers={...y.headers,DPoP:S}}return h(g)},{step:"finalizeRequest",name:"dpopInterceptor",override:!0})}async generateDpop(f="POST",h){let g=await this.loadToken();try{let y=yG({key:g.dpopKey,format:"pem",type:"sec1"}),S=SG(y).export({format:"der",type:"spki"}),x=-1;for(let q=0;q<S.length;q++)if(S[q]===4){x=q;break}let _=S.slice(x+1,x+33),A=S.slice(x+33,x+65),P={alg:"ES256",typ:"dpop+jwt",jwk:{kty:"EC",crv:"P-256",x:_.toString("base64url"),y:A.toString("base64url")}},D={jti:crypto.randomUUID(),htm:f,htu:h,iat:Math.floor(Date.now()/1000)},U=Buffer.from(JSON.stringify(P)).toString("base64url"),B=Buffer.from(JSON.stringify(D)).toString("base64url"),z=`${U}.${B}`,k=wG("sha256",Buffer.from(z),y),N=this.derToRawSignature(k).toString("base64url");return`${z}.${N}`}catch(y){throw new mr(`Failed to generate Dpop proof: ${y instanceof Error?y.message:String(y)}`,{logger:this.logger,tryNextLink:!1})}}}var xG=(f)=>async({callerClientConfig:h}={})=>{f?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");let g=await hG(f||{}),y=pG({profile:f?.profile??h?.profile}),w=g[y];if(!w?.login_session)throw new mr(`Profile ${y} does not contain login_session.`,{tryNextLink:!0,logger:f?.logger});let x=await new na(w,f,h).loadCredentials();return fG(x,"CREDENTIALS_LOGIN","AD")};_G.fromLoginCredentials=xG});var tl=i(function(MG){var{externalDataInterceptor:AG,CredentialsProviderError:el,parseKnownFiles:IG,getProfileName:CG}=Ce(),{exec:RG}=c("node:child_process"),{promisify:vG}=c("node:util"),{setCredentialFeature:kG}=nt(),NG=(f,h,g)=>{if(h.Version!==1)throw Error(`Profile ${f} credential_process did not return Version 1.`);if(h.AccessKeyId===void 0||h.SecretAccessKey===void 0)throw Error(`Profile ${f} credential_process returned invalid credentials.`);if(h.Expiration){let S=new Date;if(new Date(h.Expiration)<S)throw Error(`Profile ${f} credential_process returned expired credentials.`)}let y=h.AccountId;if(!y&&g?.[f]?.aws_account_id)y=g[f].aws_account_id;let w={accessKeyId:h.AccessKeyId,secretAccessKey:h.SecretAccessKey,...h.SessionToken&&{sessionToken:h.SessionToken},...h.Expiration&&{expiration:new Date(h.Expiration)},...h.CredentialScope&&{credentialScope:h.CredentialScope},...y&&{accountId:y}};return kG(w,"CREDENTIALS_PROCESS","w"),w},OG=async(f,h,g)=>{let y=h[f];if(h[f]){let w=y.credential_process;if(w!==void 0){let S=vG(AG?.getTokenRecord?.().exec??RG);try{let{stdout:x}=await S(w),_;try{_=JSON.parse(x.trim())}catch{throw Error(`Profile ${f} credential_process returned invalid JSON.`)}return NG(f,_,h)}catch(x){throw new el(x.message,{logger:g})}}else throw new el(`Profile ${f} did not contain credential_process.`,{logger:g})}else throw new el(`Profile ${f} could not be found in shared credentials file.`,{logger:g})},PG=(f={})=>async({callerClientConfig:h}={})=>{f.logger?.debug("@aws-sdk/credential-provider-process - fromProcess");let g=await IG(f);return OG(CG({profile:f.profile??h?.profile}),g,f.logger)};MG.fromProcess=PG});var rl=i(function(zG){var{setCredentialFeature:UG}=nt(),{CredentialsProviderError:FG,externalDataInterceptor:$G}=Ce(),{readFileSync:BG}=c("node:fs"),Fb=(f)=>async(h)=>{f.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken");let{roleArn:g,roleSessionName:y,webIdentityToken:w,providerId:S,policyArns:x,policy:_,durationSeconds:A}=f,{roleAssumerWithWebIdentity:P}=f;if(!P){let{getDefaultRoleAssumerWithWebIdentity:D}=Ld();P=D({...f.clientConfig,credentialProviderLogger:f.logger,parentClientConfig:{...h?.callerClientConfig,...f.parentClientConfig}},f.clientPlugins)}return P({RoleArn:g,RoleSessionName:y??`aws-sdk-js-session-${Date.now()}`,WebIdentityToken:w,ProviderId:S,PolicyArns:x,Policy:_,DurationSeconds:A})},LG=(f={})=>async(h)=>{f.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");let g=f?.webIdentityTokenFile??process.env.AWS_WEB_IDENTITY_TOKEN_FILE,y=f?.roleArn??process.env.AWS_ROLE_ARN,w=f?.roleSessionName??process.env.AWS_ROLE_SESSION_NAME;if(!g||!y)throw new FG("Web identity configuration not specified",{logger:f.logger});let S=await Fb({...f,webIdentityToken:$G?.getTokenRecord?.()[g]??BG(g,{encoding:"ascii"}),roleArn:y,roleSessionName:w})(h);if(g===process.env.AWS_WEB_IDENTITY_TOKEN_FILE)UG(S,"CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN","h");return S};zG.fromTokenFile=LG;zG.fromWebToken=Fb});var qb=i(function(iK){var{CredentialsProviderError:sa,chain:jG,getProfileName:zb,parseKnownFiles:VG}=Ce(),{setCredentialFeature:Gt}=nt(),WG=(f,h,g)=>{let y={EcsContainer:async(w)=>{let{fromHttp:S}=Tu(),{fromContainerMetadata:x}=Ho();return g?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>jG(S(w??{}),x(w))().then(nl)},Ec2InstanceMetadata:async(w)=>{g?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");let{fromInstanceMetadata:S}=Ho();return async()=>S(w)().then(nl)},Environment:async(w)=>{g?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");let{fromEnv:S}=pu();return async()=>S(w)().then(nl)}};if(f in y)return y[f];else throw new sa(`Unsupported credential source in profile ${h}. Got ${f}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:g})},nl=(f)=>Gt(f,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p"),GG=(f,{profile:h="default",logger:g}={})=>Boolean(f)&&typeof f==="object"&&typeof f.role_arn==="string"&&["undefined","string"].indexOf(typeof f.role_session_name)>-1&&["undefined","string"].indexOf(typeof f.external_id)>-1&&["undefined","string"].indexOf(typeof f.mfa_serial)>-1&&(KG(f,{profile:h,logger:g})||JG(f,{profile:h,logger:g})),KG=(f,{profile:h,logger:g})=>{let y=typeof f.source_profile==="string"&&typeof f.credential_source>"u";if(y)g?.debug?.(` ${h} isAssumeRoleWithSourceProfile source_profile=${f.source_profile}`);return y},JG=(f,{profile:h,logger:g})=>{let y=typeof f.credential_source==="string"&&typeof f.source_profile>"u";if(y)g?.debug?.(` ${h} isCredentialSourceProfile credential_source=${f.credential_source}`);return y},QG=async(f,h,g,y,w={},S)=>{g.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");let x=h[f],{source_profile:_,region:A}=x;if(!g.roleAssumer){let{getDefaultRoleAssumer:D}=Ld();g.roleAssumer=D({...g.clientConfig,credentialProviderLogger:g.logger,parentClientConfig:{...y,...g?.parentClientConfig,region:A??g?.parentClientConfig?.region??y?.region}},g.clientPlugins)}if(_&&_ in w)throw new sa(`Detected a cycle attempting to resolve credentials for profile ${zb(g)}. Profiles visited: `+Object.keys(w).join(", "),{logger:g.logger});g.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${_?`source_profile=[${_}]`:`profile=[${f}]`}`);let P=_?S(_,h,g,y,{...w,[_]:!0},$b(h[_]??{})):(await WG(x.credential_source,f,g.logger)(g))();if($b(x))return P.then((D)=>Gt(D,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));else{let D={RoleArn:x.role_arn,RoleSessionName:x.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:x.external_id,DurationSeconds:parseInt(x.duration_seconds||"3600",10)},{mfa_serial:U}=x;if(U){if(!g.mfaCodeProvider)throw new sa(`Profile ${f} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:g.logger,tryNextLink:!1});D.SerialNumber=U,D.TokenCode=await g.mfaCodeProvider(U)}let B=await P;return g.roleAssumer(B,D).then((z)=>Gt(z,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}},$b=(f)=>!f.role_arn&&!!f.credential_source,XG=(f)=>Boolean(f&&f.login_session),YG=async(f,h,g)=>{let{fromLoginCredentials:y}=Ub(),w=await y({...h,profile:f})({callerClientConfig:g});return Gt(w,"CREDENTIALS_PROFILE_LOGIN","AC")},ZG=(f)=>Boolean(f)&&typeof f==="object"&&typeof f.credential_process==="string",eK=async(f,h)=>{let{fromProcess:g}=tl(),y=await g({...f,profile:h})();return Gt(y,"CREDENTIALS_PROFILE_PROCESS","v")},tK=async(f,h,g={},y)=>{let{fromSSO:w}=Rd();return w({profile:f,logger:g.logger,parentClientConfig:g.parentClientConfig,clientConfig:g.clientConfig})({callerClientConfig:y}).then((S)=>{if(h.sso_session)return Gt(S,"CREDENTIALS_PROFILE_SSO","r");else return Gt(S,"CREDENTIALS_PROFILE_SSO_LEGACY","t")})},rK=(f)=>f&&(typeof f.sso_start_url==="string"||typeof f.sso_account_id==="string"||typeof f.sso_session==="string"||typeof f.sso_region==="string"||typeof f.sso_role_name==="string"),Bb=(f)=>Boolean(f)&&typeof f==="object"&&typeof f.aws_access_key_id==="string"&&typeof f.aws_secret_access_key==="string"&&["undefined","string"].indexOf(typeof f.aws_session_token)>-1&&["undefined","string"].indexOf(typeof f.aws_account_id)>-1,Lb=async(f,h)=>{h?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");let g={accessKeyId:f.aws_access_key_id,secretAccessKey:f.aws_secret_access_key,sessionToken:f.aws_session_token,...f.aws_credential_scope&&{credentialScope:f.aws_credential_scope},...f.aws_account_id&&{accountId:f.aws_account_id}};return Gt(g,"CREDENTIALS_PROFILE","n")},nK=(f)=>Boolean(f)&&typeof f==="object"&&typeof f.web_identity_token_file==="string"&&typeof f.role_arn==="string"&&["undefined","string"].indexOf(typeof f.role_session_name)>-1,sK=async(f,h,g)=>{let{fromTokenFile:y}=rl(),w=await y({webIdentityTokenFile:f.web_identity_token_file,roleArn:f.role_arn,roleSessionName:f.role_session_name,roleAssumerWithWebIdentity:h.roleAssumerWithWebIdentity,logger:h.logger,parentClientConfig:h.parentClientConfig})({callerClientConfig:g});return Gt(w,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q")},Hb=async(f,h,g,y,w={},S=!1)=>{let x=h[f];if(Object.keys(w).length>0&&Bb(x))return Lb(x,g);if(S||GG(x,{profile:f,logger:g.logger}))return QG(f,h,g,y,w,Hb);if(Bb(x))return Lb(x,g);if(nK(x))return sK(x,g,y);if(ZG(x))return eK(g,f);if(rK(x))return await tK(f,x,g,y);if(XG(x))return YG(f,g,y);throw new sa(`Could not resolve credentials using profile: [${f}] in configuration/credentials file(s).`,{logger:g.logger})},oK=(f={})=>async({callerClientConfig:h}={})=>{f.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");let g=await VG(f);return Hb(zb({profile:f.profile??h?.profile}),g,f,h)};iK.fromIni=oK});var Wb=i(function(SK){var{ENV_KEY:cK,ENV_SECRET:uK,fromEnv:dK}=pu(),{chain:lK,CredentialsProviderError:oa,ENV_PROFILE:fK}=Ce(),hK=async(f)=>{let{ENV_CMDS_FULL_URI:h,ENV_CMDS_RELATIVE_URI:g,fromContainerMetadata:y,fromInstanceMetadata:w}=Ho();if(process.env[g]||process.env[h]){f.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata");let{fromHttp:S}=Tu();return lK(S(f),y(f))}if(process.env.AWS_EC2_METADATA_DISABLED&&process.env.AWS_EC2_METADATA_DISABLED!=="false")return async()=>{throw new oa("EC2 Instance Metadata Service access disabled",{logger:f.logger})};return f.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"),w(f)};function pK(f,h){let g=mK(f),y,w,S,x,_=async(A)=>{if(A?.forceRefresh){if(!x)x=g(A).then((P)=>{S=P}).finally(()=>{x=void 0});return await x,S}if(S?.expiration){if(S?.expiration?.getTime()<Date.now())S=void 0}if(y)await y;else if(!S||h?.(S))if(S){if(!w)w=g(A).then((P)=>{S=P}).catch(()=>{}).finally(()=>{w=void 0})}else return y=g(A).then((P)=>{S=P}).finally(()=>{y=void 0}),_(A);return S};return _}var mK=(f)=>async(h)=>{let g;for(let y of f)try{return await y(h)}catch(w){if(g=w,w?.tryNextLink)continue;throw w}throw g},jb=!1,gK=(f={})=>pK([async()=>{if(f.profile??process.env[fK]){if(process.env[cK]&&process.env[uK]){if(!jb)(f.logger?.warn&&f.logger?.constructor?.name!=="NoOpLogger"?f.logger.warn.bind(f.logger):console.warn)(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:
61
+ Multiple credential sources detected:
62
+ Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set.
63
+ This SDK will proceed with the AWS_PROFILE value.
64
+
65
+ However, a future version may change this behavior to prefer the ENV static credentials.
66
+ Please ensure that your environment only sets either the AWS_PROFILE or the
67
+ AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair.
68
+ `),jb=!0}throw new oa("AWS_PROFILE is set, skipping fromEnv provider.",{logger:f.logger,tryNextLink:!0})}return f.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"),dK(f)()},async(h)=>{f.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO");let{ssoStartUrl:g,ssoAccountId:y,ssoRegion:w,ssoRoleName:S,ssoSession:x}=f;if(!g&&!y&&!w&&!S&&!x)throw new oa("Skipping SSO provider in default chain (inputs do not include SSO fields).",{logger:f.logger});let{fromSSO:_}=Rd();return _(f)(h)},async(h)=>{f.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni");let{fromIni:g}=qb();return g(f)(h)},async(h)=>{f.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess");let{fromProcess:g}=tl();return g(f)(h)},async(h)=>{f.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile");let{fromTokenFile:g}=rl();return g(f)(h)},async()=>(f.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"),(await hK(f))()),async()=>{throw new oa("Could not load credentials from any providers",{tryNextLink:!1,logger:f.logger})}],Vb),yK=(f)=>f?.expiration!==void 0,Vb=(f)=>f?.expiration!==void 0&&f.expiration.getTime()-Date.now()<300000;SK.credentialsTreatedAsExpired=Vb;SK.credentialsWillNeedRefresh=yK;SK.defaultProvider=gK});var ip=v(Bh(),1),wo=v(Lh(),1);var eN=["stop","stop_sequence","end_turn","length","max_tokens","content-filter","content_filtered","guardrail_intervened","tool-calls","tool_use"],zh={"image/jpeg":"jpeg","image/png":"png","image/gif":"gif","image/webp":"webp"},Hh={"application/pdf":"pdf","text/csv":"csv","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","text/html":"html","text/plain":"txt","text/markdown":"md"},qh={"video/x-matroska":"mkv","video/quicktime":"mov","video/mp4":"mp4","video/webm":"webm","video/x-flv":"flv","video/mpeg":"mpeg","video/mpg":"mpg","video/wmv":"wmv","video/x-ms-wmv":"wmv","video/3gpp":"three_gp"},jh=u(()=>l(t({citations:t({enabled:r()}).optional()}))),Vh=u(()=>l(t({guardContent:r().optional(),guardContentQualifiers:o(s(["grounding_source","query","guard_content"])).optional()}))),Wh=u(()=>l(t({guardContent:r().optional()}))),Gh=t({structuredOutputMode:s(["outputFormat","jsonTool","auto"]).optional(),additionalModelRequestFields:d(e(),L()).optional(),reasoningConfig:t({type:p([a("enabled"),a("disabled"),a("adaptive")]).optional(),budgetTokens:n().optional(),maxReasoningEffort:s(["low","medium","high","xhigh","max"]).optional(),display:s(["omitted","summarized"]).optional()}).optional(),anthropicBeta:o(e()).optional(),serviceTier:s(["reserved","priority","default","flex"]).optional(),requestMetadata:d(e(),e()).optional()});function ap({modelId:f,modelFamily:h,reasoningBudgetTokens:g}){return h==="anthropic"||f.includes("anthropic")||f.includes(":application-inference-profile/")&&g!=null}function Tc(f){return!f.includes("claude-")||tN.test(f)||rN.some((h)=>h.test(f))}function Kh(f){return Tc(f)&&!/claude-(?:sonnet-4-6|haiku-4-5)(?=[-.:]|$)/.test(f)}var tN=/claude-(?:instant|v?2|3)(?=[-.:]|$)/,rN=[/claude-(?:opus|sonnet)-4(?:-\d{8})?(?:-v\d+)?(?=[:.]|$)/,/claude-opus-4-(?:1|5|6)(?=[-.:]|$)/,/claude-sonnet-4-(?:5|6)(?=[-.:]|$)/,/claude-haiku-4-5(?=[-.:]|$)/],cp=u(()=>l(t({message:e(),type:e().nullish()}))),Eo=oe({errorSchema:cp,errorToMessage:(f)=>f.type==null?f.message:`${f.type}: ${f.message}`});function nN(f,h){let g=new ip.EventStreamCodec(wo.toUtf8,wo.fromUtf8),y=new Uint8Array(0),w=new TextDecoder;return f.pipeThrough(new TransformStream({async transform(S,x){let _=new Uint8Array(y.length+S.length);_.set(y),_.set(S,y.length),y=_;while(y.length>=4){let A=new DataView(y.buffer,y.byteOffset,y.byteLength).getUint32(0,!1);if(y.length<A)break;let P=y.subarray(0,A),D=g.decode(P);y=y.slice(A);let U=D.headers[":message-type"]?.value,B=D.headers[":event-type"]?.value,z=D.headers[":exception-type"]?.value;await h({messageType:U,eventType:B,exceptionType:z,data:w.decode(D.body)},x)}},flush(){if(y.length>0)throw Error(`Incomplete Amazon Bedrock event-stream frame: ${y.length} buffered bytes remain at end of stream.`)}}))}var sN=(f)=>async({response:h})=>{let g=yi(h);if(h.body==null)throw new Ns({});return{responseHeaders:g,value:nN(h.body,async(y,w)=>{let S=y.messageType==="event"?y.eventType:y.messageType==="exception"?y.exceptionType:void 0;if(S==null)return;let x=await yt({text:y.data});if(!x.success){w.enqueue(x);return}delete x.value.p;let _={[S]:x.value},A=await De({value:_,schema:f});if(!A.success)w.enqueue(A);else w.enqueue({success:!0,value:A.value,rawValue:_})})}};function oN(f){switch(f){case"internalServerException":case"InternalServerException":return{statusCode:500,isRetryable:!0};case"modelStreamErrorException":case"ModelStreamErrorException":return{statusCode:424,isRetryable:!0};case"serviceUnavailableException":case"ServiceUnavailableException":return{statusCode:503,isRetryable:!0};case"throttlingException":case"ThrottlingException":return{statusCode:429,isRetryable:!0};case"validationException":case"ValidationException":return{statusCode:400,isRetryable:!1};default:return{}}}async function iN({tools:f,toolChoice:h,modelId:g,modelFamily:y,reasoningBudgetTokens:w,disableParallelToolUse:S,rejectsForcedToolUse:x=!1}){let _=[],A=new Set;if(f==null||f.length===0)return{toolConfig:{},additionalTools:void 0,betas:A,toolWarnings:_};let P=f.filter((J)=>{if(J.type==="provider"&&(J.id==="anthropic.web_search_20250305"||J.id==="anthropic.web_search_20260318"||J.id==="anthropic.web_fetch_20260318"))return _.push({type:"unsupported",feature:`${J.id.slice(10)} tool`,details:`The ${J.id.slice(10)} tool is not supported on Amazon Bedrock.`}),!1;return!0});if(P.length===0)return{toolConfig:{},additionalTools:void 0,betas:A,toolWarnings:_};let D=ap({modelId:g,modelFamily:y,reasoningBudgetTokens:w}),U=P.filter((J)=>J.type==="provider"),B=P.filter((J)=>J.type==="function"),z=D&&x&&(h?.type==="required"||h?.type==="tool"),k=z&&h.type==="tool"?U.filter((J)=>J.name===h.toolName):U,R=void 0,N=[],q=D&&k.length>0;if(q){let{toolChoice:J,toolWarnings:re,betas:Y}=await wy({tools:U,toolChoice:h,disableParallelToolUse:S,supportsStructuredOutput:!1,supportsStrictTools:!1,rejectsForcedToolUse:x});if(_.push(...re),Y.forEach((X)=>A.add(X)),J)R={tool_choice:J};for(let X of k){let ie=Object.values(Oi).find((ye)=>ye({}).id===X.id);if(ie!=null){let ye=ie({});N.push({toolSpec:{name:X.name,inputSchema:{json:await Ur(ye.inputSchema).jsonSchema}}})}else _.push({type:"unsupported",feature:`tool ${X.id}`})}}else for(let J of k)_.push({type:"unsupported",feature:`tool ${J.id}`});let V=h;if(!q&&z){if(h.type==="tool")_.push({type:"unsupported",feature:"toolChoice",details:`toolChoice 'tool' is not supported by this model because it rejects forced tool use. Only the '${h.toolName}' tool is sent with 'auto' tool choice. Instruct the model to use the tool in the prompt and verify that a tool call was made.`});else _.push({type:"unsupported",feature:"toolChoice",details:"toolChoice 'required' is not supported by this model because it rejects forced tool use. Using 'auto' instead. Instruct the model to use a tool in the prompt and verify that a tool call was made."});V={type:"auto"}}let W=h?.type==="tool"?B.filter((J)=>J.name===h.toolName):B,G=Tc(g);for(let J of W){let re=G&&(J.strict!==!0||xr(J.inputSchema));if(!G&&J.strict===!0)_.push({type:"unsupported",feature:"strict",details:`Tool '${J.name}' has strict: ${J.strict}, but strict mode is not supported by this model on Amazon Bedrock. The strict property will be ignored.`});else if(J.strict===!0&&!re)_.push({type:"unsupported",feature:"strict",details:`Tool '${J.name}' has strict: true, but Amazon Bedrock requires every object in a strict tool schema to set additionalProperties: false. The strict property will be ignored.`});N.push({toolSpec:{name:J.name,...J.description?.trim()!==""?{description:J.description}:{},...J.strict!=null&&re?{strict:J.strict}:{},inputSchema:{json:J.inputSchema}}})}if(D&&!q&&S&&N.length>0&&V?.type!=="none")R={tool_choice:V?.type==="required"?{type:"any",disable_parallel_tool_use:!0}:V?.type==="tool"?{type:"tool",name:V.toolName,disable_parallel_tool_use:!0}:{type:"auto",disable_parallel_tool_use:!0}};let K=void 0;if(!q&&R?.tool_choice==null&&N.length>0&&V){let J=V.type;switch(J){case"auto":K={auto:{}};break;case"required":K={any:{}};break;case"none":N.length=0,K=void 0;break;case"tool":K={tool:{name:V.toolName}};break;default:throw new b({functionality:`tool choice type: ${J}`})}}return{toolConfig:N.length>0?{tools:N,toolChoice:K}:{},additionalTools:R,betas:A,toolWarnings:_}}function xr(f){if(typeof f==="boolean")return!0;let h=f;if((f.type==="object"||Array.isArray(f.type)&&f.type.includes("object"))&&f.additionalProperties!==!1)return!1;let g=[f.properties,f.patternProperties,f.definitions,h.$defs];for(let y of g)if(y!=null&&Object.values(y).some((w)=>!xr(w)))return!1;if(f.dependencies!=null&&Object.values(f.dependencies).some((y)=>!Array.isArray(y)&&!xr(y)))return!1;if([f.propertyNames,f.contains,f.not,f.if,f.then,f.else].some((y)=>y!=null&&!xr(y)))return!1;if(f.items!=null&&(Array.isArray(f.items)?f.items.some((y)=>!xr(y)):!xr(f.items)))return!1;return[f.anyOf,f.allOf,f.oneOf].every((y)=>y==null||y.every(xr))}function Jh(f){if(f==null)return At();let{inputTokens:h,outputTokens:g}=f,y=f.cacheReadInputTokens??0,w=f.cacheWriteInputTokens??0;return{inputTokens:{total:h+y+w,noCache:h,cacheRead:y,cacheWrite:w},outputTokens:{total:g,text:g,reasoning:void 0},raw:f}}var Qh=u(()=>l(t({signature:e().optional(),redactedData:e().optional(),redactedContent:e().optional()})));function Sc(f){return f.includes("mistral.")}function Zn(f,h){if(!h)return f;if(/^[a-zA-Z0-9]{9}$/.test(f))return f;return fN(f)}var aN="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",wc=BigInt(62),up=9,cN=wc**BigInt(up),uN=BigInt("14695981039346656037"),dN=BigInt("1099511628211"),lN=BigInt("18446744073709551615");function fN(f){let h=uN;for(let w=0;w<f.length;w++)h^=BigInt(f.charCodeAt(w)),h=h*dN&lN;let g=h%cN,y="";for(let w=0;w<up;w++)y=aN[Number(g%wc)]+y,g/=wc;return y}function dp(f){let h=f?.amazonBedrock?.cachePoint??f?.bedrock?.cachePoint;if(!h)return;return{cachePoint:h}}function Yn(f,h){let g=dp(h);if(g)f.push(g)}function hN(f){return f.replace(/[^a-zA-Z0-9_-]/g,"")||"_"}function pN(f){return jw(f).replace(/\s+/g," ").replace(/[^a-zA-Z0-9 ()[\]-]/g,"").trim().slice(0,200).trim()}function on({data:f,functionality:h}){switch(f.type){case"data":return{bytes:j(f.data)};case"url":if(f.url.protocol!=="s3:")throw new b({functionality:h});return{s3Location:{uri:f.url.toString()}}}}async function Ec(f){return(await T({provider:"amazonBedrock",providerOptions:f,schema:jh})??await T({provider:"bedrock",providerOptions:f,schema:jh}))?.citations?.enabled??!1}async function mN(f){return await T({provider:"amazonBedrock",providerOptions:f,schema:Vh})??await T({provider:"bedrock",providerOptions:f,schema:Vh})}async function gN(f){return await T({provider:"amazonBedrock",providerOptions:f,schema:Wh})??await T({provider:"bedrock",providerOptions:f,schema:Wh})}async function yN(f,h=!1){let g=EN(f),y=[],w=[],S=0,x=()=>`document-${++S}`,_=new Set,A=(P)=>{let D=P&&pN(P)||x(),U=D;for(let B=2;_.has(U);B++){let z=` (${B})`;U=`${D.slice(0,200-z.length).trim()}${z}`}return _.add(U),U};for(let P=0;P<g.length;P++){let D=g[P],U=P===g.length-1,B=D.type;switch(B){case"system":if(w.length>0)throw new b({functionality:"Multiple system messages that are separated by user/assistant messages"});for(let z of D.messages){y.push({text:z.content});let k=dp(z.providerOptions);if(k)y.push(k)}break;case"user":{let z=[];for(let k of D.messages){let{role:R,content:N,providerOptions:q}=k;switch(R){case"user":for(let V=0;V<N.length;V++){let W=N[V];switch(W.type){case"text":{let G=await mN(W.providerOptions);if(G?.guardContent)z.push({guardContent:{text:{text:W.text,qualifiers:G.guardContentQualifiers}}});else z.push({text:W.text});break}case"file":switch(W.data.type){case"reference":throw new b({functionality:"file parts with provider references"});case"url":{if(W.data.url.protocol!=="s3:")throw new b({functionality:"File URL data"});let G=ee({part:W});switch(fe(G)){case"image":z.push({image:{format:bc(G),source:on({data:W.data,functionality:"File URL data"})}});break;case"video":z.push({video:{format:_c(G),source:on({data:W.data,functionality:"File URL data"})}});break;default:throw new b({functionality:"File URL data"})}break}case"text":{let G=Ae(W.mediaType)?W.mediaType:"text/plain",K=await Ec(W.providerOptions);z.push({document:{format:xc(G),name:A(W.filename),source:{bytes:j(new TextEncoder().encode(W.data.text))},...K&&{citations:{enabled:!0}}}});break}case"data":{let G=ee({part:W});switch(fe(G)){case"image":{let K=await gN(W.providerOptions),J={image:{format:bc(G),source:on({data:W.data,functionality:"File URL data"})}};if(K?.guardContent)z.push({guardContent:J});else z.push(J);break}case"video":z.push({video:{format:_c(G),source:on({data:W.data,functionality:"File URL data"})}});break;default:{let K=await Ec(W.providerOptions);z.push({document:{format:xc(G),name:A(W.filename),source:{bytes:j(W.data.data)},...K&&{citations:{enabled:!0}}}})}}break}}}Yn(z,W.providerOptions)}break;case"tool":for(let V of N){if(V.type==="tool-approval-response")continue;z.push({toolResult:{toolUseId:Zn(V.toolCallId,h),content:await Yh({output:V.output,getDocumentName:A})}}),Yn(z,V.providerOptions)}break;default:throw Error(`Unsupported role: ${R}`)}Yn(z,q)}Xh(w,z);break}case"assistant":{let z=[],k=[],R=()=>{if(z.some((q)=>!("cachePoint"in q)))w.push({role:"assistant",content:z});z=[]},N=()=>{if(k.length>0)Xh(w,k),k=[]};for(let q=0;q<D.messages.length;q++){let V=D.messages[q],W=q===D.messages.length-1,{content:G}=V,K=G.some((J)=>J.type==="reasoning");for(let J=0;J<G.length;J++){let re=G[J],Y=J===G.length-1;if(re.type!=="tool-result")N();switch(re.type){case"text":if(!re.text.trim()&&!K)break;z.push({text:wN(U,W,Y,re.text)});break;case"reasoning":{let X=await T({provider:"amazonBedrock",providerOptions:re.providerOptions,schema:Qh})??await T({provider:"bedrock",providerOptions:re.providerOptions,schema:Qh});if(X?.signature!=null)z.push({reasoningContent:{reasoningText:{text:re.text,signature:X.signature}}});else if(X?.redactedContent!=null)z.push({reasoningContent:{redactedContent:X.redactedContent}});else if(X?.redactedData!=null)z.push({reasoningContent:{redactedReasoning:{data:X.redactedData}}});break}case"tool-call":z.push({toolUse:{toolUseId:Zn(re.toolCallId,h),name:hN(re.toolName),input:SN(re.input)}});break;case"tool-result":R(),k.push({toolResult:{toolUseId:Zn(re.toolCallId,h),content:await Yh({output:re.output,getDocumentName:A})}})}Yn(re.type==="tool-result"?k:z,re.providerOptions)}Yn(G[G.length-1]?.type==="tool-result"?k:z,V.providerOptions)}N(),R();break}default:throw Error(`Unsupported type: ${B}`)}}return{system:y,messages:w}}function Xh(f,h){let g=f[f.length-1];if(g?.role==="user"&&g.content.some((y)=>("toolResult"in y)))g.content.push(...h);else f.push({role:"user",content:h})}async function Yh({output:f,getDocumentName:h}){switch(f.type){case"content":return Promise.all(f.value.map(async(g)=>{switch(g.type){case"text":return{text:g.text};case"file":{if(g.data.type!=="data"&&(g.data.type!=="url"||g.data.url.protocol!=="s3:"))throw new b({functionality:`tool result file data of type "${g.data.type}"`});let y=ee({part:g});switch(fe(y)){case"image":return{image:{format:bc(y),source:on({data:g.data,functionality:`tool result file data of type "${g.data.type}"`})}};case"video":return{video:{format:_c(y),source:on({data:g.data,functionality:`tool result file data of type "${g.data.type}"`})}};default:{if(g.data.type!=="data")throw new b({functionality:`tool result file data of type "${g.data.type}"`});let w=await Ec(g.providerOptions);return{document:{format:xc(y),name:h(g.filename),source:{bytes:j(g.data.data)},...w&&{citations:{enabled:!0}}}}}}}default:throw new b({functionality:`unsupported tool content part type: ${g.type}`})}}));case"text":case"error-text":return[{text:f.value}];case"execution-denied":return[{text:f.reason??"Tool call execution denied."}];default:return[{text:JSON.stringify(f.value)}]}}function SN(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)?f:{rawInvalidInput:f}}function bc(f){let h=zh[f];if(!h)throw new b({functionality:`image mime type: ${f}`,message:`Unsupported image mime type: ${f}, expected one of: ${Object.keys(zh).join(", ")}`});return h}function xc(f){let h=Hh[f];if(!h)throw new b({functionality:`file mime type: ${f}`,message:`Unsupported file mime type: ${f}, expected one of: ${Object.keys(Hh).join(", ")}`});return h}function _c(f){let h=qh[f];if(!h)throw new b({functionality:`video mime type: ${f}`,message:`Unsupported video mime type: ${f}, expected one of: ${Object.keys(qh).join(", ")}`});return h}function wN(f,h,g,y){return f&&h&&g?y.trim():y}function EN(f){let h=[],g=void 0;for(let y of f){let{role:w}=y;switch(w){case"system":if(g?.type!=="system")g={type:"system",messages:[]},h.push(g);g.messages.push(y);break;case"assistant":if(g?.type!=="assistant")g={type:"assistant",messages:[]},h.push(g);g.messages.push(y);break;case"user":if(g?.type!=="user")g={type:"user",messages:[]},h.push(g);g.messages.push(y);break;case"tool":if(g?.type!=="user")g={type:"user",messages:[]},h.push(g);g.messages.push(y);break;default:throw Error(`Unsupported role: ${w}`)}}return h}function Zh(f,h){switch(f){case"stop_sequence":case"end_turn":return"stop";case"max_tokens":return"length";case"content_filtered":case"guardrail_intervened":return"content-filter";case"tool_use":return h?"stop":"tool-calls";default:return"other"}}var bN=u(()=>l(t({disableParallelToolUse:r().optional(),structuredOutputMode:s(["outputFormat","jsonTool","auto"]).optional()})));function xN({type:f,error:h,data:g}){let y=typeof h.message==="string"?h.message:`Amazon Bedrock stream failed with ${f}`;return Kt({message:y,type:f,...oN(f),data:g})}var _N=class f{static[H](h){return te({modelId:h.modelId,config:h.config})}static[Q](h){return new f(h.modelId,h.config)}constructor(h,g){this.modelId=h,this.config=g,this.specificationVersion="v4",this.provider="amazon-bedrock",this.supportedUrls={"image/*":[/^s3:\/\//],"video/*":[/^s3:\/\//]}}async getArgs({prompt:h,maxOutputTokens:g,temperature:y,topP:w,topK:S,frequencyPenalty:x,presencePenalty:_,stopSequences:A,responseFormat:P,seed:D,tools:U,toolChoice:B,reasoning:z,providerOptions:k}){let R=await T({provider:"amazonBedrock",providerOptions:k,schema:Gh})??await T({provider:"bedrock",providerOptions:k,schema:Gh})??{},N=await T({provider:"anthropic",providerOptions:k,schema:bN}),q=[],{supportsStructuredOutput:V,rejectsSamplingParameters:W,rejectsForcedToolUse:G,rejectsThinkingDisabled:K,rejectsThinkingDisabledAboveHighEffort:J,supportsBetweenToolsThinking:re,isKnownModel:Y}=Hm(this.modelId);if(x!=null)q.push({type:"unsupported",feature:"frequencyPenalty"});if(_!=null)q.push({type:"unsupported",feature:"presencePenalty"});if(D!=null)q.push({type:"unsupported",feature:"seed"});if(W){if(y!=null)q.push({type:"unsupported",feature:"temperature",details:`temperature is not supported by ${this.modelId} and will be ignored`}),y=void 0;if(S!=null)q.push({type:"unsupported",feature:"topK",details:`topK is not supported by ${this.modelId} and will be ignored`}),S=void 0;if(w!=null)q.push({type:"unsupported",feature:"topP",details:`topP is not supported by ${this.modelId} and will be ignored`}),w=void 0}let X=/^(?:[^.]+\.)?(openai\..+)$/.exec(this.modelId)?.[1],ie=X!=null,ye=X?.startsWith("openai.gpt-oss-")??!1,ve=mp(this.modelId),Te=!ie||ye;if(Te&&y!=null&&y>1)q.push({type:"unsupported",feature:"temperature",details:`${y} exceeds bedrock maximum of 1.0. clamped to 1.0`}),y=1;else if(Te&&y!=null&&y<0)q.push({type:"unsupported",feature:"temperature",details:`${y} is below bedrock minimum of 0. clamped to 0`}),y=0;if(P!=null&&P.type!=="text"&&P.type!=="json")q.push({type:"unsupported",feature:"responseFormat",details:"Only text and json response formats are supported."});let se=ap({modelId:this.modelId,modelFamily:this.config.modelFamily,reasoningBudgetTokens:R.reasoningConfig?.budgetTokens}),le=R.reasoningConfig?.type==="disabled",ft=R.reasoningConfig?.maxReasoningEffort;R=NN({reasoning:z,amazonBedrockOptions:R,warnings:q,isAnthropicModel:se,isOpenAIModel:ie,modelId:this.modelId});let we=R.reasoningConfig?.type,tt=R.reasoningConfig?.maxReasoningEffort;if(se&&we==="disabled"){if(/claude-(?:instant|v?2|3-(?:5-)?(?:haiku|sonnet|opus))(?=[-.:]|$)/.test(this.modelId))we=void 0;else if(K){if(we=re?"between_tools":"adaptive",!le&&we==="adaptive"){if(tt??=ft,tt==null&&R.additionalModelRequestFields?.output_config?.effort==null)tt="low"}q.push({type:le?"unsupported":"compatibility",feature:le?"providerOptions.amazonBedrock.reasoningConfig":"reasoning",details:`thinking cannot be disabled for ${this.modelId}. Using '${we}' thinking instead.`})}let Se=tt??R.additionalModelRequestFields?.output_config?.effort;if((we==="disabled"&&J||we==="between_tools")&&(Se==="xhigh"||Se==="max"))q.push({type:"unsupported",feature:tt!=null?"providerOptions.amazonBedrock.reasoningConfig.maxReasoningEffort":"providerOptions.amazonBedrock.additionalModelRequestFields.output_config.effort",details:`effort '${Se}' is not supported by ${this.modelId} with '${we}' thinking. The effort has been lowered to 'high'.`}),tt="high"}let sl=we==="enabled"||we==="adaptive"||we==="between_tools",Nn=R.structuredOutputMode??N?.structuredOutputMode??"auto";if(Nn==="jsonTool"){let Se={...R.additionalModelRequestFields},Be=Se.output_config;if(Be!=null&&typeof Be==="object"&&!Array.isArray(Be)){let da={...Be};if(delete da.format,Object.keys(da).length>0)Se.output_config=da;else delete Se.output_config;R={...R,additionalModelRequestFields:Se}}}let Gb=Kh(this.modelId)&&(V||sl||this.config.modelFamily==="anthropic"),ia=se&&P?.type==="json"&&P.schema!=null&&(Nn==="outputFormat"||Nn==="auto"&&Gb),aa=!ia&&se&&P?.type==="json"&&P.schema!=null&&(G||this.modelId.includes("claude-")&&(!Y||!V)&&!Kh(this.modelId)&&Nn!=="jsonTool"||Nn!=="jsonTool"&&!Tc(this.modelId)&&U!=null&&U.length>0),Ms=P?.type==="json"&&P.schema!=null&&!ia&&!aa?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:P.schema}:void 0,{toolConfig:Ds,additionalTools:ca,toolWarnings:Kb,betas:Us}=await iN({tools:Ms?[...U??[],Ms]:U,toolChoice:Ms!=null?{type:"required"}:B,modelId:this.modelId,modelFamily:this.config.modelFamily,reasoningBudgetTokens:R.reasoningConfig?.budgetTokens,disableParallelToolUse:N?.disableParallelToolUse,rejectsForcedToolUse:G});if(q.push(...Kb),ca)R.additionalModelRequestFields={...R.additionalModelRequestFields,...ca};if(Us.size>0||R.anthropicBeta){let Se=R.anthropicBeta??[],Be=Us.size>0?[...Se,...Array.from(Us)]:Se;R.additionalModelRequestFields={...R.additionalModelRequestFields,anthropic_beta:Be}}let Wr=we==="enabled"?R.reasoningConfig?.budgetTokens:void 0,ol=we==="adaptive"?R.reasoningConfig?.display:void 0,ua=se&&sl,Ze={...g!=null&&{maxTokens:g},...y!=null&&{temperature:y},...w!=null&&{topP:w},...S!=null&&{topK:S},...A!=null&&{stopSequences:A}};if(se){if(Wr!=null){if(Ze.maxTokens!=null)Ze.maxTokens+=Wr;else Ze.maxTokens=Wr+4096;R.additionalModelRequestFields={...R.additionalModelRequestFields,thinking:{type:"enabled",budget_tokens:Wr}}}else if(we==="adaptive")R.additionalModelRequestFields={...R.additionalModelRequestFields,thinking:{type:"adaptive",...ol!=null&&{display:ol}}};else if(we==="disabled"||we==="between_tools")R.additionalModelRequestFields={...R.additionalModelRequestFields,thinking:{type:we}}}else{if(R.reasoningConfig?.budgetTokens!=null)q.push({type:"unsupported",feature:"budgetTokens",details:"budgetTokens applies only to Anthropic models on Bedrock and will be ignored for this model."});if(we==="adaptive")q.push({type:"unsupported",feature:"adaptive thinking",details:"adaptive thinking type applies only to Anthropic models on Bedrock."})}if(tt!=null)if(se)R.additionalModelRequestFields={...R.additionalModelRequestFields,output_config:{...R.additionalModelRequestFields?.output_config,effort:tt}};else if(ie)R.additionalModelRequestFields=ye?{...R.additionalModelRequestFields,reasoning_effort:tt}:{...R.additionalModelRequestFields,reasoning:{...R.additionalModelRequestFields?.reasoning,effort:tt}};else R.additionalModelRequestFields={...R.additionalModelRequestFields,reasoningConfig:{...we!=null&&we!=="adaptive"&&{type:we},...Wr!=null&&{budgetTokens:Wr},maxReasoningEffort:tt}};if(ve&&we==="enabled"&&(tt==="high"||tt==="xhigh"||tt==="max")&&Ze.maxTokens!=null)delete Ze.maxTokens,q.push({type:"unsupported",feature:"maxOutputTokens",details:`maxOutputTokens is not supported by ${this.modelId} when high reasoning is enabled and will be ignored`});if(ia)R.additionalModelRequestFields={...R.additionalModelRequestFields,output_config:{...R.additionalModelRequestFields?.output_config,format:{type:"json_schema",schema:Ty(P.schema)}}};if(ua&&Ze.temperature!=null)delete Ze.temperature,q.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"});if(ua&&Ze.topP!=null)delete Ze.topP,q.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"});if(ua&&Ze.topK!=null)delete Ze.topK,q.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"});if(ie){let Se=ye?["stopSequences"]:["temperature","topP","stopSequences"];for(let Be of Se)if(Ze[Be]!=null)delete Ze[Be],q.push({type:"unsupported",feature:Be,details:`${Be} is not supported by this OpenAI model on the Converse API`})}let Jb=(Ds.tools?.length??0)>0||ca,Fs=h;if(!Jb){if(h.some((Se)=>("content"in Se)&&Array.isArray(Se.content)&&Se.content.some((Be)=>Be.type==="tool-call"||Be.type==="tool-result")))Fs=h.map((Se)=>Se.role==="system"?Se:{...Se,content:Se.content.filter((Be)=>Be.type!=="tool-call"&&Be.type!=="tool-result")}).filter((Se)=>Se.role==="system"||Se.content.length>0),q.push({type:"unsupported",feature:"toolContent",details:"Tool calls and results removed from conversation because Bedrock does not support tool content without active tools."})}if(aa)Fs=kl({messages:Fs,schema:P.schema,schemaSuffix:"You MUST answer with only a JSON object that matches the JSON schema above. Do not wrap it in markdown fences or include any other text."});let Qb=Sc(this.modelId),{system:Xb,messages:Yb}=await yN(Fs,Qb),{reasoningConfig:_K,additionalModelRequestFields:TK,serviceTier:AK,structuredOutputMode:IK,requestMetadata:CK,...Zb}=k?.amazonBedrock??k?.bedrock??{},il=R.requestMetadata,al=se?["/delta/stop_sequence"]:void 0;return{command:{system:Xb,messages:Yb,additionalModelRequestFields:R.additionalModelRequestFields,...al&&{additionalModelResponseFieldPaths:al},...Object.keys(Ze).length>0&&{inferenceConfig:Ze},...R.serviceTier!=null&&{serviceTier:{type:R.serviceTier}},...il!=null&&{requestMetadata:il},...Zb,...Ds.tools!==void 0&&Ds.tools.length>0?{toolConfig:Ds}:{}},warnings:q,usesJsonInstruction:aa,usesJsonResponseTool:Ms!=null,betas:Us}}async getHeaders({headers:h}){return I(this.config.headers?await M(this.config.headers):void 0,h)}async doGenerate(h){let{command:g,warnings:y,usesJsonInstruction:w,usesJsonResponseTool:S}=await this.getArgs(h),x=`${this.getUrl(this.modelId)}/converse`,{value:_,responseHeaders:A}=await O({url:x,headers:await this.getHeaders({headers:h.headers}),body:g,failedResponseHandler:oe({errorSchema:cp,errorToMessage:(R)=>`${R.message??"Unknown error"}`}),successfulResponseHandler:E(IN),abortSignal:h.abortSignal,fetch:this.config.fetch}),P=[],D=!1,U=w?new ep:void 0;for(let R of _.output.message.content){let N=R.text!=null?[R.text]:R.citationsContent?.content?.flatMap((q)=>q.text==null?[]:[q.text])??[];for(let q of N)P.push({type:"text",text:U?.process(q)??q});if(R.reasoningContent){if("reasoningText"in R.reasoningContent){let q={type:"reasoning",text:R.reasoningContent.reasoningText.text};if(R.reasoningContent.reasoningText.signature){let V={signature:R.reasoningContent.reasoningText.signature};q.providerMetadata={amazonBedrock:V,bedrock:V}}P.push(q)}else if("redactedReasoning"in R.reasoningContent){let q={redactedData:R.reasoningContent.redactedReasoning.data??""};P.push({type:"reasoning",text:"",providerMetadata:{amazonBedrock:q,bedrock:q}})}else if("redactedContent"in R.reasoningContent){let q={redactedContent:R.reasoningContent.redactedContent};P.push({type:"reasoning",text:"",providerMetadata:{amazonBedrock:q,bedrock:q}})}}if(R.toolUse)if(S&&R.toolUse.name==="json")D=!0,P.push({type:"text",text:JSON.stringify(R.toolUse.input)});else{let q=Sc(this.modelId),V=R.toolUse?.toolUseId||this.config.generateId();P.push({type:"tool-call",toolCallId:Zn(V,q),toolName:R.toolUse?.name??`tool-${this.config.generateId()}`,input:JSON.stringify(R.toolUse?.input??{})})}}let B=_.additionalModelResponseFields?.delta?.stop_sequence??null,z=_.trace||_.usage||_.performanceConfig||_.serviceTier||D||B?{..._.trace&&typeof _.trace==="object"?{trace:_.trace}:{},..._.performanceConfig&&{performanceConfig:_.performanceConfig},..._.serviceTier&&{serviceTier:_.serviceTier},...(_.usage?.cacheWriteInputTokens!=null||_.usage?.cacheDetails!=null)&&{usage:{..._.usage.cacheWriteInputTokens!=null&&{cacheWriteInputTokens:_.usage.cacheWriteInputTokens},..._.usage.cacheDetails!=null&&{cacheDetails:_.usage.cacheDetails}}},...D&&{isJsonResponseFromTool:!0},stopSequence:B}:void 0,k=z?{amazonBedrock:z,bedrock:z}:void 0;return{content:P,finishReason:{unified:Zh(_.stopReason,D),raw:_.stopReason??void 0},usage:Jh(_.usage),response:{id:A?.["x-amzn-requestid"]??void 0,timestamp:A?.date!=null?new Date(A.date):void 0,modelId:this.modelId,headers:A},warnings:y,request:{body:g},...k&&{providerMetadata:k}}}async doStream(h){let{command:g,warnings:y,usesJsonInstruction:w,usesJsonResponseTool:S}=await this.getArgs(h),x=this.modelId,_=Sc(x),A=`${this.getUrl(x)}/converse-stream`,{value:P,responseHeaders:D}=await O({url:A,headers:await this.getHeaders({headers:h.headers}),body:g,failedResponseHandler:Eo,successfulResponseHandler:sN(CN),abortSignal:h.abortSignal,fetch:this.config.fetch}),U={unified:"interrupted",raw:void 0},B=void 0,z=void 0,k=!1,R=null,N=w?new ep:void 0,q={};return{stream:P.pipeThrough(new TransformStream({start(V){V.enqueue({type:"stream-start",warnings:y}),V.enqueue({type:"response-metadata",id:D?.["x-amzn-requestid"]??void 0,timestamp:D?.date!=null?new Date(D.date):void 0,modelId:x})},transform(V,W){function G(Y,X){U={unified:"error",raw:void 0},W.enqueue({type:"error",error:xN({type:Y,error:X,data:V.rawValue})})}if(h.includeRawChunks)W.enqueue({type:"raw",rawValue:V.rawValue});if(!V.success){U={unified:"error",raw:void 0},W.enqueue({type:"error",error:V.error});return}let K=V.value;if(K.internalServerException){G("internalServerException",K.internalServerException);return}if(K.modelStreamErrorException){G("modelStreamErrorException",K.modelStreamErrorException);return}if(K.serviceUnavailableException){G("serviceUnavailableException",K.serviceUnavailableException);return}if(K.throttlingException){G("throttlingException",K.throttlingException);return}if(K.validationException){G("validationException",K.validationException);return}if(K.messageStop)U={unified:Zh(K.messageStop.stopReason,k),raw:K.messageStop.stopReason??void 0},R=K.messageStop.additionalModelResponseFields?.delta?.stop_sequence??null;if(K.metadata){if(K.metadata.usage)B=K.metadata.usage;let Y=K.metadata.usage?.cacheWriteInputTokens!=null||K.metadata.usage?.cacheDetails!=null?{usage:{...K.metadata.usage?.cacheWriteInputTokens!=null&&{cacheWriteInputTokens:K.metadata.usage.cacheWriteInputTokens},...K.metadata.usage?.cacheDetails!=null&&{cacheDetails:K.metadata.usage.cacheDetails}}}:void 0,X=K.metadata.trace?{trace:K.metadata.trace}:void 0;if(Y||X||K.metadata.performanceConfig||K.metadata.serviceTier){let ie={...Y,...X,...K.metadata.performanceConfig&&{performanceConfig:K.metadata.performanceConfig},...K.metadata.serviceTier&&{serviceTier:K.metadata.serviceTier}};z={amazonBedrock:ie,bedrock:ie}}}if(K.contentBlockStart?.contentBlockIndex!=null&&!K.contentBlockStart?.start?.toolUse){let Y=K.contentBlockStart.contentBlockIndex;q[Y]={type:"text"},W.enqueue({type:"text-start",id:String(Y)})}if(K.contentBlockDelta?.delta&&"text"in K.contentBlockDelta.delta&&K.contentBlockDelta.delta.text){let Y=K.contentBlockDelta.contentBlockIndex||0;if(q[Y]==null)q[Y]={type:"text"},W.enqueue({type:"text-start",id:String(Y)});let X=N?.process(K.contentBlockDelta.delta.text)??K.contentBlockDelta.delta.text;if(X.length>0)W.enqueue({type:"text-delta",id:String(Y),delta:X})}if(K.contentBlockStop?.contentBlockIndex!=null){let Y=K.contentBlockStop.contentBlockIndex,X=q[Y];if(X!=null){if(X.type==="reasoning"){let ie=X.redactedContent!=null?{redactedContent:X.redactedContent}:null;W.enqueue({type:"reasoning-end",id:String(Y),...ie!=null?{providerMetadata:{amazonBedrock:ie,bedrock:ie}}:{}})}else if(X.type==="text")W.enqueue({type:"text-end",id:String(Y)});else if(X.type==="tool-call")if(X.isJsonResponseTool)k=!0,W.enqueue({type:"text-start",id:String(Y)}),W.enqueue({type:"text-delta",id:String(Y),delta:X.jsonText}),W.enqueue({type:"text-end",id:String(Y)});else W.enqueue({type:"tool-input-end",id:X.toolCallId}),W.enqueue({type:"tool-call",toolCallId:X.toolCallId,toolName:X.toolName,input:X.jsonText===""?"{}":X.jsonText});delete q[Y]}}if(K.contentBlockDelta?.delta&&"reasoningContent"in K.contentBlockDelta.delta&&K.contentBlockDelta.delta.reasoningContent){let Y=K.contentBlockDelta.contentBlockIndex||0,X=K.contentBlockDelta.delta.reasoningContent;if("text"in X&&X.text){if(q[Y]==null)q[Y]={type:"reasoning"},W.enqueue({type:"reasoning-start",id:String(Y)});W.enqueue({type:"reasoning-delta",id:String(Y),delta:X.text})}else if("signature"in X&&X.signature){if(q[Y]==null)q[Y]={type:"reasoning"},W.enqueue({type:"reasoning-start",id:String(Y)});{let ie={signature:X.signature};W.enqueue({type:"reasoning-delta",id:String(Y),delta:"",providerMetadata:{amazonBedrock:ie,bedrock:ie}})}}else if("data"in X&&X.data){if(q[Y]==null)q[Y]={type:"reasoning"},W.enqueue({type:"reasoning-start",id:String(Y)});{let ie={redactedData:X.data};W.enqueue({type:"reasoning-delta",id:String(Y),delta:"",providerMetadata:{amazonBedrock:ie,bedrock:ie}})}}else if("redactedContent"in X&&X.redactedContent){if(q[Y]==null)q[Y]={type:"reasoning"},W.enqueue({type:"reasoning-start",id:String(Y)});let ie=q[Y];if(ie.type==="reasoning")ie.redactedContent=(ie.redactedContent??"")+X.redactedContent}}let J=K.contentBlockStart;if(J?.start?.toolUse!=null){let Y=J.start.toolUse,X=J.contentBlockIndex,ie=S&&Y.name==="json",ye=Zn(Y.toolUseId,_);if(q[X]={type:"tool-call",toolCallId:ye,toolName:Y.name,jsonText:"",isJsonResponseTool:ie},!ie)W.enqueue({type:"tool-input-start",id:ye,toolName:Y.name})}let re=K.contentBlockDelta;if(re?.delta&&"toolUse"in re.delta&&re.delta.toolUse){let Y=re.contentBlockIndex,X=q[Y];if(X?.type==="tool-call"){let ie=re.delta.toolUse.input??"";if(!X.isJsonResponseTool)W.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:ie});X.jsonText+=ie}}},flush(V){if(k||R!=null){let W={...z?.amazonBedrock??z?.bedrock,...k&&{isJsonResponseFromTool:!0},stopSequence:R};z={...z,amazonBedrock:W,bedrock:W}}V.enqueue({type:"finish",finishReason:U,usage:Jh(B),...z&&{providerMetadata:z}})}})),request:{body:g},response:{headers:D}}}getUrl(h){return`${this.config.baseUrl()}/model/${encodeURIComponent(h)}`}},ep=class{constructor(){this.started=!1,this.completed=!1,this.depth=0,this.inString=!1,this.escaped=!1}process(f){let h="";for(let g of f){if(this.completed)break;if(!this.started){if(g!=="{")continue;this.started=!0,this.depth=1,h+=g;continue}if(h+=g,this.escaped){this.escaped=!1;continue}if(g==="\\"&&this.inString){this.escaped=!0;continue}if(g==='"'){this.inString=!this.inString;continue}if(this.inString)continue;if(g==="{")this.depth++;else if(g==="}"){if(this.depth--,this.depth===0)this.completed=!0}}return h}},lp=p([s(eN),e()]),fp=t({delta:t({stop_sequence:e().nullish()}).nullish()}).catchall(m()),hp=t({toolUseId:e(),name:e(),input:m().optional()}),TN=()=>t({signature:e().nullish(),text:e()}),AN=()=>t({data:e()}),pp=t({inputTokens:n(),ttl:e()}).catchall(Fe()),IN=u(()=>l(t({metrics:t({latencyMs:n()}).nullish(),output:t({message:t({content:o(t({text:e().nullish(),citationsContent:t({content:o(t({text:e().nullish()})).nullish()}).nullish(),toolUse:hp.nullish(),reasoningContent:p([t({reasoningText:TN()}),t({redactedReasoning:AN()}),t({redactedContent:e()})]).nullish()})),role:e()})}),stopReason:lp,additionalModelResponseFields:fp.nullish(),trace:m().nullish(),performanceConfig:t({latency:e()}).nullish(),serviceTier:t({type:e()}).nullish(),usage:t({inputTokens:n(),outputTokens:n(),totalTokens:n(),cacheReadInputTokens:n().nullish(),cacheWriteInputTokens:n().nullish(),cacheDetails:o(pp).nullish()}).catchall(Fe())}))),CN=t({contentBlockDelta:t({contentBlockIndex:n(),delta:p([t({text:e()}),t({citation:d(e(),m())}),t({toolUse:t({input:e()})}),t({reasoningContent:t({text:e()})}),t({reasoningContent:t({signature:e()})}),t({reasoningContent:t({data:e()})}),t({reasoningContent:t({redactedContent:e()})})]).nullish()}).nullish(),contentBlockStart:t({contentBlockIndex:n(),start:t({toolUse:hp.nullish()}).nullish()}).nullish(),contentBlockStop:t({contentBlockIndex:n()}).nullish(),internalServerException:d(e(),m()).nullish(),messageStop:t({additionalModelResponseFields:fp.nullish(),stopReason:lp}).nullish(),metadata:t({trace:m().nullish(),performanceConfig:t({latency:e()}).nullish(),serviceTier:t({type:e()}).nullish(),usage:t({cacheReadInputTokens:n().nullish(),cacheWriteInputTokens:n().nullish(),cacheDetails:o(pp).nullish(),inputTokens:n(),outputTokens:n(),totalTokens:n().optional()}).catchall(Fe()).nullish()}).nullish(),modelStreamErrorException:d(e(),m()).nullish(),serviceUnavailableException:d(e(),m()).nullish(),throttlingException:d(e(),m()).nullish(),validationException:d(e(),m()).nullish()}),tp={low:"low",medium:"medium",high:"high",max:"max"},RN={low:"low",medium:"medium",high:"high"},vN={low:"low",medium:"medium",high:"high"},kN={none:"none",minimal:"minimal",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"};function mp(f){return f.includes("amazon.nova-2-lite-v1:0")}function NN({reasoning:f,amazonBedrockOptions:h,warnings:g,isAnthropicModel:y,isOpenAIModel:w,modelId:S}){let x=h.reasoningConfig;if(!Pe(f))return h;let _={...h};if(x?.type==="disabled")return _.reasoningConfig={...x},delete _.reasoningConfig.maxReasoningEffort,delete _.reasoningConfig.budgetTokens,_;let A=mp(S),P=w||A||x!=null;if(y){let D=Hm(S);if(f==="none")_.reasoningConfig={type:"disabled"};else if(D.supportsAdaptiveThinking){let U=x?.maxReasoningEffort??ut({reasoning:f,effortMap:{...tp,...D.supportsXhighEffort&&{xhigh:"xhigh"}},warnings:g});_.reasoningConfig={...x,type:x?.type??"adaptive",maxReasoningEffort:U}}else{let U=x?.budgetTokens??nn({reasoning:f,maxOutputTokens:D.maxOutputTokens,maxReasoningBudget:D.maxOutputTokens,warnings:g});_.reasoningConfig={...x,type:x?.type??"enabled",budgetTokens:U}}}else if(f==="none"&&A);else if(P){let D=x?.maxReasoningEffort??ut({reasoning:f,effortMap:A?RN:w?S.includes("openai.gpt-oss-")?vN:kN:tp,warnings:g});_.reasoningConfig={...x,...A&&{type:x?.type??"enabled"},maxReasoningEffort:D}}else g.push({type:"unsupported",feature:"reasoning",details:"Portable reasoning is not supported for this model and will be ignored. If the model supports a provider-specific reasoning configuration, use providerOptions.amazonBedrock.reasoningConfig."});return _}var rp=u(()=>l(t({dimensions:p([a(1024),a(512),a(256)]).optional(),normalize:r().optional(),embeddingDimension:p([a(256),a(384),a(1024),a(3072)]).optional(),embeddingPurpose:s(["GENERIC_INDEX","TEXT_RETRIEVAL","IMAGE_RETRIEVAL","VIDEO_RETRIEVAL","DOCUMENT_RETRIEVAL","AUDIO_RETRIEVAL","GENERIC_RETRIEVAL","CLASSIFICATION","CLUSTERING"]).optional(),inputType:s(["search_document","search_query","classification","clustering"]).optional(),truncate:s(["NONE","START","END"]).optional(),outputDimension:p([a(256),a(512),a(1024),a(1536)]).optional()}))),ON=class f{get maxEmbeddingsPerCall(){return this.modelFamily==="cohere"?96:1}get modelFamily(){return this.config.modelFamily??DN(this.modelId)}static[H](h){return te({modelId:h.modelId,config:h.config})}static[Q](h){return new f(h.modelId,h.config)}constructor(h,g){this.modelId=h,this.config=g,this.specificationVersion="v4",this.provider="amazon-bedrock",this.supportsParallelCalls=!0}getUrl(h){let g=encodeURIComponent(h);return`${this.config.baseUrl()}/model/${g}/invoke`}async doEmbed({values:h,dimensions:g,headers:y,abortSignal:w,providerOptions:S}){if(h.length>this.maxEmbeddingsPerCall)throw new pt({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:h});let x=await T({provider:"amazonBedrock",providerOptions:S,schema:rp})??await T({provider:"bedrock",providerOptions:S,schema:rp})??{},_=this.modelFamily,A=_==="nova"?{taskType:"SINGLE_EMBEDDING",singleEmbeddingParams:{embeddingPurpose:x.embeddingPurpose??"GENERIC_INDEX",embeddingDimension:x.embeddingDimension??g??1024,text:{truncationMode:x.truncate??"END",value:h[0]}}}:_==="cohere"?{input_type:x.inputType??"search_query",texts:h,truncate:x.truncate,output_dimension:x.outputDimension??g}:{inputText:h[0],dimensions:x.dimensions??g,normalize:x.normalize},P=this.getUrl(this.modelId),{value:D,responseHeaders:U}=await O({url:P,headers:await M(I(this.config.headers?await M(this.config.headers):void 0,y)),body:A,failedResponseHandler:Eo,successfulResponseHandler:E(UN),fetch:this.config.fetch,abortSignal:w}),B;if("embedding"in D)B=[D.embedding];else if(Array.isArray(D.embeddings)){let R=D.embeddings[0];if(typeof R==="object"&&R!==null&&"embeddingType"in R)B=[R.embedding];else B=D.embeddings}else B=D.embeddings.float;let z=Number(U?.["x-amzn-bedrock-input-token-count"]),k="inputTextTokenCount"in D?D.inputTextTokenCount:("inputTokenCount"in D)?D.inputTokenCount??0:z;return{embeddings:B,usage:{tokens:k},warnings:[]}}};function PN(f){return f.includes("cohere.embed-")}function MN(f){return f.includes("amazon.nova-")&&f.includes("embed")}function DN(f){return MN(f)?"nova":PN(f)?"cohere":"titan"}var UN=u(()=>l(p([t({embedding:o(n()),inputTextTokenCount:n()}),t({embeddings:o(t({embeddingType:e(),embedding:o(n())})),inputTokenCount:n().optional()}),t({embeddings:o(o(n()))}),t({embeddings:t({float:o(o(n()))})})]))),FN={"amazon.nova-canvas-v1:0":5},np=u(()=>l(t({quality:s(["standard","premium"]).optional(),negativeText:e().optional(),cfgScale:n().optional(),style:s(["3D_ANIMATED_FAMILY_FILM","DESIGN_SKETCH","FLAT_VECTOR_ILLUSTRATION","GRAPHIC_NOVEL_ILLUSTRATION","MAXIMALISM","MIDCENTURY_RETRO","PHOTOREALISM","SOFT_DIGITAL_PAINTING"]).optional(),taskType:s(["TEXT_IMAGE","IMAGE_VARIATION","INPAINTING","OUTPAINTING","BACKGROUND_REMOVAL"]).optional(),maskPrompt:e().optional(),outPaintingMode:s(["DEFAULT","PRECISE"]).optional(),similarityStrength:n().optional()}))),$N=class f{static[H](h){return te({modelId:h.modelId,config:h.config})}static[Q](h){return new f(h.modelId,h.config)}get maxImagesPerCall(){return FN[this.modelId]??1}get supportsFileInputs(){return this.modelId==="amazon.nova-canvas-v1:0"?!0:void 0}get supportsMaskInputs(){return this.modelId==="amazon.nova-canvas-v1:0"?!0:void 0}getUrl(h){let g=encodeURIComponent(h);return`${this.config.baseUrl()}/model/${g}/invoke`}constructor(h,g){this.modelId=h,this.config=g,this.specificationVersion="v4",this.provider="amazon-bedrock"}async doGenerate({prompt:h,n:g,size:y,aspectRatio:w,seed:S,providerOptions:x,headers:_,abortSignal:A,files:P,mask:D}){let U=[],[B,z]=y?y.split("x").map(Number):[],k=P!=null&&P.length>0,R=await T({provider:"amazonBedrock",providerOptions:x,schema:np})??await T({provider:"bedrock",providerOptions:x,schema:np})??{},N={...B?{width:B}:{},...z?{height:z}:{},...S?{seed:S}:{},...g?{numberOfImages:g}:{},...R?.quality?{quality:R.quality}:{},...R?.cfgScale?{cfgScale:R.cfgScale}:{}},q;if(k){let K=D?.type!=null,J=R?.maskPrompt!=null,re=R?.taskType??(K||J?"INPAINTING":"IMAGE_VARIATION"),Y=So(P[0]);switch(re){case"INPAINTING":{let X={image:Y,...h?{text:h}:{},...R?.negativeText?{negativeText:R.negativeText}:{}};if(K)X.maskImage=So(D);else if(J)X.maskPrompt=R.maskPrompt;q={taskType:"INPAINTING",inPaintingParams:X,imageGenerationConfig:N};break}case"OUTPAINTING":{let X={image:Y,...h?{text:h}:{},...R?.negativeText?{negativeText:R.negativeText}:{},...R?.outPaintingMode?{outPaintingMode:R.outPaintingMode}:{}};if(K)X.maskImage=So(D);else if(J)X.maskPrompt=R.maskPrompt;q={taskType:"OUTPAINTING",outPaintingParams:X,imageGenerationConfig:N};break}case"BACKGROUND_REMOVAL":q={taskType:"BACKGROUND_REMOVAL",backgroundRemovalParams:{image:Y}};break;case"IMAGE_VARIATION":q={taskType:"IMAGE_VARIATION",imageVariationParams:{images:P.map((X)=>So(X)),...h?{text:h}:{},...R?.negativeText?{negativeText:R.negativeText}:{},...R?.similarityStrength!=null?{similarityStrength:R.similarityStrength}:{}},imageGenerationConfig:N};break;default:throw Error(`Unsupported task type: ${re}`)}}else q={taskType:"TEXT_IMAGE",textToImageParams:{text:h,...R?.negativeText?{negativeText:R.negativeText}:{},...R?.style?{style:R.style}:{}},imageGenerationConfig:N};if(w!=null)U.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."});let V=this.config._internal?.currentDate?.()??new Date,{value:W,responseHeaders:G}=await O({url:this.getUrl(this.modelId),headers:await M(I(this.config.headers?await M(this.config.headers):void 0,_)),body:q,failedResponseHandler:Eo,successfulResponseHandler:E(BN),abortSignal:A,fetch:this.config.fetch});if(W.status==="Request Moderated"){let K=W.details?.["Moderation Reasons"];throw Error(`Amazon Bedrock request was moderated: ${(Array.isArray(K)?K:["Unknown"]).join(", ")}`)}if(!W.images||W.images.length===0)throw Error("Amazon Bedrock returned no images. "+(W.status?`Status: ${W.status}`:""));return{images:W.images,warnings:U,response:{timestamp:V,modelId:this.modelId,headers:G}}}};function So(f){if(f.type==="url")throw Error("URL-based images are not supported for Amazon Bedrock image editing. Please provide the image data directly.");if(f.data instanceof Uint8Array)return it(f.data);return f.data}var BN=u(()=>l(t({images:o(e()).optional(),id:e().optional(),status:e().optional(),result:m().optional(),progress:m().optional(),details:d(e(),m()).optional(),preview:m().optional()}))),Ac="5.0.128";function LN(f,h,g="bedrock"){return async(y,w)=>{let S=h??globalThis.fetch,x=y instanceof Request?y:void 0,_=I(Di(x?.headers),Di(w?.headers)),A=Ee(_,`ai-sdk-amazon-bedrock/${Ac}`,Pi()),P=w?.body??void 0;if(P===void 0&&x&&x.body!==null)try{P=await x.clone().text()}catch{}if((w?.method??x?.method)?.toUpperCase()!=="POST"||!P)return S(y,{...w,headers:A});let D=typeof y==="string"?y:y instanceof URL?y.href:y.url,U=zN(P),B=await f(),z=await new Ym({url:D,method:"POST",headers:Object.entries(A).filter(([,N])=>HN(N)),body:U,region:B.region,accessKeyId:B.accessKeyId,secretAccessKey:B.secretAccessKey,sessionToken:B.sessionToken,service:g}).sign(),k=Di(z.headers),R=I(A,k);return S(y,{...w,body:U,headers:R})}}function zN(f){if(typeof f==="string")return f;else if(f instanceof Uint8Array)return new TextDecoder().decode(f);else if(f instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(f));else return JSON.stringify(f)}function HN(f){return!/[\u0080-\uffff]/.test(f)}function qN(f,h){return async(g,y)=>{let w=h??globalThis.fetch,S=Di(y?.headers),x=Ee(S,`ai-sdk-amazon-bedrock/${Ac}`,Pi()),_=I(x,{Authorization:`Bearer ${f}`});return w(g,{...y,headers:_})}}var jN=u(()=>l(t({results:o(t({index:n(),relevanceScore:n()})),nextToken:e().optional()}))),sp=u(()=>l(t({nextToken:e().optional(),additionalModelRequestFields:d(e(),L()).optional()}))),VN=class{constructor(f,h){this.modelId=f,this.config=h,this.specificationVersion="v4",this.provider="amazon-bedrock"}async doRerank({documents:f,headers:h,query:g,topN:y,abortSignal:w,providerOptions:S}){let x=await T({provider:"amazonBedrock",providerOptions:S,schema:sp})??await T({provider:"bedrock",providerOptions:S,schema:sp}),{value:_,responseHeaders:A,rawValue:P}=await O({url:`${this.config.baseUrl()}/rerank`,headers:await M(I(await M(this.config.headers),h)),body:{nextToken:x?.nextToken,queries:[{textQuery:{text:g},type:"TEXT"}],rerankingConfiguration:{bedrockRerankingConfiguration:{modelConfiguration:{modelArn:`arn:aws:bedrock:${this.config.region}::foundation-model/${this.modelId}`,additionalModelRequestFields:x?.additionalModelRequestFields},numberOfResults:y},type:"BEDROCK_RERANKING_MODEL"},sources:f.values.map((D)=>({type:"INLINE",inlineDocumentSource:f.type==="text"?{type:"TEXT",textDocument:{text:D}}:{type:"JSON",jsonDocument:D}}))},failedResponseHandler:Eo,successfulResponseHandler:E(jN),fetch:this.config.fetch,abortSignal:w});return{ranking:_.results,response:{headers:A,body:P}}}},WN=[{regionPrefix:"cn-",dnsSuffix:"amazonaws.com.cn"},{regionPrefix:"us-iso-",dnsSuffix:"c2s.ic.gov"},{regionPrefix:"us-isob-",dnsSuffix:"sc2s.sgov.gov"},{regionPrefix:"eu-isoe-",dnsSuffix:"cloud.adc-e.uk"},{regionPrefix:"us-isof-",dnsSuffix:"csp.hci.ic.gov"},{regionPrefix:"eusc-",dnsSuffix:"amazonaws.eu"}];function op({baseURL:f,getRegion:h,service:g,serviceEndpointUrlEnvironmentVariableName:y}){let w=f??dt({settingValue:void 0,environmentVariableName:y})??dt({settingValue:void 0,environmentVariableName:"AWS_ENDPOINT_URL"});if(w!=null)return Ye(w)??w;let S=h();if(!Ls(S))throw new F({argument:"region",message:"Invalid AWS region. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints."});let x=`https://${g}.${S}.${WN.find(({regionPrefix:_})=>S.startsWith(_))?.dnsSuffix??"amazonaws.com"}`;return Ye(x)??x}function Tl(f={}){let h=dt({settingValue:f.apiKey,environmentVariableName:"AWS_BEARER_TOKEN_BEDROCK"}),g=h&&h.trim().length>0?h.trim():void 0,y=g?qN(g,f.fetch):LN(async()=>{let B=so({settingValue:f.region,settingName:"region",environmentVariableName:"AWS_REGION",description:"AWS region"});if(f.credentialProvider)try{return{...await f.credentialProvider(),region:B}}catch(z){let k=z instanceof Error?z.message:String(z);throw Error(`AWS credential provider failed: ${k}. Please ensure your credential provider returns valid AWS credentials with accessKeyId and secretAccessKey properties.`)}try{return{region:B,accessKeyId:so({settingValue:f.accessKeyId,settingName:"accessKeyId",environmentVariableName:"AWS_ACCESS_KEY_ID",description:"AWS access key ID"}),secretAccessKey:so({settingValue:f.secretAccessKey,settingName:"secretAccessKey",environmentVariableName:"AWS_SECRET_ACCESS_KEY",description:"AWS secret access key"}),sessionToken:f.accessKeyId!=null&&f.secretAccessKey!=null?f.sessionToken:dt({settingValue:f.sessionToken,environmentVariableName:"AWS_SESSION_TOKEN"})}}catch(z){let k=z instanceof Error?z.message:String(z);if(k.includes("AWS_ACCESS_KEY_ID")||k.includes("accessKeyId"))throw Error(`AWS SigV4 authentication requires AWS credentials. Please provide either:
69
+ 1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables
70
+ 2. Provide accessKeyId and secretAccessKey in options
71
+ 3. Use a credentialProvider function
72
+ 4. Use API key authentication with AWS_BEARER_TOKEN_BEDROCK or apiKey option
73
+ Original error: ${k}`);if(k.includes("AWS_SECRET_ACCESS_KEY")||k.includes("secretAccessKey"))throw Error(`AWS SigV4 authentication requires both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. Please ensure both credentials are provided.
74
+ Original error: ${k}`);throw z}},f.fetch),w=()=>{let B=f.headers??{};return Ee(B,`ai-sdk-amazon-bedrock/${Ac}`)},S=()=>op({baseURL:f.baseURL,getRegion:()=>so({settingValue:f.region,settingName:"region",environmentVariableName:"AWS_REGION",description:"AWS region"}),service:"bedrock-runtime",serviceEndpointUrlEnvironmentVariableName:"AWS_ENDPOINT_URL_BEDROCK_RUNTIME"}),x=()=>op({baseURL:f.baseURL,getRegion:()=>so({settingValue:f.region,settingName:"region",environmentVariableName:"AWS_REGION",description:"AWS region"}),service:"bedrock-agent-runtime",serviceEndpointUrlEnvironmentVariableName:"AWS_ENDPOINT_URL_BEDROCK_AGENT_RUNTIME"}),_=(B,z={})=>new _N(B,{baseUrl:S,headers:w,fetch:y,generateId:C,modelFamily:z.modelFamily}),A=function(B,z){if(new.target)throw Error("The Amazon Bedrock model function cannot be called with the new keyword.");return _(B,z)},P=(B,z={})=>new ON(B,{baseUrl:S,headers:w,fetch:y,modelFamily:z.modelFamily}),D=(B)=>new $N(B,{baseUrl:S,headers:w,fetch:y}),U=(B)=>new VN(B,{baseUrl:x,region:so({settingValue:f.region,settingName:"region",environmentVariableName:"AWS_REGION",description:"AWS region"}),headers:w,fetch:y});return A.specificationVersion="v4",A.languageModel=_,A.embedding=P,A.embeddingModel=P,A.textEmbedding=P,A.textEmbeddingModel=P,A.image=D,A.imageModel=D,A.reranking=U,A.rerankingModel=U,A.tools=Oi,A}var e9=Tl();var{ProviderError:N9,CredentialsProviderError:O9,loadConfig:P9,NODE_REGION_CONFIG_FILE_OPTIONS:M9}=Ce(),{normalizeProvider:D9}=rr();var xK=(f={})=>{let h;return async(g)=>{if(!h){let{defaultProvider:y}=Wb();h=y({...f})}return h(g)}};var Co=xK;
75
+ export{Tl,Co};