@graphql-hive/gateway-runtime 2.1.0 → 2.1.1-alpha-e43a6c1917d3c195bc31b20b3caee2b0deaa9c7b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -19,13 +19,27 @@ import { wrapSchema, schemaFromExecutor } from '@graphql-tools/wrap';
19
19
  import { useCSRFPrevention } from '@graphql-yoga/plugin-csrf-prevention';
20
20
  import { useDeferStream } from '@graphql-yoga/plugin-defer-stream';
21
21
  import { usePersistedOperations } from '@graphql-yoga/plugin-persisted-operations';
22
- import { AsyncDisposableStack } from '@whatwg-node/disposablestack';
22
+ import require$$1__default, { AsyncDisposableStack } from '@whatwg-node/disposablestack';
23
23
  export * from '@whatwg-node/disposablestack';
24
- import { handleMaybePromise, iterateAsync } from '@whatwg-node/promise-helpers';
24
+ import require$$4, { handleMaybePromise, iterateAsync } from '@whatwg-node/promise-helpers';
25
25
  import { useCookies } from '@whatwg-node/server-plugin-cookies';
26
26
  import { print, visit, visitWithTypeInfo, getArgumentValues, getNamedType, isIntrospectionType, isListType, isCompositeType, getOperationAST, isSchema, parse, buildASTSchema, buildSchema } from 'graphql';
27
27
  import { isAsyncIterable as isAsyncIterable$1, useReadinessCheck, useExecutionCancellation, createYoga, chain, mergeSchemas } from 'graphql-yoga';
28
28
  import { DEFAULT_UPLINKS, fetchSupergraphSdlFromManagedFederation } from '@graphql-tools/federation';
29
+ import require$$0$2 from 'node:buffer';
30
+ import require$$1$4 from 'node:fs';
31
+ import require$$2$1 from 'node:url';
32
+ import require$$0$1 from 'node:stream';
33
+ import require$$1$2 from 'node:tls';
34
+ import require$$0$3 from 'node:http';
35
+ import require$$1$1 from 'node:util';
36
+ import require$$0 from 'node:events';
37
+ import require$$3 from 'node:stream/promises';
38
+ import require$$1$3 from 'node:https';
39
+ import require$$0$5 from 'node:zlib';
40
+ import require$$0$4 from 'tslib';
41
+ import require$$2 from 'node:crypto';
42
+ import require$$3$1 from 'crypto';
29
43
  import { useApolloUsageReport } from '@graphql-yoga/plugin-apollo-usage-report';
30
44
  import { useHive } from '@graphql-hive/yoga';
31
45
  import { useContentEncoding as useContentEncoding$1 } from '@whatwg-node/server';
@@ -72,6 +86,4837 @@ function isDebug() {
72
86
  return getEnvBool("DEBUG");
73
87
  }
74
88
 
89
+ function commonjsRequire(path) {
90
+ throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
91
+ }
92
+
93
+ function isNextJs() {
94
+ return Object.keys(globalThis).some(key => key.startsWith('__NEXT'))
95
+ }
96
+
97
+ var shouldSkipPonyfill$2 = function shouldSkipPonyfill() {
98
+ if (globalThis.Deno) {
99
+ return true
100
+ }
101
+ if (globalThis.Bun) {
102
+ return true
103
+ }
104
+ if (isNextJs()) {
105
+ return true
106
+ }
107
+ return false
108
+ };
109
+
110
+ var urlpattern;
111
+ var hasRequiredUrlpattern;
112
+
113
+ function requireUrlpattern () {
114
+ if (hasRequiredUrlpattern) return urlpattern;
115
+ hasRequiredUrlpattern = 1;
116
+ var U=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var Ee=Object.getOwnPropertyNames;var Oe=Object.prototype.hasOwnProperty;var a=(e,t)=>U(e,"name",{value:t,configurable:true});var ke=(e,t)=>{for(var r in t)U(e,r,{get:t[r],enumerable:true});},Te=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ee(t))!Oe.call(e,o)&&o!==r&&U(e,o,{get:()=>t[o],enumerable:!(n=Re(t,o))||n.enumerable});return e};var Ae=e=>Te(U({},"__esModule",{value:true}),e);var He={};ke(He,{URLPattern:()=>M});urlpattern=Ae(He);var P=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,r,n,o,l,f){this.type=t,this.name=r,this.prefix=n,this.value=o,this.suffix=l,this.modifier=f;}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};a(P,"Part");var ye=/[$_\p{ID_Start}]/u,we=/[$_\u200C\u200D\p{ID_Continue}]/u,F=".*";function Ce(e,t){return (t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}a(Ce,"isASCII");function W(e,t=false){let r=[],n=0;for(;n<e.length;){let o=e[n],l=a(function(f){if(!t)throw new TypeError(f);r.push({type:"INVALID_CHAR",index:n,value:e[n++]});},"ErrorOrInvalid");if(o==="*"){r.push({type:"ASTERISK",index:n,value:e[n++]});continue}if(o==="+"||o==="?"){r.push({type:"OTHER_MODIFIER",index:n,value:e[n++]});continue}if(o==="\\"){r.push({type:"ESCAPED_CHAR",index:n++,value:e[n++]});continue}if(o==="{"){r.push({type:"OPEN",index:n,value:e[n++]});continue}if(o==="}"){r.push({type:"CLOSE",index:n,value:e[n++]});continue}if(o===":"){let f="",s=n+1;for(;s<e.length;){let i=e.substr(s,1);if(s===n+1&&ye.test(i)||s!==n+1&&we.test(i)){f+=e[s++];continue}break}if(!f){l(`Missing parameter name at ${n}`);continue}r.push({type:"NAME",index:n,value:f}),n=s;continue}if(o==="("){let f=1,s="",i=n+1,c=false;if(e[i]==="?"){l(`Pattern cannot start with "?" at ${i}`);continue}for(;i<e.length;){if(!Ce(e[i],false)){l(`Invalid character '${e[i]}' at ${i}.`),c=true;break}if(e[i]==="\\"){s+=e[i++]+e[i++];continue}if(e[i]===")"){if(f--,f===0){i++;break}}else if(e[i]==="("&&(f++,e[i+1]!=="?")){l(`Capturing groups are not allowed at ${i}`),c=true;break}s+=e[i++];}if(c)continue;if(f){l(`Unbalanced pattern at ${n}`);continue}if(!s){l(`Missing pattern at ${n}`);continue}r.push({type:"REGEX",index:n,value:s}),n=i;continue}r.push({type:"CHAR",index:n,value:e[n++]});}return r.push({type:"END",index:n,value:""}),r}a(W,"lexer");function _(e,t={}){let r=W(e);t.delimiter??="/#?",t.prefixes??="./";let n=`[^${x(t.delimiter)}]+?`,o=[],l=0,f=0,i=new Set,c=a(u=>{if(f<r.length&&r[f].type===u)return r[f++].value},"tryConsume"),h=a(()=>c("OTHER_MODIFIER")??c("ASTERISK"),"tryConsumeModifier"),p=a(u=>{let d=c(u);if(d!==void 0)return d;let{type:g,index:y}=r[f];throw new TypeError(`Unexpected ${g} at ${y}, expected ${u}`)},"mustConsume"),A=a(()=>{let u="",d;for(;d=c("CHAR")??c("ESCAPED_CHAR");)u+=d;return u},"consumeText"),be=a(u=>u,"DefaultEncodePart"),N=t.encodePart||be,H="",v=a(u=>{H+=u;},"appendToPendingFixedValue"),D=a(()=>{H.length&&(o.push(new P(3,"","",N(H),"",3)),H="");},"maybeAddPartFromPendingFixedValue"),Z=a((u,d,g,y,B)=>{let m=3;switch(B){case "?":m=1;break;case "*":m=0;break;case "+":m=2;break}if(!d&&!g&&m===3){v(u);return}if(D(),!d&&!g){if(!u)return;o.push(new P(3,"","",N(u),"",m));return}let S;g?g==="*"?S=F:S=g:S=n;let k=2;S===n?(k=1,S=""):S===F&&(k=0,S="");let E;if(d?E=d:g&&(E=l++),i.has(E))throw new TypeError(`Duplicate name '${E}'.`);i.add(E),o.push(new P(k,E,N(u),S,N(y),m));},"addPart");for(;f<r.length;){let u=c("CHAR"),d=c("NAME"),g=c("REGEX");if(!d&&!g&&(g=c("ASTERISK")),d||g){let m=u??"";t.prefixes.indexOf(m)===-1&&(v(m),m=""),D();let S=h();Z(m,d,g,"",S);continue}let y=u??c("ESCAPED_CHAR");if(y){v(y);continue}if(c("OPEN")){let m=A(),S=c("NAME"),k=c("REGEX");!S&&!k&&(k=c("ASTERISK"));let E=A();p("CLOSE");let Pe=h();Z(m,S,k,E,Pe);continue}D(),p("END");}return o}a(_,"parse");function x(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}a(x,"escapeString");function q(e){return e&&e.ignoreCase?"ui":"u"}a(q,"flags");function J(e,t,r){return z(_(e,r),t,r)}a(J,"stringToRegexp");function T(e){switch(e){case 0:return "*";case 1:return "?";case 2:return "+";case 3:return ""}}a(T,"modifierToString");function z(e,t,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=false,r.strict??=false,r.end??=true,r.start??=true,r.endsWith="";let n=r.start?"^":"";for(let s of e){if(s.type===3){s.modifier===3?n+=x(s.value):n+=`(?:${x(s.value)})${T(s.modifier)}`;continue}t&&t.push(s.name);let i=`[^${x(r.delimiter)}]+?`,c=s.value;if(s.type===1?c=i:s.type===0&&(c=F),!s.prefix.length&&!s.suffix.length){s.modifier===3||s.modifier===1?n+=`(${c})${T(s.modifier)}`:n+=`((?:${c})${T(s.modifier)})`;continue}if(s.modifier===3||s.modifier===1){n+=`(?:${x(s.prefix)}(${c})${x(s.suffix)})`,n+=T(s.modifier);continue}n+=`(?:${x(s.prefix)}`,n+=`((?:${c})(?:`,n+=x(s.suffix),n+=x(s.prefix),n+=`(?:${c}))*)${x(s.suffix)})`,s.modifier===0&&(n+="?");}let o=`[${x(r.endsWith)}]|$`,l=`[${x(r.delimiter)}]`;if(r.end)return r.strict||(n+=`${l}?`),r.endsWith.length?n+=`(?=${o})`:n+="$",new RegExp(n,q(r));r.strict||(n+=`(?:${l}(?=${o}))?`);let f=false;if(e.length){let s=e[e.length-1];s.type===3&&s.modifier===3&&(f=r.delimiter.indexOf(s)>-1);}return f||(n+=`(?=${l}|${o})`),new RegExp(n,q(r))}a(z,"partsToRegexp");var b={delimiter:"",prefixes:"",sensitive:true,strict:true},Q={delimiter:".",prefixes:"",sensitive:true,strict:true},ee={delimiter:"/",prefixes:"/",sensitive:true,strict:true};function te(e,t){return e.length?e[0]==="/"?true:!t||e.length<2?false:(e[0]=="\\"||e[0]=="{")&&e[1]=="/":false}a(te,"isAbsolutePathname");function re(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}a(re,"maybeStripPrefix");function Le(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}a(Le,"maybeStripSuffix");function j(e){return !e||e.length<2?false:e[0]==="["||(e[0]==="\\"||e[0]==="{")&&e[1]==="["}a(j,"treatAsIPv6Hostname");var ne=["ftp","file","http","https","ws","wss"];function $(e){if(!e)return true;for(let t of ne)if(e.test(t))return true;return false}a($,"isSpecialScheme");function se(e,t){if(e=re(e,"#"),t||e==="")return e;let r=new URL("https://example.com");return r.hash=e,r.hash?r.hash.substring(1,r.hash.length):""}a(se,"canonicalizeHash");function ie(e,t){if(e=re(e,"?"),t||e==="")return e;let r=new URL("https://example.com");return r.search=e,r.search?r.search.substring(1,r.search.length):""}a(ie,"canonicalizeSearch");function ae(e,t){return t||e===""?e:j(e)?V(e):G(e)}a(ae,"canonicalizeHostname");function oe(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.password=e,r.password}a(oe,"canonicalizePassword");function ce(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.username=e,r.username}a(ce,"canonicalizeUsername");function le(e,t,r){if(r||e==="")return e;if(t&&!ne.includes(t))return new URL(`${t}:${e}`).pathname;let n=e[0]=="/";return e=new URL(n?e:"/-"+e,"https://example.com").pathname,n||(e=e.substring(2,e.length)),e}a(le,"canonicalizePathname");function fe(e,t,r){return K(t)===e&&(e=""),r||e===""?e:Y(e)}a(fe,"canonicalizePort");function he(e,t){return e=Le(e,":"),t||e===""?e:w(e)}a(he,"canonicalizeProtocol");function K(e){switch(e){case "ws":case "http":return "80";case "wws":case "https":return "443";case "ftp":return "21";default:return ""}}a(K,"defaultPortForProtocol");function w(e){if(e==="")return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(`Invalid protocol '${e}'.`)}a(w,"protocolEncodeCallback");function ue(e){if(e==="")return e;let t=new URL("https://example.com");return t.username=e,t.username}a(ue,"usernameEncodeCallback");function de(e){if(e==="")return e;let t=new URL("https://example.com");return t.password=e,t.password}a(de,"passwordEncodeCallback");function G(e){if(e==="")return e;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(e))throw new TypeError(`Invalid hostname '${e}'`);let t=new URL("https://example.com");return t.hostname=e,t.hostname}a(G,"hostnameEncodeCallback");function V(e){if(e==="")return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw new TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}a(V,"ipv6HostnameEncodeCallback");function Y(e){if(e===""||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(`Invalid port '${e}'.`)}a(Y,"portEncodeCallback");function pe(e){if(e==="")return e;let t=new URL("https://example.com");return t.pathname=e[0]!=="/"?"/-"+e:e,e[0]!=="/"?t.pathname.substring(2,t.pathname.length):t.pathname}a(pe,"standardURLPathnameEncodeCallback");function ge(e){return e===""?e:new URL(`data:${e}`).pathname}a(ge,"pathURLPathnameEncodeCallback");function me(e){if(e==="")return e;let t=new URL("https://example.com");return t.search=e,t.search.substring(1,t.search.length)}a(me,"searchEncodeCallback");function Se(e){if(e==="")return e;let t=new URL("https://example.com");return t.hash=e,t.hash.substring(1,t.hash.length)}a(Se,"hashEncodeCallback");var C=class{#i;#n=[];#t={};#e=0;#s=1;#l=0;#o=0;#d=0;#p=0;#g=false;constructor(t){this.#i=t;}get result(){return this.#t}parse(){for(this.#n=W(this.#i,true);this.#e<this.#n.length;this.#e+=this.#s){if(this.#s=1,this.#n[this.#e].type==="END"){if(this.#o===0){this.#b(),this.#f()?this.#r(9,1):this.#h()?this.#r(8,1):this.#r(7,0);continue}else if(this.#o===2){this.#u(5);continue}this.#r(10,0);break}if(this.#d>0)if(this.#A())this.#d-=1;else continue;if(this.#T()){this.#d+=1;continue}switch(this.#o){case 0:this.#P()&&this.#u(1);break;case 1:if(this.#P()){this.#C();let t=7,r=1;this.#E()?(t=2,r=3):this.#g&&(t=2),this.#r(t,r);}break;case 2:this.#S()?this.#u(3):(this.#x()||this.#h()||this.#f())&&this.#u(5);break;case 3:this.#O()?this.#r(4,1):this.#S()&&this.#r(5,1);break;case 4:this.#S()&&this.#r(5,1);break;case 5:this.#y()?this.#p+=1:this.#w()&&(this.#p-=1),this.#k()&&!this.#p?this.#r(6,1):this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 6:this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 7:this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 8:this.#f()&&this.#r(9,1);break;}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port="");}#r(t,r){switch(this.#o){case 0:break;case 1:this.#t.protocol=this.#c();break;case 2:break;case 3:this.#t.username=this.#c();break;case 4:this.#t.password=this.#c();break;case 5:this.#t.hostname=this.#c();break;case 6:this.#t.port=this.#c();break;case 7:this.#t.pathname=this.#c();break;case 8:this.#t.search=this.#c();break;case 9:this.#t.hash=this.#c();break;}this.#o!==0&&t!==10&&([1,2,3,4].includes(this.#o)&&[6,7,8,9].includes(t)&&(this.#t.hostname??=""),[1,2,3,4,5,6].includes(this.#o)&&[8,9].includes(t)&&(this.#t.pathname??=this.#g?"/":""),[1,2,3,4,5,6,7].includes(this.#o)&&t===9&&(this.#t.search??="")),this.#R(t,r);}#R(t,r){this.#o=t,this.#l=this.#e+r,this.#e+=r,this.#s=0;}#b(){this.#e=this.#l,this.#s=0;}#u(t){this.#b(),this.#o=t;}#m(t){return t<0&&(t=this.#n.length-t),t<this.#n.length?this.#n[t]:this.#n[this.#n.length-1]}#a(t,r){let n=this.#m(t);return n.value===r&&(n.type==="CHAR"||n.type==="ESCAPED_CHAR"||n.type==="INVALID_CHAR")}#P(){return this.#a(this.#e,":")}#E(){return this.#a(this.#e+1,"/")&&this.#a(this.#e+2,"/")}#S(){return this.#a(this.#e,"@")}#O(){return this.#a(this.#e,":")}#k(){return this.#a(this.#e,":")}#x(){return this.#a(this.#e,"/")}#h(){if(this.#a(this.#e,"?"))return true;if(this.#n[this.#e].value!=="?")return false;let t=this.#m(this.#e-1);return t.type!=="NAME"&&t.type!=="REGEX"&&t.type!=="CLOSE"&&t.type!=="ASTERISK"}#f(){return this.#a(this.#e,"#")}#T(){return this.#n[this.#e].type=="OPEN"}#A(){return this.#n[this.#e].type=="CLOSE"}#y(){return this.#a(this.#e,"[")}#w(){return this.#a(this.#e,"]")}#c(){let t=this.#n[this.#e],r=this.#m(this.#l).index;return this.#i.substring(r,t.index)}#C(){let t={};Object.assign(t,b),t.encodePart=w;let r=J(this.#c(),void 0,t);this.#g=$(r);}};a(C,"Parser");var X=["protocol","username","password","hostname","port","pathname","search","hash"],O="*";function xe(e,t){if(typeof e!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(e,t);return {protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}a(xe,"extractValues");function R(e,t){return t?I(e):e}a(R,"processBaseURLString");function L(e,t,r){let n;if(typeof t.baseURL=="string")try{n=new URL(t.baseURL),t.protocol===void 0&&(e.protocol=R(n.protocol.substring(0,n.protocol.length-1),r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&(e.username=R(n.username,r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&t.password===void 0&&(e.password=R(n.password,r)),t.protocol===void 0&&t.hostname===void 0&&(e.hostname=R(n.hostname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&(e.port=R(n.port,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&(e.pathname=R(n.pathname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&(e.search=R(n.search.substring(1,n.search.length),r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&t.hash===void 0&&(e.hash=R(n.hash.substring(1,n.hash.length),r));}catch{throw new TypeError(`invalid baseURL '${t.baseURL}'.`)}if(typeof t.protocol=="string"&&(e.protocol=he(t.protocol,r)),typeof t.username=="string"&&(e.username=ce(t.username,r)),typeof t.password=="string"&&(e.password=oe(t.password,r)),typeof t.hostname=="string"&&(e.hostname=ae(t.hostname,r)),typeof t.port=="string"&&(e.port=fe(t.port,e.protocol,r)),typeof t.pathname=="string"){if(e.pathname=t.pathname,n&&!te(e.pathname,r)){let o=n.pathname.lastIndexOf("/");o>=0&&(e.pathname=R(n.pathname.substring(0,o+1),r)+e.pathname);}e.pathname=le(e.pathname,e.protocol,r);}return typeof t.search=="string"&&(e.search=ie(t.search,r)),typeof t.hash=="string"&&(e.hash=se(t.hash,r)),e}a(L,"applyInit");function I(e){return e.replace(/([+*?:{}()\\])/g,"\\$1")}a(I,"escapePatternString");function Ie(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}a(Ie,"escapeRegexpString");function Ne(e,t){t.delimiter??="/#?",t.prefixes??="./",t.sensitive??=false,t.strict??=false,t.end??=true,t.start??=true,t.endsWith="";let r=".*",n=`[^${Ie(t.delimiter)}]+?`,o=/[$_\u200C\u200D\p{ID_Continue}]/u,l="";for(let f=0;f<e.length;++f){let s=e[f];if(s.type===3){if(s.modifier===3){l+=I(s.value);continue}l+=`{${I(s.value)}}${T(s.modifier)}`;continue}let i=s.hasCustomName(),c=!!s.suffix.length||!!s.prefix.length&&(s.prefix.length!==1||!t.prefixes.includes(s.prefix)),h=f>0?e[f-1]:null,p=f<e.length-1?e[f+1]:null;if(!c&&i&&s.type===1&&s.modifier===3&&p&&!p.prefix.length&&!p.suffix.length)if(p.type===3){let A=p.value.length>0?p.value[0]:"";c=o.test(A);}else c=!p.hasCustomName();if(!c&&!s.prefix.length&&h&&h.type===3){let A=h.value[h.value.length-1];c=t.prefixes.includes(A);}c&&(l+="{"),l+=I(s.prefix),i&&(l+=`:${s.name}`),s.type===2?l+=`(${s.value})`:s.type===1?i||(l+=`(${n})`):s.type===0&&(!i&&(!h||h.type===3||h.modifier!==3||c||s.prefix!=="")?l+="*":l+=`(${r})`),s.type===1&&i&&s.suffix.length&&o.test(s.suffix[0])&&(l+="\\"),l+=I(s.suffix),c&&(l+="}"),s.modifier!==3&&(l+=T(s.modifier));}return l}a(Ne,"partsToPattern");var M=class{#i;#n={};#t={};#e={};#s={};#l=false;constructor(t={},r,n){try{let o;if(typeof r=="string"?o=r:n=r,typeof t=="string"){let i=new C(t);if(i.parse(),t=i.result,o===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=o;}else {if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(o)throw new TypeError("parameter 1 is not of type 'string'.")}typeof n>"u"&&(n={ignoreCase:!1});let l={ignoreCase:n.ignoreCase===!0},f={pathname:O,protocol:O,username:O,password:O,hostname:O,port:O,search:O,hash:O};this.#i=L(f,t,!0),K(this.#i.protocol)===this.#i.port&&(this.#i.port="");let s;for(s of X){if(!(s in this.#i))continue;let i={},c=this.#i[s];switch(this.#t[s]=[],s){case "protocol":Object.assign(i,b),i.encodePart=w;break;case "username":Object.assign(i,b),i.encodePart=ue;break;case "password":Object.assign(i,b),i.encodePart=de;break;case "hostname":Object.assign(i,Q),j(c)?i.encodePart=V:i.encodePart=G;break;case "port":Object.assign(i,b),i.encodePart=Y;break;case "pathname":$(this.#n.protocol)?(Object.assign(i,ee,l),i.encodePart=pe):(Object.assign(i,b,l),i.encodePart=ge);break;case "search":Object.assign(i,b,l),i.encodePart=me;break;case "hash":Object.assign(i,b,l),i.encodePart=Se;break}try{this.#s[s]=_(c,i),this.#n[s]=z(this.#s[s],this.#t[s],i),this.#e[s]=Ne(this.#s[s],i),this.#l=this.#l||this.#s[s].some(h=>h.type===2);}catch{throw new TypeError(`invalid ${s} pattern '${this.#i[s]}'.`)}}}catch(o){throw new TypeError(`Failed to construct 'URLPattern': ${o.message}`)}}get[Symbol.toStringTag](){return "URLPattern"}test(t={},r){let n={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&r)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return false;try{typeof t=="object"?n=L(n,t,!1):n=L(n,xe(t,r),!1);}catch{return false}let o;for(o of X)if(!this.#n[o].exec(n[o]))return false;return true}exec(t={},r){let n={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&r)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?n=L(n,t,!1):n=L(n,xe(t,r),!1);}catch{return null}let o={};r?o.inputs=[t,r]:o.inputs=[t];let l;for(l of X){let f=this.#n[l].exec(n[l]);if(!f)return null;let s={};for(let[i,c]of this.#t[l].entries())if(typeof c=="string"||typeof c=="number"){let h=f[i+1];s[c]=h;}o[l]={input:n[l]??"",groups:s};}return o}static compareComponent(t,r,n){let o=a((i,c)=>{for(let h of ["type","modifier","prefix","value","suffix"]){if(i[h]<c[h])return -1;if(i[h]===c[h])continue;return 1}return 0},"comparePart"),l=new P(3,"","","","",3),f=new P(0,"","","","",3),s=a((i,c)=>{let h=0;for(;h<Math.min(i.length,c.length);++h){let p=o(i[h],c[h]);if(p)return p}return i.length===c.length?0:o(i[h]??l,c[h]??l)},"comparePartList");return !r.#e[t]&&!n.#e[t]?0:r.#e[t]&&!n.#e[t]?s(r.#s[t],[f]):!r.#e[t]&&n.#e[t]?s([f],n.#s[t]):s(r.#s[t],n.#s[t])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#l}};a(M,"URLPattern");
117
+ return urlpattern;
118
+ }
119
+
120
+ var urlpatternPolyfill;
121
+ var hasRequiredUrlpatternPolyfill;
122
+
123
+ function requireUrlpatternPolyfill () {
124
+ if (hasRequiredUrlpatternPolyfill) return urlpatternPolyfill;
125
+ hasRequiredUrlpatternPolyfill = 1;
126
+ const { URLPattern } = requireUrlpattern();
127
+
128
+ urlpatternPolyfill = { URLPattern };
129
+
130
+ if (!globalThis.URLPattern) {
131
+ globalThis.URLPattern = URLPattern;
132
+ }
133
+ return urlpatternPolyfill;
134
+ }
135
+
136
+ var cjs = {};
137
+
138
+ var fetch = {};
139
+
140
+ var fetchCurl = {};
141
+
142
+ var Response = {};
143
+
144
+ var Body = {};
145
+
146
+ var main = {exports: {}};
147
+
148
+ var sbmh;
149
+ var hasRequiredSbmh;
150
+
151
+ function requireSbmh () {
152
+ if (hasRequiredSbmh) return sbmh;
153
+ hasRequiredSbmh = 1;
154
+
155
+ /**
156
+ * Copyright Brian White. All rights reserved.
157
+ *
158
+ * @see https://github.com/mscdex/streamsearch
159
+ *
160
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
161
+ * of this software and associated documentation files (the "Software"), to
162
+ * deal in the Software without restriction, including without limitation the
163
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
164
+ * sell copies of the Software, and to permit persons to whom the Software is
165
+ * furnished to do so, subject to the following conditions:
166
+ *
167
+ * The above copyright notice and this permission notice shall be included in
168
+ * all copies or substantial portions of the Software.
169
+ *
170
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
171
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
172
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
173
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
174
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
175
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
176
+ * IN THE SOFTWARE.
177
+ *
178
+ * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation
179
+ * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool
180
+ */
181
+
182
+ const { EventEmitter } = require$$0;
183
+ const { inherits } = require$$1$1;
184
+
185
+ function SBMH (needle) {
186
+ if (typeof needle === 'string') {
187
+ needle = Buffer.from(needle);
188
+ }
189
+
190
+ if (!Buffer.isBuffer(needle)) {
191
+ throw new TypeError('The needle has to be a String or a Buffer.')
192
+ }
193
+
194
+ const needleLength = needle.length;
195
+ const needleLastCharIndex = needleLength - 1;
196
+
197
+ if (needleLength === 0) {
198
+ throw new Error('The needle cannot be an empty String/Buffer.')
199
+ }
200
+
201
+ if (needleLength > 256) {
202
+ throw new Error('The needle cannot have a length bigger than 256.')
203
+ }
204
+
205
+ this.maxMatches = Infinity;
206
+ this.matches = 0;
207
+
208
+ this._occ = new Uint8Array(256)
209
+ .fill(needleLength); // Initialize occurrence table.
210
+ this._lookbehind_size = 0;
211
+ this._needle = needle;
212
+ this._bufpos = 0;
213
+
214
+ this._lookbehind = Buffer.alloc(needleLastCharIndex);
215
+
216
+ // Populate occurrence table with analysis of the needle,
217
+ // ignoring last letter.
218
+ for (var i = 0; i < needleLastCharIndex; ++i) { // eslint-disable-line no-var
219
+ this._occ[needle[i]] = needleLastCharIndex - i;
220
+ }
221
+ }
222
+ inherits(SBMH, EventEmitter);
223
+
224
+ SBMH.prototype.reset = function () {
225
+ this._lookbehind_size = 0;
226
+ this.matches = 0;
227
+ this._bufpos = 0;
228
+ };
229
+
230
+ SBMH.prototype.push = function (chunk, pos) {
231
+ if (!Buffer.isBuffer(chunk)) {
232
+ chunk = Buffer.from(chunk, 'binary');
233
+ }
234
+ const chlen = chunk.length;
235
+ this._bufpos = pos || 0;
236
+ let r;
237
+ while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk); }
238
+ return r
239
+ };
240
+
241
+ SBMH.prototype._sbmh_feed = function (data) {
242
+ const len = data.length;
243
+ const needle = this._needle;
244
+ const needleLength = needle.length;
245
+ const needleLastCharIndex = needleLength - 1;
246
+ const needleLastChar = needle[needleLastCharIndex];
247
+
248
+ // Positive: points to a position in `data`
249
+ // pos == 3 points to data[3]
250
+ // Negative: points to a position in the lookbehind buffer
251
+ // pos == -2 points to lookbehind[lookbehind_size - 2]
252
+ let pos = -this._lookbehind_size;
253
+ let ch;
254
+
255
+ if (pos < 0) {
256
+ // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool
257
+ // search with character lookup code that considers both the
258
+ // lookbehind buffer and the current round's haystack data.
259
+ //
260
+ // Loop until
261
+ // there is a match.
262
+ // or until
263
+ // we've moved past the position that requires the
264
+ // lookbehind buffer. In this case we switch to the
265
+ // optimized loop.
266
+ // or until
267
+ // the character to look at lies outside the haystack.
268
+ while (pos < 0 && pos <= len - needleLength) {
269
+ ch = data[pos + needleLastCharIndex];
270
+
271
+ if (
272
+ ch === needleLastChar &&
273
+ this._sbmh_memcmp(data, pos, needleLastCharIndex)
274
+ ) {
275
+ this._lookbehind_size = 0;
276
+ ++this.matches;
277
+ this.emit('info', true);
278
+ return (this._bufpos = pos + needleLength)
279
+ }
280
+
281
+ pos += this._occ[ch];
282
+ }
283
+
284
+ // No match.
285
+
286
+ while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) {
287
+ // There's too few data for Boyer-Moore-Horspool to run,
288
+ // so let's use a different algorithm to skip as much as
289
+ // we can.
290
+ // Forward pos until
291
+ // the trailing part of lookbehind + data
292
+ // looks like the beginning of the needle
293
+ // or until
294
+ // pos == 0
295
+ ++pos;
296
+ }
297
+
298
+ if (pos >= 0) {
299
+ // Discard lookbehind buffer.
300
+ this.emit('info', false, this._lookbehind, 0, this._lookbehind_size);
301
+ this._lookbehind_size = 0;
302
+ } else {
303
+ // Cut off part of the lookbehind buffer that has
304
+ // been processed and append the entire haystack
305
+ // into it.
306
+ const bytesToCutOff = this._lookbehind_size + pos;
307
+ if (bytesToCutOff > 0) {
308
+ // The cut off data is guaranteed not to contain the needle.
309
+ this.emit('info', false, this._lookbehind, 0, bytesToCutOff);
310
+ }
311
+
312
+ this._lookbehind_size -= bytesToCutOff;
313
+ this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, this._lookbehind_size);
314
+
315
+ data.copy(this._lookbehind, this._lookbehind_size);
316
+ this._lookbehind_size += len;
317
+
318
+ this._bufpos = len;
319
+ return len
320
+ }
321
+ }
322
+
323
+ // Lookbehind buffer is now empty. We only need to check if the
324
+ // needle is in the haystack.
325
+ pos = data.indexOf(needle, pos + this._bufpos);
326
+
327
+ if (pos !== -1) {
328
+ ++this.matches;
329
+ if (pos === 0) { this.emit('info', true); } else { this.emit('info', true, data, this._bufpos, pos); }
330
+ return (this._bufpos = pos + needleLength)
331
+ }
332
+
333
+ pos = len - needleLastCharIndex;
334
+ if (pos < 0) {
335
+ pos = 0;
336
+ }
337
+
338
+ // There was no match. If there's trailing haystack data that we cannot
339
+ // match yet using the Boyer-Moore-Horspool algorithm (because the trailing
340
+ // data is less than the needle size) then match using a modified
341
+ // algorithm that starts matching from the beginning instead of the end.
342
+ // Whatever trailing data is left after running this algorithm is added to
343
+ // the lookbehind buffer.
344
+ while (
345
+ pos !== len &&
346
+ (
347
+ data[pos] !== needle[0] ||
348
+ Buffer.compare(
349
+ data.subarray(pos + 1, len),
350
+ needle.subarray(1, len - pos)
351
+ ) !== 0
352
+ )
353
+ ) {
354
+ ++pos;
355
+ }
356
+
357
+ if (pos !== len) {
358
+ data.copy(this._lookbehind, 0, pos, len);
359
+ this._lookbehind_size = len - pos;
360
+ }
361
+
362
+ // Everything until pos is guaranteed not to contain needle data.
363
+ if (pos !== 0) { this.emit('info', false, data, this._bufpos, pos); }
364
+
365
+ this._bufpos = len;
366
+ return len
367
+ };
368
+
369
+ SBMH.prototype._sbmh_lookup_char = function (data, pos) {
370
+ return pos < 0
371
+ ? this._lookbehind[this._lookbehind_size + pos]
372
+ : data[pos]
373
+ };
374
+
375
+ SBMH.prototype._sbmh_memcmp = function (data, pos, len) {
376
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
377
+ if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false }
378
+ }
379
+ return true
380
+ };
381
+
382
+ sbmh = SBMH;
383
+ return sbmh;
384
+ }
385
+
386
+ var PartStream_1;
387
+ var hasRequiredPartStream;
388
+
389
+ function requirePartStream () {
390
+ if (hasRequiredPartStream) return PartStream_1;
391
+ hasRequiredPartStream = 1;
392
+
393
+ const inherits = require$$1$1.inherits;
394
+ const ReadableStream = require$$0$1.Readable;
395
+
396
+ function PartStream (opts) {
397
+ ReadableStream.call(this, opts);
398
+ }
399
+ inherits(PartStream, ReadableStream);
400
+
401
+ PartStream.prototype._read = function (n) {};
402
+
403
+ PartStream_1 = PartStream;
404
+ return PartStream_1;
405
+ }
406
+
407
+ var getLimit;
408
+ var hasRequiredGetLimit;
409
+
410
+ function requireGetLimit () {
411
+ if (hasRequiredGetLimit) return getLimit;
412
+ hasRequiredGetLimit = 1;
413
+
414
+ getLimit = function getLimit (limits, name, defaultLimit) {
415
+ if (
416
+ !limits ||
417
+ limits[name] === undefined ||
418
+ limits[name] === null
419
+ ) { return defaultLimit }
420
+
421
+ if (
422
+ typeof limits[name] !== 'number' ||
423
+ isNaN(limits[name])
424
+ ) { throw new TypeError('Limit ' + name + ' is not a valid number') }
425
+
426
+ return limits[name]
427
+ };
428
+ return getLimit;
429
+ }
430
+
431
+ var HeaderParser_1;
432
+ var hasRequiredHeaderParser;
433
+
434
+ function requireHeaderParser () {
435
+ if (hasRequiredHeaderParser) return HeaderParser_1;
436
+ hasRequiredHeaderParser = 1;
437
+
438
+ const EventEmitter = require$$0.EventEmitter;
439
+ const inherits = require$$1$1.inherits;
440
+ const getLimit = requireGetLimit();
441
+
442
+ const StreamSearch = requireSbmh();
443
+
444
+ const B_DCRLF = Buffer.from('\r\n\r\n');
445
+ const RE_CRLF = /\r\n/g;
446
+ const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/; // eslint-disable-line no-control-regex
447
+
448
+ function HeaderParser (cfg) {
449
+ EventEmitter.call(this);
450
+
451
+ cfg = cfg || {};
452
+ const self = this;
453
+ this.nread = 0;
454
+ this.maxed = false;
455
+ this.npairs = 0;
456
+ this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000);
457
+ this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024);
458
+ this.buffer = '';
459
+ this.header = {};
460
+ this.finished = false;
461
+ this.ss = new StreamSearch(B_DCRLF);
462
+ this.ss.on('info', function (isMatch, data, start, end) {
463
+ if (data && !self.maxed) {
464
+ if (self.nread + end - start >= self.maxHeaderSize) {
465
+ end = self.maxHeaderSize - self.nread + start;
466
+ self.nread = self.maxHeaderSize;
467
+ self.maxed = true;
468
+ } else { self.nread += (end - start); }
469
+
470
+ self.buffer += data.toString('binary', start, end);
471
+ }
472
+ if (isMatch) { self._finish(); }
473
+ });
474
+ }
475
+ inherits(HeaderParser, EventEmitter);
476
+
477
+ HeaderParser.prototype.push = function (data) {
478
+ const r = this.ss.push(data);
479
+ if (this.finished) { return r }
480
+ };
481
+
482
+ HeaderParser.prototype.reset = function () {
483
+ this.finished = false;
484
+ this.buffer = '';
485
+ this.header = {};
486
+ this.ss.reset();
487
+ };
488
+
489
+ HeaderParser.prototype._finish = function () {
490
+ if (this.buffer) { this._parseHeader(); }
491
+ this.ss.matches = this.ss.maxMatches;
492
+ const header = this.header;
493
+ this.header = {};
494
+ this.buffer = '';
495
+ this.finished = true;
496
+ this.nread = this.npairs = 0;
497
+ this.maxed = false;
498
+ this.emit('header', header);
499
+ };
500
+
501
+ HeaderParser.prototype._parseHeader = function () {
502
+ if (this.npairs === this.maxHeaderPairs) { return }
503
+
504
+ const lines = this.buffer.split(RE_CRLF);
505
+ const len = lines.length;
506
+ let m, h;
507
+
508
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
509
+ if (lines[i].length === 0) { continue }
510
+ if (lines[i][0] === '\t' || lines[i][0] === ' ') {
511
+ // folded header content
512
+ // RFC2822 says to just remove the CRLF and not the whitespace following
513
+ // it, so we follow the RFC and include the leading whitespace ...
514
+ if (h) {
515
+ this.header[h][this.header[h].length - 1] += lines[i];
516
+ continue
517
+ }
518
+ }
519
+
520
+ const posColon = lines[i].indexOf(':');
521
+ if (
522
+ posColon === -1 ||
523
+ posColon === 0
524
+ ) {
525
+ return
526
+ }
527
+ m = RE_HDR.exec(lines[i]);
528
+ h = m[1].toLowerCase();
529
+ this.header[h] = this.header[h] || [];
530
+ this.header[h].push((m[2] || ''));
531
+ if (++this.npairs === this.maxHeaderPairs) { break }
532
+ }
533
+ };
534
+
535
+ HeaderParser_1 = HeaderParser;
536
+ return HeaderParser_1;
537
+ }
538
+
539
+ var Dicer_1;
540
+ var hasRequiredDicer;
541
+
542
+ function requireDicer () {
543
+ if (hasRequiredDicer) return Dicer_1;
544
+ hasRequiredDicer = 1;
545
+
546
+ const WritableStream = require$$0$1.Writable;
547
+ const inherits = require$$1$1.inherits;
548
+
549
+ const StreamSearch = requireSbmh();
550
+
551
+ const PartStream = requirePartStream();
552
+ const HeaderParser = requireHeaderParser();
553
+
554
+ const DASH = 45;
555
+ const B_ONEDASH = Buffer.from('-');
556
+ const B_CRLF = Buffer.from('\r\n');
557
+ const EMPTY_FN = function () {};
558
+
559
+ function Dicer (cfg) {
560
+ if (!(this instanceof Dicer)) { return new Dicer(cfg) }
561
+ WritableStream.call(this, cfg);
562
+
563
+ if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') }
564
+
565
+ if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary); } else { this._bparser = undefined; }
566
+
567
+ this._headerFirst = cfg.headerFirst;
568
+
569
+ this._dashes = 0;
570
+ this._parts = 0;
571
+ this._finished = false;
572
+ this._realFinish = false;
573
+ this._isPreamble = true;
574
+ this._justMatched = false;
575
+ this._firstWrite = true;
576
+ this._inHeader = true;
577
+ this._part = undefined;
578
+ this._cb = undefined;
579
+ this._ignoreData = false;
580
+ this._partOpts = { highWaterMark: cfg.partHwm };
581
+ this._pause = false;
582
+
583
+ const self = this;
584
+ this._hparser = new HeaderParser(cfg);
585
+ this._hparser.on('header', function (header) {
586
+ self._inHeader = false;
587
+ self._part.emit('header', header);
588
+ });
589
+ }
590
+ inherits(Dicer, WritableStream);
591
+
592
+ Dicer.prototype.emit = function (ev) {
593
+ if (ev === 'finish' && !this._realFinish) {
594
+ if (!this._finished) {
595
+ const self = this;
596
+ process.nextTick(function () {
597
+ self.emit('error', new Error('Unexpected end of multipart data'));
598
+ if (self._part && !self._ignoreData) {
599
+ const type = (self._isPreamble ? 'Preamble' : 'Part');
600
+ self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data'));
601
+ self._part.push(null);
602
+ process.nextTick(function () {
603
+ self._realFinish = true;
604
+ self.emit('finish');
605
+ self._realFinish = false;
606
+ });
607
+ return
608
+ }
609
+ self._realFinish = true;
610
+ self.emit('finish');
611
+ self._realFinish = false;
612
+ });
613
+ }
614
+ } else { WritableStream.prototype.emit.apply(this, arguments); }
615
+ };
616
+
617
+ Dicer.prototype._write = function (data, encoding, cb) {
618
+ // ignore unexpected data (e.g. extra trailer data after finished)
619
+ if (!this._hparser && !this._bparser) { return cb() }
620
+
621
+ if (this._headerFirst && this._isPreamble) {
622
+ if (!this._part) {
623
+ this._part = new PartStream(this._partOpts);
624
+ if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part); } else { this._ignore(); }
625
+ }
626
+ const r = this._hparser.push(data);
627
+ if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r); } else { return cb() }
628
+ }
629
+
630
+ // allows for "easier" testing
631
+ if (this._firstWrite) {
632
+ this._bparser.push(B_CRLF);
633
+ this._firstWrite = false;
634
+ }
635
+
636
+ this._bparser.push(data);
637
+
638
+ if (this._pause) { this._cb = cb; } else { cb(); }
639
+ };
640
+
641
+ Dicer.prototype.reset = function () {
642
+ this._part = undefined;
643
+ this._bparser = undefined;
644
+ this._hparser = undefined;
645
+ };
646
+
647
+ Dicer.prototype.setBoundary = function (boundary) {
648
+ const self = this;
649
+ this._bparser = new StreamSearch('\r\n--' + boundary);
650
+ this._bparser.on('info', function (isMatch, data, start, end) {
651
+ self._oninfo(isMatch, data, start, end);
652
+ });
653
+ };
654
+
655
+ Dicer.prototype._ignore = function () {
656
+ if (this._part && !this._ignoreData) {
657
+ this._ignoreData = true;
658
+ this._part.on('error', EMPTY_FN);
659
+ // we must perform some kind of read on the stream even though we are
660
+ // ignoring the data, otherwise node's Readable stream will not emit 'end'
661
+ // after pushing null to the stream
662
+ this._part.resume();
663
+ }
664
+ };
665
+
666
+ Dicer.prototype._oninfo = function (isMatch, data, start, end) {
667
+ let buf; const self = this; let i = 0; let r; let shouldWriteMore = true;
668
+
669
+ if (!this._part && this._justMatched && data) {
670
+ while (this._dashes < 2 && (start + i) < end) {
671
+ if (data[start + i] === DASH) {
672
+ ++i;
673
+ ++this._dashes;
674
+ } else {
675
+ if (this._dashes) { buf = B_ONEDASH; }
676
+ this._dashes = 0;
677
+ break
678
+ }
679
+ }
680
+ if (this._dashes === 2) {
681
+ if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)); }
682
+ this.reset();
683
+ this._finished = true;
684
+ // no more parts will be added
685
+ if (self._parts === 0) {
686
+ self._realFinish = true;
687
+ self.emit('finish');
688
+ self._realFinish = false;
689
+ }
690
+ }
691
+ if (this._dashes) { return }
692
+ }
693
+ if (this._justMatched) { this._justMatched = false; }
694
+ if (!this._part) {
695
+ this._part = new PartStream(this._partOpts);
696
+ this._part._read = function (n) {
697
+ self._unpause();
698
+ };
699
+ if (this._isPreamble && this.listenerCount('preamble') !== 0) {
700
+ this.emit('preamble', this._part);
701
+ } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) {
702
+ this.emit('part', this._part);
703
+ } else {
704
+ this._ignore();
705
+ }
706
+ if (!this._isPreamble) { this._inHeader = true; }
707
+ }
708
+ if (data && start < end && !this._ignoreData) {
709
+ if (this._isPreamble || !this._inHeader) {
710
+ if (buf) { shouldWriteMore = this._part.push(buf); }
711
+ shouldWriteMore = this._part.push(data.slice(start, end));
712
+ if (!shouldWriteMore) { this._pause = true; }
713
+ } else if (!this._isPreamble && this._inHeader) {
714
+ if (buf) { this._hparser.push(buf); }
715
+ r = this._hparser.push(data.slice(start, end));
716
+ if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end); }
717
+ }
718
+ }
719
+ if (isMatch) {
720
+ this._hparser.reset();
721
+ if (this._isPreamble) { this._isPreamble = false; } else {
722
+ if (start !== end) {
723
+ ++this._parts;
724
+ this._part.on('end', function () {
725
+ if (--self._parts === 0) {
726
+ if (self._finished) {
727
+ self._realFinish = true;
728
+ self.emit('finish');
729
+ self._realFinish = false;
730
+ } else {
731
+ self._unpause();
732
+ }
733
+ }
734
+ });
735
+ }
736
+ }
737
+ this._part.push(null);
738
+ this._part = undefined;
739
+ this._ignoreData = false;
740
+ this._justMatched = true;
741
+ this._dashes = 0;
742
+ }
743
+ };
744
+
745
+ Dicer.prototype._unpause = function () {
746
+ if (!this._pause) { return }
747
+
748
+ this._pause = false;
749
+ if (this._cb) {
750
+ const cb = this._cb;
751
+ this._cb = undefined;
752
+ cb();
753
+ }
754
+ };
755
+
756
+ Dicer_1 = Dicer;
757
+ return Dicer_1;
758
+ }
759
+
760
+ var decodeText_1;
761
+ var hasRequiredDecodeText;
762
+
763
+ function requireDecodeText () {
764
+ if (hasRequiredDecodeText) return decodeText_1;
765
+ hasRequiredDecodeText = 1;
766
+
767
+ // Node has always utf-8
768
+ const utf8Decoder = new TextDecoder('utf-8');
769
+ const textDecoders = new Map([
770
+ ['utf-8', utf8Decoder],
771
+ ['utf8', utf8Decoder]
772
+ ]);
773
+
774
+ function getDecoder (charset) {
775
+ let lc;
776
+ while (true) {
777
+ switch (charset) {
778
+ case 'utf-8':
779
+ case 'utf8':
780
+ return decoders.utf8
781
+ case 'latin1':
782
+ case 'ascii': // TODO: Make these a separate, strict decoder?
783
+ case 'us-ascii':
784
+ case 'iso-8859-1':
785
+ case 'iso8859-1':
786
+ case 'iso88591':
787
+ case 'iso_8859-1':
788
+ case 'windows-1252':
789
+ case 'iso_8859-1:1987':
790
+ case 'cp1252':
791
+ case 'x-cp1252':
792
+ return decoders.latin1
793
+ case 'utf16le':
794
+ case 'utf-16le':
795
+ case 'ucs2':
796
+ case 'ucs-2':
797
+ return decoders.utf16le
798
+ case 'base64':
799
+ return decoders.base64
800
+ default:
801
+ if (lc === undefined) {
802
+ lc = true;
803
+ charset = charset.toLowerCase();
804
+ continue
805
+ }
806
+ return decoders.other.bind(charset)
807
+ }
808
+ }
809
+ }
810
+
811
+ const decoders = {
812
+ utf8: (data, sourceEncoding) => {
813
+ if (data.length === 0) {
814
+ return ''
815
+ }
816
+ if (typeof data === 'string') {
817
+ data = Buffer.from(data, sourceEncoding);
818
+ }
819
+ return data.utf8Slice(0, data.length)
820
+ },
821
+
822
+ latin1: (data, sourceEncoding) => {
823
+ if (data.length === 0) {
824
+ return ''
825
+ }
826
+ if (typeof data === 'string') {
827
+ return data
828
+ }
829
+ return data.latin1Slice(0, data.length)
830
+ },
831
+
832
+ utf16le: (data, sourceEncoding) => {
833
+ if (data.length === 0) {
834
+ return ''
835
+ }
836
+ if (typeof data === 'string') {
837
+ data = Buffer.from(data, sourceEncoding);
838
+ }
839
+ return data.ucs2Slice(0, data.length)
840
+ },
841
+
842
+ base64: (data, sourceEncoding) => {
843
+ if (data.length === 0) {
844
+ return ''
845
+ }
846
+ if (typeof data === 'string') {
847
+ data = Buffer.from(data, sourceEncoding);
848
+ }
849
+ return data.base64Slice(0, data.length)
850
+ },
851
+
852
+ other: (data, sourceEncoding) => {
853
+ if (data.length === 0) {
854
+ return ''
855
+ }
856
+ if (typeof data === 'string') {
857
+ data = Buffer.from(data, sourceEncoding);
858
+ }
859
+
860
+ if (textDecoders.has(this.toString())) {
861
+ try {
862
+ return textDecoders.get(this).decode(data)
863
+ } catch {}
864
+ }
865
+ return typeof data === 'string'
866
+ ? data
867
+ : data.toString()
868
+ }
869
+ };
870
+
871
+ function decodeText (text, sourceEncoding, destEncoding) {
872
+ if (text) {
873
+ return getDecoder(destEncoding)(text, sourceEncoding)
874
+ }
875
+ return text
876
+ }
877
+
878
+ decodeText_1 = decodeText;
879
+ return decodeText_1;
880
+ }
881
+
882
+ /* eslint-disable object-property-newline */
883
+
884
+ var parseParams_1;
885
+ var hasRequiredParseParams;
886
+
887
+ function requireParseParams () {
888
+ if (hasRequiredParseParams) return parseParams_1;
889
+ hasRequiredParseParams = 1;
890
+
891
+ const decodeText = requireDecodeText();
892
+
893
+ const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g;
894
+
895
+ const EncodedLookup = {
896
+ '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04',
897
+ '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09',
898
+ '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c',
899
+ '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e',
900
+ '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12',
901
+ '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17',
902
+ '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b',
903
+ '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d',
904
+ '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20',
905
+ '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25',
906
+ '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a',
907
+ '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c',
908
+ '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f',
909
+ '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33',
910
+ '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38',
911
+ '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b',
912
+ '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e',
913
+ '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41',
914
+ '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46',
915
+ '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a',
916
+ '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d',
917
+ '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f',
918
+ '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54',
919
+ '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59',
920
+ '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c',
921
+ '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e',
922
+ '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62',
923
+ '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67',
924
+ '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b',
925
+ '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d',
926
+ '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70',
927
+ '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75',
928
+ '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a',
929
+ '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c',
930
+ '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f',
931
+ '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83',
932
+ '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88',
933
+ '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b',
934
+ '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e',
935
+ '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91',
936
+ '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96',
937
+ '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a',
938
+ '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d',
939
+ '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f',
940
+ '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2',
941
+ '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4',
942
+ '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7',
943
+ '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9',
944
+ '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab',
945
+ '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac',
946
+ '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad',
947
+ '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae',
948
+ '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0',
949
+ '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2',
950
+ '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5',
951
+ '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7',
952
+ '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba',
953
+ '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb',
954
+ '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc',
955
+ '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd',
956
+ '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf',
957
+ '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0',
958
+ '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3',
959
+ '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5',
960
+ '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8',
961
+ '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca',
962
+ '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb',
963
+ '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc',
964
+ '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce',
965
+ '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf',
966
+ '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1',
967
+ '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3',
968
+ '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6',
969
+ '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8',
970
+ '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda',
971
+ '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb',
972
+ '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd',
973
+ '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde',
974
+ '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf',
975
+ '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1',
976
+ '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4',
977
+ '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6',
978
+ '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9',
979
+ '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea',
980
+ '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec',
981
+ '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed',
982
+ '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee',
983
+ '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef',
984
+ '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2',
985
+ '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4',
986
+ '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7',
987
+ '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9',
988
+ '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb',
989
+ '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc',
990
+ '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd',
991
+ '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe',
992
+ '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff'
993
+ };
994
+
995
+ function encodedReplacer (match) {
996
+ return EncodedLookup[match]
997
+ }
998
+
999
+ const STATE_KEY = 0;
1000
+ const STATE_VALUE = 1;
1001
+ const STATE_CHARSET = 2;
1002
+ const STATE_LANG = 3;
1003
+
1004
+ function parseParams (str) {
1005
+ const res = [];
1006
+ let state = STATE_KEY;
1007
+ let charset = '';
1008
+ let inquote = false;
1009
+ let escaping = false;
1010
+ let p = 0;
1011
+ let tmp = '';
1012
+ const len = str.length;
1013
+
1014
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
1015
+ const char = str[i];
1016
+ if (char === '\\' && inquote) {
1017
+ if (escaping) { escaping = false; } else {
1018
+ escaping = true;
1019
+ continue
1020
+ }
1021
+ } else if (char === '"') {
1022
+ if (!escaping) {
1023
+ if (inquote) {
1024
+ inquote = false;
1025
+ state = STATE_KEY;
1026
+ } else { inquote = true; }
1027
+ continue
1028
+ } else { escaping = false; }
1029
+ } else {
1030
+ if (escaping && inquote) { tmp += '\\'; }
1031
+ escaping = false;
1032
+ if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") {
1033
+ if (state === STATE_CHARSET) {
1034
+ state = STATE_LANG;
1035
+ charset = tmp.substring(1);
1036
+ } else { state = STATE_VALUE; }
1037
+ tmp = '';
1038
+ continue
1039
+ } else if (state === STATE_KEY &&
1040
+ (char === '*' || char === '=') &&
1041
+ res.length) {
1042
+ state = char === '*'
1043
+ ? STATE_CHARSET
1044
+ : STATE_VALUE;
1045
+ res[p] = [tmp, undefined];
1046
+ tmp = '';
1047
+ continue
1048
+ } else if (!inquote && char === ';') {
1049
+ state = STATE_KEY;
1050
+ if (charset) {
1051
+ if (tmp.length) {
1052
+ tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
1053
+ 'binary',
1054
+ charset);
1055
+ }
1056
+ charset = '';
1057
+ } else if (tmp.length) {
1058
+ tmp = decodeText(tmp, 'binary', 'utf8');
1059
+ }
1060
+ if (res[p] === undefined) { res[p] = tmp; } else { res[p][1] = tmp; }
1061
+ tmp = '';
1062
+ ++p;
1063
+ continue
1064
+ } else if (!inquote && (char === ' ' || char === '\t')) { continue }
1065
+ }
1066
+ tmp += char;
1067
+ }
1068
+ if (charset && tmp.length) {
1069
+ tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
1070
+ 'binary',
1071
+ charset);
1072
+ } else if (tmp) {
1073
+ tmp = decodeText(tmp, 'binary', 'utf8');
1074
+ }
1075
+
1076
+ if (res[p] === undefined) {
1077
+ if (tmp) { res[p] = tmp; }
1078
+ } else { res[p][1] = tmp; }
1079
+
1080
+ return res
1081
+ }
1082
+
1083
+ parseParams_1 = parseParams;
1084
+ return parseParams_1;
1085
+ }
1086
+
1087
+ var basename;
1088
+ var hasRequiredBasename;
1089
+
1090
+ function requireBasename () {
1091
+ if (hasRequiredBasename) return basename;
1092
+ hasRequiredBasename = 1;
1093
+
1094
+ basename = function basename (path) {
1095
+ if (typeof path !== 'string') { return '' }
1096
+ for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var
1097
+ switch (path.charCodeAt(i)) {
1098
+ case 0x2F: // '/'
1099
+ case 0x5C: // '\'
1100
+ path = path.slice(i + 1);
1101
+ return (path === '..' || path === '.' ? '' : path)
1102
+ }
1103
+ }
1104
+ return (path === '..' || path === '.' ? '' : path)
1105
+ };
1106
+ return basename;
1107
+ }
1108
+
1109
+ var multipart;
1110
+ var hasRequiredMultipart;
1111
+
1112
+ function requireMultipart () {
1113
+ if (hasRequiredMultipart) return multipart;
1114
+ hasRequiredMultipart = 1;
1115
+
1116
+ // TODO:
1117
+ // * support 1 nested multipart level
1118
+ // (see second multipart example here:
1119
+ // http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data)
1120
+ // * support limits.fieldNameSize
1121
+ // -- this will require modifications to utils.parseParams
1122
+
1123
+ const { Readable } = require$$0$1;
1124
+ const { inherits } = require$$1$1;
1125
+
1126
+ const Dicer = requireDicer();
1127
+
1128
+ const parseParams = requireParseParams();
1129
+ const decodeText = requireDecodeText();
1130
+ const basename = requireBasename();
1131
+ const getLimit = requireGetLimit();
1132
+
1133
+ const RE_BOUNDARY = /^boundary$/i;
1134
+ const RE_FIELD = /^form-data$/i;
1135
+ const RE_CHARSET = /^charset$/i;
1136
+ const RE_FILENAME = /^filename$/i;
1137
+ const RE_NAME = /^name$/i;
1138
+
1139
+ Multipart.detect = /^multipart\/form-data/i;
1140
+ function Multipart (boy, cfg) {
1141
+ let i;
1142
+ let len;
1143
+ const self = this;
1144
+ let boundary;
1145
+ const limits = cfg.limits;
1146
+ const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined));
1147
+ const parsedConType = cfg.parsedConType || [];
1148
+ const defCharset = cfg.defCharset || 'utf8';
1149
+ const preservePath = cfg.preservePath;
1150
+ const fileOpts = { highWaterMark: cfg.fileHwm };
1151
+
1152
+ for (i = 0, len = parsedConType.length; i < len; ++i) {
1153
+ if (Array.isArray(parsedConType[i]) &&
1154
+ RE_BOUNDARY.test(parsedConType[i][0])) {
1155
+ boundary = parsedConType[i][1];
1156
+ break
1157
+ }
1158
+ }
1159
+
1160
+ function checkFinished () {
1161
+ if (nends === 0 && finished && !boy._done) {
1162
+ finished = false;
1163
+ self.end();
1164
+ }
1165
+ }
1166
+
1167
+ if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') }
1168
+
1169
+ const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024);
1170
+ const fileSizeLimit = getLimit(limits, 'fileSize', Infinity);
1171
+ const filesLimit = getLimit(limits, 'files', Infinity);
1172
+ const fieldsLimit = getLimit(limits, 'fields', Infinity);
1173
+ const partsLimit = getLimit(limits, 'parts', Infinity);
1174
+ const headerPairsLimit = getLimit(limits, 'headerPairs', 2000);
1175
+ const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024);
1176
+
1177
+ let nfiles = 0;
1178
+ let nfields = 0;
1179
+ let nends = 0;
1180
+ let curFile;
1181
+ let curField;
1182
+ let finished = false;
1183
+
1184
+ this._needDrain = false;
1185
+ this._pause = false;
1186
+ this._cb = undefined;
1187
+ this._nparts = 0;
1188
+ this._boy = boy;
1189
+
1190
+ const parserCfg = {
1191
+ boundary,
1192
+ maxHeaderPairs: headerPairsLimit,
1193
+ maxHeaderSize: headerSizeLimit,
1194
+ partHwm: fileOpts.highWaterMark,
1195
+ highWaterMark: cfg.highWaterMark
1196
+ };
1197
+
1198
+ this.parser = new Dicer(parserCfg);
1199
+ this.parser.on('drain', function () {
1200
+ self._needDrain = false;
1201
+ if (self._cb && !self._pause) {
1202
+ const cb = self._cb;
1203
+ self._cb = undefined;
1204
+ cb();
1205
+ }
1206
+ }).on('part', function onPart (part) {
1207
+ if (++self._nparts > partsLimit) {
1208
+ self.parser.removeListener('part', onPart);
1209
+ self.parser.on('part', skipPart);
1210
+ boy.hitPartsLimit = true;
1211
+ boy.emit('partsLimit');
1212
+ return skipPart(part)
1213
+ }
1214
+
1215
+ // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let
1216
+ // us emit 'end' early since we know the part has ended if we are already
1217
+ // seeing the next part
1218
+ if (curField) {
1219
+ const field = curField;
1220
+ field.emit('end');
1221
+ field.removeAllListeners('end');
1222
+ }
1223
+
1224
+ part.on('header', function (header) {
1225
+ let contype;
1226
+ let fieldname;
1227
+ let parsed;
1228
+ let charset;
1229
+ let encoding;
1230
+ let filename;
1231
+ let nsize = 0;
1232
+
1233
+ if (header['content-type']) {
1234
+ parsed = parseParams(header['content-type'][0]);
1235
+ if (parsed[0]) {
1236
+ contype = parsed[0].toLowerCase();
1237
+ for (i = 0, len = parsed.length; i < len; ++i) {
1238
+ if (RE_CHARSET.test(parsed[i][0])) {
1239
+ charset = parsed[i][1].toLowerCase();
1240
+ break
1241
+ }
1242
+ }
1243
+ }
1244
+ }
1245
+
1246
+ if (contype === undefined) { contype = 'text/plain'; }
1247
+ if (charset === undefined) { charset = defCharset; }
1248
+
1249
+ if (header['content-disposition']) {
1250
+ parsed = parseParams(header['content-disposition'][0]);
1251
+ if (!RE_FIELD.test(parsed[0])) { return skipPart(part) }
1252
+ for (i = 0, len = parsed.length; i < len; ++i) {
1253
+ if (RE_NAME.test(parsed[i][0])) {
1254
+ fieldname = parsed[i][1];
1255
+ } else if (RE_FILENAME.test(parsed[i][0])) {
1256
+ filename = parsed[i][1];
1257
+ if (!preservePath) { filename = basename(filename); }
1258
+ }
1259
+ }
1260
+ } else { return skipPart(part) }
1261
+
1262
+ if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase(); } else { encoding = '7bit'; }
1263
+
1264
+ let onData,
1265
+ onEnd;
1266
+
1267
+ if (isPartAFile(fieldname, contype, filename)) {
1268
+ // file/binary field
1269
+ if (nfiles === filesLimit) {
1270
+ if (!boy.hitFilesLimit) {
1271
+ boy.hitFilesLimit = true;
1272
+ boy.emit('filesLimit');
1273
+ }
1274
+ return skipPart(part)
1275
+ }
1276
+
1277
+ ++nfiles;
1278
+
1279
+ if (boy.listenerCount('file') === 0) {
1280
+ self.parser._ignore();
1281
+ return
1282
+ }
1283
+
1284
+ ++nends;
1285
+ const file = new FileStream(fileOpts);
1286
+ curFile = file;
1287
+ file.on('end', function () {
1288
+ --nends;
1289
+ self._pause = false;
1290
+ checkFinished();
1291
+ if (self._cb && !self._needDrain) {
1292
+ const cb = self._cb;
1293
+ self._cb = undefined;
1294
+ cb();
1295
+ }
1296
+ });
1297
+ file._read = function (n) {
1298
+ if (!self._pause) { return }
1299
+ self._pause = false;
1300
+ if (self._cb && !self._needDrain) {
1301
+ const cb = self._cb;
1302
+ self._cb = undefined;
1303
+ cb();
1304
+ }
1305
+ };
1306
+ boy.emit('file', fieldname, file, filename, encoding, contype);
1307
+
1308
+ onData = function (data) {
1309
+ if ((nsize += data.length) > fileSizeLimit) {
1310
+ const extralen = fileSizeLimit - nsize + data.length;
1311
+ if (extralen > 0) { file.push(data.slice(0, extralen)); }
1312
+ file.truncated = true;
1313
+ file.bytesRead = fileSizeLimit;
1314
+ part.removeAllListeners('data');
1315
+ file.emit('limit');
1316
+ return
1317
+ } else if (!file.push(data)) { self._pause = true; }
1318
+
1319
+ file.bytesRead = nsize;
1320
+ };
1321
+
1322
+ onEnd = function () {
1323
+ curFile = undefined;
1324
+ file.push(null);
1325
+ };
1326
+ } else {
1327
+ // non-file field
1328
+ if (nfields === fieldsLimit) {
1329
+ if (!boy.hitFieldsLimit) {
1330
+ boy.hitFieldsLimit = true;
1331
+ boy.emit('fieldsLimit');
1332
+ }
1333
+ return skipPart(part)
1334
+ }
1335
+
1336
+ ++nfields;
1337
+ ++nends;
1338
+ let buffer = '';
1339
+ let truncated = false;
1340
+ curField = part;
1341
+
1342
+ onData = function (data) {
1343
+ if ((nsize += data.length) > fieldSizeLimit) {
1344
+ const extralen = (fieldSizeLimit - (nsize - data.length));
1345
+ buffer += data.toString('binary', 0, extralen);
1346
+ truncated = true;
1347
+ part.removeAllListeners('data');
1348
+ } else { buffer += data.toString('binary'); }
1349
+ };
1350
+
1351
+ onEnd = function () {
1352
+ curField = undefined;
1353
+ if (buffer.length) { buffer = decodeText(buffer, 'binary', charset); }
1354
+ boy.emit('field', fieldname, buffer, false, truncated, encoding, contype);
1355
+ --nends;
1356
+ checkFinished();
1357
+ };
1358
+ }
1359
+
1360
+ /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become
1361
+ broken. Streams2/streams3 is a huge black box of confusion, but
1362
+ somehow overriding the sync state seems to fix things again (and still
1363
+ seems to work for previous node versions).
1364
+ */
1365
+ part._readableState.sync = false;
1366
+
1367
+ part.on('data', onData);
1368
+ part.on('end', onEnd);
1369
+ }).on('error', function (err) {
1370
+ if (curFile) { curFile.emit('error', err); }
1371
+ });
1372
+ }).on('error', function (err) {
1373
+ boy.emit('error', err);
1374
+ }).on('finish', function () {
1375
+ finished = true;
1376
+ checkFinished();
1377
+ });
1378
+ }
1379
+
1380
+ Multipart.prototype.write = function (chunk, cb) {
1381
+ const r = this.parser.write(chunk);
1382
+ if (r && !this._pause) {
1383
+ cb();
1384
+ } else {
1385
+ this._needDrain = !r;
1386
+ this._cb = cb;
1387
+ }
1388
+ };
1389
+
1390
+ Multipart.prototype.end = function () {
1391
+ const self = this;
1392
+
1393
+ if (self.parser.writable) {
1394
+ self.parser.end();
1395
+ } else if (!self._boy._done) {
1396
+ process.nextTick(function () {
1397
+ self._boy._done = true;
1398
+ self._boy.emit('finish');
1399
+ });
1400
+ }
1401
+ };
1402
+
1403
+ function skipPart (part) {
1404
+ part.resume();
1405
+ }
1406
+
1407
+ function FileStream (opts) {
1408
+ Readable.call(this, opts);
1409
+
1410
+ this.bytesRead = 0;
1411
+
1412
+ this.truncated = false;
1413
+ }
1414
+
1415
+ inherits(FileStream, Readable);
1416
+
1417
+ FileStream.prototype._read = function (n) {};
1418
+
1419
+ multipart = Multipart;
1420
+ return multipart;
1421
+ }
1422
+
1423
+ var Decoder_1;
1424
+ var hasRequiredDecoder;
1425
+
1426
+ function requireDecoder () {
1427
+ if (hasRequiredDecoder) return Decoder_1;
1428
+ hasRequiredDecoder = 1;
1429
+
1430
+ const RE_PLUS = /\+/g;
1431
+
1432
+ const HEX = [
1433
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1434
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1435
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1436
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
1437
+ 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1438
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1439
+ 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1440
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1441
+ ];
1442
+
1443
+ function Decoder () {
1444
+ this.buffer = undefined;
1445
+ }
1446
+ Decoder.prototype.write = function (str) {
1447
+ // Replace '+' with ' ' before decoding
1448
+ str = str.replace(RE_PLUS, ' ');
1449
+ let res = '';
1450
+ let i = 0; let p = 0; const len = str.length;
1451
+ for (; i < len; ++i) {
1452
+ if (this.buffer !== undefined) {
1453
+ if (!HEX[str.charCodeAt(i)]) {
1454
+ res += '%' + this.buffer;
1455
+ this.buffer = undefined;
1456
+ --i; // retry character
1457
+ } else {
1458
+ this.buffer += str[i];
1459
+ ++p;
1460
+ if (this.buffer.length === 2) {
1461
+ res += String.fromCharCode(parseInt(this.buffer, 16));
1462
+ this.buffer = undefined;
1463
+ }
1464
+ }
1465
+ } else if (str[i] === '%') {
1466
+ if (i > p) {
1467
+ res += str.substring(p, i);
1468
+ p = i;
1469
+ }
1470
+ this.buffer = '';
1471
+ ++p;
1472
+ }
1473
+ }
1474
+ if (p < len && this.buffer === undefined) { res += str.substring(p); }
1475
+ return res
1476
+ };
1477
+ Decoder.prototype.reset = function () {
1478
+ this.buffer = undefined;
1479
+ };
1480
+
1481
+ Decoder_1 = Decoder;
1482
+ return Decoder_1;
1483
+ }
1484
+
1485
+ var urlencoded;
1486
+ var hasRequiredUrlencoded;
1487
+
1488
+ function requireUrlencoded () {
1489
+ if (hasRequiredUrlencoded) return urlencoded;
1490
+ hasRequiredUrlencoded = 1;
1491
+
1492
+ const Decoder = requireDecoder();
1493
+ const decodeText = requireDecodeText();
1494
+ const getLimit = requireGetLimit();
1495
+
1496
+ const RE_CHARSET = /^charset$/i;
1497
+
1498
+ UrlEncoded.detect = /^application\/x-www-form-urlencoded/i;
1499
+ function UrlEncoded (boy, cfg) {
1500
+ const limits = cfg.limits;
1501
+ const parsedConType = cfg.parsedConType;
1502
+ this.boy = boy;
1503
+
1504
+ this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024);
1505
+ this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100);
1506
+ this.fieldsLimit = getLimit(limits, 'fields', Infinity);
1507
+
1508
+ let charset;
1509
+ for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var
1510
+ if (Array.isArray(parsedConType[i]) &&
1511
+ RE_CHARSET.test(parsedConType[i][0])) {
1512
+ charset = parsedConType[i][1].toLowerCase();
1513
+ break
1514
+ }
1515
+ }
1516
+
1517
+ if (charset === undefined) { charset = cfg.defCharset || 'utf8'; }
1518
+
1519
+ this.decoder = new Decoder();
1520
+ this.charset = charset;
1521
+ this._fields = 0;
1522
+ this._state = 'key';
1523
+ this._checkingBytes = true;
1524
+ this._bytesKey = 0;
1525
+ this._bytesVal = 0;
1526
+ this._key = '';
1527
+ this._val = '';
1528
+ this._keyTrunc = false;
1529
+ this._valTrunc = false;
1530
+ this._hitLimit = false;
1531
+ }
1532
+
1533
+ UrlEncoded.prototype.write = function (data, cb) {
1534
+ if (this._fields === this.fieldsLimit) {
1535
+ if (!this.boy.hitFieldsLimit) {
1536
+ this.boy.hitFieldsLimit = true;
1537
+ this.boy.emit('fieldsLimit');
1538
+ }
1539
+ return cb()
1540
+ }
1541
+
1542
+ let idxeq; let idxamp; let i; let p = 0; const len = data.length;
1543
+
1544
+ while (p < len) {
1545
+ if (this._state === 'key') {
1546
+ idxeq = idxamp = undefined;
1547
+ for (i = p; i < len; ++i) {
1548
+ if (!this._checkingBytes) { ++p; }
1549
+ if (data[i] === 0x3D/* = */) {
1550
+ idxeq = i;
1551
+ break
1552
+ } else if (data[i] === 0x26/* & */) {
1553
+ idxamp = i;
1554
+ break
1555
+ }
1556
+ if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) {
1557
+ this._hitLimit = true;
1558
+ break
1559
+ } else if (this._checkingBytes) { ++this._bytesKey; }
1560
+ }
1561
+
1562
+ if (idxeq !== undefined) {
1563
+ // key with assignment
1564
+ if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)); }
1565
+ this._state = 'val';
1566
+
1567
+ this._hitLimit = false;
1568
+ this._checkingBytes = true;
1569
+ this._val = '';
1570
+ this._bytesVal = 0;
1571
+ this._valTrunc = false;
1572
+ this.decoder.reset();
1573
+
1574
+ p = idxeq + 1;
1575
+ } else if (idxamp !== undefined) {
1576
+ // key with no assignment
1577
+ ++this._fields;
1578
+ let key; const keyTrunc = this._keyTrunc;
1579
+ if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))); } else { key = this._key; }
1580
+
1581
+ this._hitLimit = false;
1582
+ this._checkingBytes = true;
1583
+ this._key = '';
1584
+ this._bytesKey = 0;
1585
+ this._keyTrunc = false;
1586
+ this.decoder.reset();
1587
+
1588
+ if (key.length) {
1589
+ this.boy.emit('field', decodeText(key, 'binary', this.charset),
1590
+ '',
1591
+ keyTrunc,
1592
+ false);
1593
+ }
1594
+
1595
+ p = idxamp + 1;
1596
+ if (this._fields === this.fieldsLimit) { return cb() }
1597
+ } else if (this._hitLimit) {
1598
+ // we may not have hit the actual limit if there are encoded bytes...
1599
+ if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)); }
1600
+ p = i;
1601
+ if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) {
1602
+ // yep, we actually did hit the limit
1603
+ this._checkingBytes = false;
1604
+ this._keyTrunc = true;
1605
+ }
1606
+ } else {
1607
+ if (p < len) { this._key += this.decoder.write(data.toString('binary', p)); }
1608
+ p = len;
1609
+ }
1610
+ } else {
1611
+ idxamp = undefined;
1612
+ for (i = p; i < len; ++i) {
1613
+ if (!this._checkingBytes) { ++p; }
1614
+ if (data[i] === 0x26/* & */) {
1615
+ idxamp = i;
1616
+ break
1617
+ }
1618
+ if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) {
1619
+ this._hitLimit = true;
1620
+ break
1621
+ } else if (this._checkingBytes) { ++this._bytesVal; }
1622
+ }
1623
+
1624
+ if (idxamp !== undefined) {
1625
+ ++this._fields;
1626
+ if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)); }
1627
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
1628
+ decodeText(this._val, 'binary', this.charset),
1629
+ this._keyTrunc,
1630
+ this._valTrunc);
1631
+ this._state = 'key';
1632
+
1633
+ this._hitLimit = false;
1634
+ this._checkingBytes = true;
1635
+ this._key = '';
1636
+ this._bytesKey = 0;
1637
+ this._keyTrunc = false;
1638
+ this.decoder.reset();
1639
+
1640
+ p = idxamp + 1;
1641
+ if (this._fields === this.fieldsLimit) { return cb() }
1642
+ } else if (this._hitLimit) {
1643
+ // we may not have hit the actual limit if there are encoded bytes...
1644
+ if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)); }
1645
+ p = i;
1646
+ if ((this._val === '' && this.fieldSizeLimit === 0) ||
1647
+ (this._bytesVal = this._val.length) === this.fieldSizeLimit) {
1648
+ // yep, we actually did hit the limit
1649
+ this._checkingBytes = false;
1650
+ this._valTrunc = true;
1651
+ }
1652
+ } else {
1653
+ if (p < len) { this._val += this.decoder.write(data.toString('binary', p)); }
1654
+ p = len;
1655
+ }
1656
+ }
1657
+ }
1658
+ cb();
1659
+ };
1660
+
1661
+ UrlEncoded.prototype.end = function () {
1662
+ if (this.boy._done) { return }
1663
+
1664
+ if (this._state === 'key' && this._key.length > 0) {
1665
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
1666
+ '',
1667
+ this._keyTrunc,
1668
+ false);
1669
+ } else if (this._state === 'val') {
1670
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
1671
+ decodeText(this._val, 'binary', this.charset),
1672
+ this._keyTrunc,
1673
+ this._valTrunc);
1674
+ }
1675
+ this.boy._done = true;
1676
+ this.boy.emit('finish');
1677
+ };
1678
+
1679
+ urlencoded = UrlEncoded;
1680
+ return urlencoded;
1681
+ }
1682
+
1683
+ var hasRequiredMain;
1684
+
1685
+ function requireMain () {
1686
+ if (hasRequiredMain) return main.exports;
1687
+ hasRequiredMain = 1;
1688
+
1689
+ const WritableStream = require$$0$1.Writable;
1690
+ const { inherits } = require$$1$1;
1691
+ const Dicer = requireDicer();
1692
+
1693
+ const MultipartParser = requireMultipart();
1694
+ const UrlencodedParser = requireUrlencoded();
1695
+ const parseParams = requireParseParams();
1696
+
1697
+ function Busboy (opts) {
1698
+ if (!(this instanceof Busboy)) { return new Busboy(opts) }
1699
+
1700
+ if (typeof opts !== 'object') {
1701
+ throw new TypeError('Busboy expected an options-Object.')
1702
+ }
1703
+ if (typeof opts.headers !== 'object') {
1704
+ throw new TypeError('Busboy expected an options-Object with headers-attribute.')
1705
+ }
1706
+ if (typeof opts.headers['content-type'] !== 'string') {
1707
+ throw new TypeError('Missing Content-Type-header.')
1708
+ }
1709
+
1710
+ const {
1711
+ headers,
1712
+ ...streamOptions
1713
+ } = opts;
1714
+
1715
+ this.opts = {
1716
+ autoDestroy: false,
1717
+ ...streamOptions
1718
+ };
1719
+ WritableStream.call(this, this.opts);
1720
+
1721
+ this._done = false;
1722
+ this._parser = this.getParserByHeaders(headers);
1723
+ this._finished = false;
1724
+ }
1725
+ inherits(Busboy, WritableStream);
1726
+
1727
+ Busboy.prototype.emit = function (ev) {
1728
+ if (ev === 'finish') {
1729
+ if (!this._done) {
1730
+ this._parser?.end();
1731
+ return
1732
+ } else if (this._finished) {
1733
+ return
1734
+ }
1735
+ this._finished = true;
1736
+ }
1737
+ WritableStream.prototype.emit.apply(this, arguments);
1738
+ };
1739
+
1740
+ Busboy.prototype.getParserByHeaders = function (headers) {
1741
+ const parsed = parseParams(headers['content-type']);
1742
+
1743
+ const cfg = {
1744
+ defCharset: this.opts.defCharset,
1745
+ fileHwm: this.opts.fileHwm,
1746
+ headers,
1747
+ highWaterMark: this.opts.highWaterMark,
1748
+ isPartAFile: this.opts.isPartAFile,
1749
+ limits: this.opts.limits,
1750
+ parsedConType: parsed,
1751
+ preservePath: this.opts.preservePath
1752
+ };
1753
+
1754
+ if (MultipartParser.detect.test(parsed[0])) {
1755
+ return new MultipartParser(this, cfg)
1756
+ }
1757
+ if (UrlencodedParser.detect.test(parsed[0])) {
1758
+ return new UrlencodedParser(this, cfg)
1759
+ }
1760
+ throw new Error('Unsupported Content-Type.')
1761
+ };
1762
+
1763
+ Busboy.prototype._write = function (chunk, encoding, cb) {
1764
+ this._parser.write(chunk, cb);
1765
+ };
1766
+
1767
+ main.exports = Busboy;
1768
+ main.exports.default = Busboy;
1769
+ main.exports.Busboy = Busboy;
1770
+
1771
+ main.exports.Dicer = Dicer;
1772
+ return main.exports;
1773
+ }
1774
+
1775
+ var Blob = {};
1776
+
1777
+ var ReadableStream = {};
1778
+
1779
+ var utils = {};
1780
+
1781
+ var hasRequiredUtils;
1782
+
1783
+ function requireUtils () {
1784
+ if (hasRequiredUtils) return utils;
1785
+ hasRequiredUtils = 1;
1786
+ (function (exports) {
1787
+ Object.defineProperty(exports, "__esModule", { value: true });
1788
+ exports.fakePromise = void 0;
1789
+ exports.getHeadersObj = getHeadersObj;
1790
+ exports.defaultHeadersSerializer = defaultHeadersSerializer;
1791
+ exports.isArrayBufferView = isArrayBufferView;
1792
+ exports.isNodeReadable = isNodeReadable;
1793
+ exports.isIterable = isIterable;
1794
+ exports.shouldRedirect = shouldRedirect;
1795
+ exports.pipeThrough = pipeThrough;
1796
+ exports.endStream = endStream;
1797
+ exports.safeWrite = safeWrite;
1798
+ const node_events_1 = require$$0;
1799
+ function isHeadersInstance(obj) {
1800
+ return obj?.forEach != null;
1801
+ }
1802
+ function getHeadersObj(headers) {
1803
+ if (headers == null || !isHeadersInstance(headers)) {
1804
+ return headers;
1805
+ }
1806
+ // @ts-expect-error - `headersInit` is not a public property
1807
+ if (headers.headersInit && !headers._map && !isHeadersInstance(headers.headersInit)) {
1808
+ // @ts-expect-error - `headersInit` is not a public property
1809
+ return headers.headersInit;
1810
+ }
1811
+ return Object.fromEntries(headers.entries());
1812
+ }
1813
+ function defaultHeadersSerializer(headers, onContentLength) {
1814
+ const headerArray = [];
1815
+ headers.forEach((value, key) => {
1816
+ if (onContentLength && key === 'content-length') {
1817
+ onContentLength(value);
1818
+ }
1819
+ headerArray.push(`${key}: ${value}`);
1820
+ });
1821
+ return headerArray;
1822
+ }
1823
+ var promise_helpers_1 = require$$4;
1824
+ Object.defineProperty(exports, "fakePromise", { enumerable: true, get: function () { return promise_helpers_1.fakePromise; } });
1825
+ function isArrayBufferView(obj) {
1826
+ return obj != null && obj.buffer != null && obj.byteLength != null && obj.byteOffset != null;
1827
+ }
1828
+ function isNodeReadable(obj) {
1829
+ return obj != null && obj.pipe != null;
1830
+ }
1831
+ function isIterable(value) {
1832
+ return value?.[Symbol.iterator] != null;
1833
+ }
1834
+ function shouldRedirect(status) {
1835
+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
1836
+ }
1837
+ function pipeThrough({ src, dest, signal, onError, }) {
1838
+ if (onError) {
1839
+ // listen for errors on the destination stream if necessary. if the readable
1840
+ // stream (src) emits an error, the writable destination (dest) will be
1841
+ // destroyed with that error (see below)
1842
+ dest.once('error', onError);
1843
+ }
1844
+ src.once('error', (e) => {
1845
+ // if the readable stream (src) emits an error during pipe, the writable
1846
+ // destination (dest) is not closed automatically. that needs to be
1847
+ // done manually. the readable stream is closed when error is emitted,
1848
+ // so only the writable destination needs to be destroyed
1849
+ dest.destroy(e);
1850
+ });
1851
+ dest.once('close', () => {
1852
+ // if the writable destination (dest) is closed, the readable stream (src)
1853
+ // is not closed automatically. that needs to be done manually
1854
+ if (!src.destroyed) {
1855
+ src.destroy();
1856
+ }
1857
+ });
1858
+ if (signal) {
1859
+ // this is faster than `import('node:signal').addAbortSignal(signal, src)`
1860
+ const srcRef = new WeakRef(src);
1861
+ const signalRef = new WeakRef(signal);
1862
+ function cleanup() {
1863
+ signalRef.deref()?.removeEventListener('abort', onAbort);
1864
+ srcRef.deref()?.removeListener('end', cleanup);
1865
+ srcRef.deref()?.removeListener('error', cleanup);
1866
+ srcRef.deref()?.removeListener('close', cleanup);
1867
+ }
1868
+ function onAbort() {
1869
+ srcRef.deref()?.destroy(new AbortError());
1870
+ cleanup();
1871
+ }
1872
+ signal.addEventListener('abort', onAbort, { once: true });
1873
+ // this is faster than `import('node:signal').finished(src, cleanup)`
1874
+ src.once('end', cleanup);
1875
+ src.once('error', cleanup);
1876
+ src.once('close', cleanup);
1877
+ }
1878
+ src.pipe(dest, { end: true /* already default */ });
1879
+ }
1880
+ function endStream(stream) {
1881
+ // @ts-expect-error Avoid arguments adaptor trampoline https://v8.dev/blog/adaptor-frame
1882
+ return stream.end(null, null, null);
1883
+ }
1884
+ function safeWrite(chunk, stream) {
1885
+ const result = stream.write(chunk);
1886
+ if (!result) {
1887
+ return (0, node_events_1.once)(stream, 'drain');
1888
+ }
1889
+ }
1890
+ // https://github.com/nodejs/node/blob/f692878dec6354c0a82241f224906981861bc840/lib/internal/errors.js#L961-L973
1891
+ class AbortError extends Error {
1892
+ constructor(message = 'The operation was aborted', options = undefined) {
1893
+ super(message, options);
1894
+ this.name = 'AbortError';
1895
+ }
1896
+ }
1897
+ } (utils));
1898
+ return utils;
1899
+ }
1900
+
1901
+ var hasRequiredReadableStream;
1902
+
1903
+ function requireReadableStream () {
1904
+ if (hasRequiredReadableStream) return ReadableStream;
1905
+ hasRequiredReadableStream = 1;
1906
+ Object.defineProperty(ReadableStream, "__esModule", { value: true });
1907
+ ReadableStream.PonyfillReadableStream = void 0;
1908
+ const node_buffer_1 = require$$0$2;
1909
+ const node_events_1 = require$$0;
1910
+ const node_stream_1 = require$$0$1;
1911
+ const promises_1 = require$$3;
1912
+ const promise_helpers_1 = require$$4;
1913
+ const utils_js_1 = requireUtils();
1914
+ function createController(desiredSize, readable) {
1915
+ let chunks = [];
1916
+ let _closed = false;
1917
+ let flushed = false;
1918
+ return {
1919
+ desiredSize,
1920
+ enqueue(chunk) {
1921
+ const buf = typeof chunk === 'string' ? node_buffer_1.Buffer.from(chunk) : chunk;
1922
+ if (!flushed) {
1923
+ chunks.push(buf);
1924
+ }
1925
+ else {
1926
+ readable.push(buf);
1927
+ }
1928
+ },
1929
+ close() {
1930
+ if (chunks.length > 0) {
1931
+ this._flush();
1932
+ }
1933
+ readable.push(null);
1934
+ _closed = true;
1935
+ },
1936
+ error(error) {
1937
+ if (chunks.length > 0) {
1938
+ this._flush();
1939
+ }
1940
+ readable.destroy(error);
1941
+ },
1942
+ get _closed() {
1943
+ return _closed;
1944
+ },
1945
+ _flush() {
1946
+ flushed = true;
1947
+ if (chunks.length > 0) {
1948
+ const concatenated = chunks.length > 1 ? node_buffer_1.Buffer.concat(chunks) : chunks[0];
1949
+ readable.push(concatenated);
1950
+ chunks = [];
1951
+ }
1952
+ },
1953
+ };
1954
+ }
1955
+ function isNodeReadable(obj) {
1956
+ return obj?.read != null;
1957
+ }
1958
+ function isReadableStream(obj) {
1959
+ return obj?.getReader != null;
1960
+ }
1961
+ class PonyfillReadableStream {
1962
+ readable;
1963
+ constructor(underlyingSource) {
1964
+ if (underlyingSource instanceof PonyfillReadableStream && underlyingSource.readable != null) {
1965
+ this.readable = underlyingSource.readable;
1966
+ }
1967
+ else if (isNodeReadable(underlyingSource)) {
1968
+ this.readable = underlyingSource;
1969
+ }
1970
+ else if (isReadableStream(underlyingSource)) {
1971
+ this.readable = node_stream_1.Readable.fromWeb(underlyingSource);
1972
+ }
1973
+ else {
1974
+ let started = false;
1975
+ let ongoing = false;
1976
+ const handleStart = (desiredSize) => {
1977
+ if (!started) {
1978
+ const controller = createController(desiredSize, this.readable);
1979
+ started = true;
1980
+ return (0, promise_helpers_1.handleMaybePromise)(() => underlyingSource?.start?.(controller), () => {
1981
+ controller._flush();
1982
+ if (controller._closed) {
1983
+ return false;
1984
+ }
1985
+ return true;
1986
+ });
1987
+ }
1988
+ return true;
1989
+ };
1990
+ const readImpl = (desiredSize) => {
1991
+ return (0, promise_helpers_1.handleMaybePromise)(() => handleStart(desiredSize), shouldContinue => {
1992
+ if (!shouldContinue) {
1993
+ return;
1994
+ }
1995
+ const controller = createController(desiredSize, this.readable);
1996
+ return (0, promise_helpers_1.handleMaybePromise)(() => underlyingSource?.pull?.(controller), () => {
1997
+ controller._flush();
1998
+ ongoing = false;
1999
+ });
2000
+ });
2001
+ };
2002
+ this.readable = new node_stream_1.Readable({
2003
+ read(desiredSize) {
2004
+ if (ongoing) {
2005
+ return;
2006
+ }
2007
+ ongoing = true;
2008
+ return readImpl(desiredSize);
2009
+ },
2010
+ destroy(err, callback) {
2011
+ if (underlyingSource?.cancel) {
2012
+ try {
2013
+ const res$ = underlyingSource.cancel(err);
2014
+ if (res$?.then) {
2015
+ return res$.then(() => {
2016
+ callback(null);
2017
+ }, err => {
2018
+ callback(err);
2019
+ });
2020
+ }
2021
+ }
2022
+ catch (err) {
2023
+ callback(err);
2024
+ return;
2025
+ }
2026
+ }
2027
+ callback(null);
2028
+ },
2029
+ });
2030
+ }
2031
+ }
2032
+ cancel(reason) {
2033
+ this.readable.destroy(reason);
2034
+ // @ts-expect-error - we know it is void
2035
+ return (0, node_events_1.once)(this.readable, 'close');
2036
+ }
2037
+ locked = false;
2038
+ getReader(_options) {
2039
+ const iterator = this.readable[Symbol.asyncIterator]();
2040
+ this.locked = true;
2041
+ const thisReadable = this.readable;
2042
+ return {
2043
+ read() {
2044
+ return iterator.next();
2045
+ },
2046
+ releaseLock: () => {
2047
+ if (iterator.return) {
2048
+ const retResult$ = iterator.return();
2049
+ if (retResult$.then) {
2050
+ retResult$.then(() => {
2051
+ this.locked = false;
2052
+ });
2053
+ return;
2054
+ }
2055
+ }
2056
+ this.locked = false;
2057
+ },
2058
+ cancel: reason => {
2059
+ if (iterator.return) {
2060
+ const retResult$ = iterator.return(reason);
2061
+ if (retResult$.then) {
2062
+ return retResult$.then(() => {
2063
+ this.locked = false;
2064
+ });
2065
+ }
2066
+ }
2067
+ this.locked = false;
2068
+ return (0, utils_js_1.fakePromise)();
2069
+ },
2070
+ get closed() {
2071
+ return Promise.race([
2072
+ (0, node_events_1.once)(thisReadable, 'end'),
2073
+ (0, node_events_1.once)(thisReadable, 'error').then(err => Promise.reject(err)),
2074
+ ]);
2075
+ },
2076
+ };
2077
+ }
2078
+ [Symbol.asyncIterator]() {
2079
+ const iterator = this.readable[Symbol.asyncIterator]();
2080
+ return {
2081
+ [Symbol.asyncIterator]() {
2082
+ return this;
2083
+ },
2084
+ next: () => iterator.next(),
2085
+ return: () => {
2086
+ if (!this.readable.destroyed) {
2087
+ this.readable.destroy();
2088
+ }
2089
+ return iterator.return?.() || (0, utils_js_1.fakePromise)({ done: true, value: undefined });
2090
+ },
2091
+ throw: (err) => {
2092
+ if (!this.readable.destroyed) {
2093
+ this.readable.destroy(err);
2094
+ }
2095
+ return iterator.throw?.(err) || (0, utils_js_1.fakePromise)({ done: true, value: undefined });
2096
+ },
2097
+ };
2098
+ }
2099
+ tee() {
2100
+ throw new Error('Not implemented');
2101
+ }
2102
+ async pipeToWriter(writer) {
2103
+ try {
2104
+ for await (const chunk of this) {
2105
+ await writer.write(chunk);
2106
+ }
2107
+ await writer.close();
2108
+ }
2109
+ catch (err) {
2110
+ await writer.abort(err);
2111
+ }
2112
+ }
2113
+ pipeTo(destination) {
2114
+ if (isPonyfillWritableStream(destination)) {
2115
+ return (0, promises_1.pipeline)(this.readable, destination.writable, {
2116
+ end: true,
2117
+ });
2118
+ }
2119
+ else {
2120
+ const writer = destination.getWriter();
2121
+ return this.pipeToWriter(writer);
2122
+ }
2123
+ }
2124
+ pipeThrough({ writable, readable, }) {
2125
+ this.pipeTo(writable).catch(err => {
2126
+ this.readable.destroy(err);
2127
+ });
2128
+ if (isPonyfillReadableStream(readable)) {
2129
+ readable.readable.once('error', err => this.readable.destroy(err));
2130
+ readable.readable.once('finish', () => this.readable.push(null));
2131
+ readable.readable.once('close', () => this.readable.push(null));
2132
+ }
2133
+ return readable;
2134
+ }
2135
+ static [Symbol.hasInstance](instance) {
2136
+ return isReadableStream(instance);
2137
+ }
2138
+ static from(iterable) {
2139
+ return new PonyfillReadableStream(node_stream_1.Readable.from(iterable));
2140
+ }
2141
+ [Symbol.toStringTag] = 'ReadableStream';
2142
+ }
2143
+ ReadableStream.PonyfillReadableStream = PonyfillReadableStream;
2144
+ function isPonyfillReadableStream(obj) {
2145
+ return obj?.readable != null;
2146
+ }
2147
+ function isPonyfillWritableStream(obj) {
2148
+ return obj?.writable != null;
2149
+ }
2150
+ return ReadableStream;
2151
+ }
2152
+
2153
+ var hasRequiredBlob;
2154
+
2155
+ function requireBlob () {
2156
+ if (hasRequiredBlob) return Blob;
2157
+ hasRequiredBlob = 1;
2158
+ Object.defineProperty(Blob, "__esModule", { value: true });
2159
+ Blob.PonyfillBlob = void 0;
2160
+ Blob.hasBufferMethod = hasBufferMethod;
2161
+ Blob.hasArrayBufferMethod = hasArrayBufferMethod;
2162
+ Blob.hasBytesMethod = hasBytesMethod;
2163
+ Blob.hasTextMethod = hasTextMethod;
2164
+ Blob.hasSizeProperty = hasSizeProperty;
2165
+ Blob.hasStreamMethod = hasStreamMethod;
2166
+ Blob.hasBlobSignature = hasBlobSignature;
2167
+ Blob.isArrayBuffer = isArrayBuffer;
2168
+ /* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */
2169
+ /* eslint-disable @typescript-eslint/ban-ts-comment */
2170
+ const node_buffer_1 = require$$0$2;
2171
+ const ReadableStream_js_1 = requireReadableStream();
2172
+ const utils_js_1 = requireUtils();
2173
+ function getBlobPartAsBuffer(blobPart) {
2174
+ if (typeof blobPart === 'string') {
2175
+ return node_buffer_1.Buffer.from(blobPart);
2176
+ }
2177
+ else if (node_buffer_1.Buffer.isBuffer(blobPart)) {
2178
+ return blobPart;
2179
+ }
2180
+ else if ((0, utils_js_1.isArrayBufferView)(blobPart)) {
2181
+ return node_buffer_1.Buffer.from(blobPart.buffer, blobPart.byteOffset, blobPart.byteLength);
2182
+ }
2183
+ else {
2184
+ return node_buffer_1.Buffer.from(blobPart);
2185
+ }
2186
+ }
2187
+ function hasBufferMethod(obj) {
2188
+ return obj != null && obj.buffer != null && typeof obj.buffer === 'function';
2189
+ }
2190
+ function hasArrayBufferMethod(obj) {
2191
+ return obj != null && obj.arrayBuffer != null && typeof obj.arrayBuffer === 'function';
2192
+ }
2193
+ function hasBytesMethod(obj) {
2194
+ return obj != null && obj.bytes != null && typeof obj.bytes === 'function';
2195
+ }
2196
+ function hasTextMethod(obj) {
2197
+ return obj != null && obj.text != null && typeof obj.text === 'function';
2198
+ }
2199
+ function hasSizeProperty(obj) {
2200
+ return obj != null && typeof obj.size === 'number';
2201
+ }
2202
+ function hasStreamMethod(obj) {
2203
+ return obj != null && obj.stream != null && typeof obj.stream === 'function';
2204
+ }
2205
+ function hasBlobSignature(obj) {
2206
+ return obj != null && obj[Symbol.toStringTag] === 'Blob';
2207
+ }
2208
+ function isArrayBuffer(obj) {
2209
+ return obj != null && obj.byteLength != null && obj.slice != null;
2210
+ }
2211
+ // Will be removed after v14 reaches EOL
2212
+ // Needed because v14 doesn't have .stream() implemented
2213
+ class PonyfillBlob {
2214
+ blobParts;
2215
+ type;
2216
+ encoding;
2217
+ _size = null;
2218
+ constructor(blobParts = [], options) {
2219
+ this.blobParts = blobParts;
2220
+ this.type = options?.type || 'application/octet-stream';
2221
+ this.encoding = options?.encoding || 'utf8';
2222
+ this._size = options?.size || null;
2223
+ if (blobParts.length === 1 && hasBlobSignature(blobParts[0])) {
2224
+ return blobParts[0];
2225
+ }
2226
+ }
2227
+ _buffer = null;
2228
+ buffer() {
2229
+ if (this._buffer) {
2230
+ return (0, utils_js_1.fakePromise)(this._buffer);
2231
+ }
2232
+ if (this.blobParts.length === 1) {
2233
+ const blobPart = this.blobParts[0];
2234
+ if (hasBufferMethod(blobPart)) {
2235
+ return blobPart.buffer().then(buf => {
2236
+ this._buffer = buf;
2237
+ return this._buffer;
2238
+ });
2239
+ }
2240
+ if (hasBytesMethod(blobPart)) {
2241
+ return blobPart.bytes().then(bytes => {
2242
+ this._buffer = node_buffer_1.Buffer.from(bytes);
2243
+ return this._buffer;
2244
+ });
2245
+ }
2246
+ if (hasArrayBufferMethod(blobPart)) {
2247
+ return blobPart.arrayBuffer().then(arrayBuf => {
2248
+ this._buffer = node_buffer_1.Buffer.from(arrayBuf, undefined, blobPart.size);
2249
+ return this._buffer;
2250
+ });
2251
+ }
2252
+ this._buffer = getBlobPartAsBuffer(blobPart);
2253
+ return (0, utils_js_1.fakePromise)(this._buffer);
2254
+ }
2255
+ const jobs = [];
2256
+ const bufferChunks = this.blobParts.map((blobPart, i) => {
2257
+ if (hasBufferMethod(blobPart)) {
2258
+ jobs.push(blobPart.buffer().then(buf => {
2259
+ bufferChunks[i] = buf;
2260
+ }));
2261
+ return undefined;
2262
+ }
2263
+ else if (hasArrayBufferMethod(blobPart)) {
2264
+ jobs.push(blobPart.arrayBuffer().then(arrayBuf => {
2265
+ bufferChunks[i] = node_buffer_1.Buffer.from(arrayBuf, undefined, blobPart.size);
2266
+ }));
2267
+ return undefined;
2268
+ }
2269
+ else if (hasBytesMethod(blobPart)) {
2270
+ jobs.push(blobPart.bytes().then(bytes => {
2271
+ bufferChunks[i] = node_buffer_1.Buffer.from(bytes);
2272
+ }));
2273
+ return undefined;
2274
+ }
2275
+ else {
2276
+ return getBlobPartAsBuffer(blobPart);
2277
+ }
2278
+ });
2279
+ if (jobs.length > 0) {
2280
+ return Promise.all(jobs).then(() => node_buffer_1.Buffer.concat(bufferChunks, this._size || undefined));
2281
+ }
2282
+ return (0, utils_js_1.fakePromise)(node_buffer_1.Buffer.concat(bufferChunks, this._size || undefined));
2283
+ }
2284
+ arrayBuffer() {
2285
+ if (this._buffer) {
2286
+ // @ts-ignore - Mismatch between Buffer and ArrayBuffer
2287
+ return (0, utils_js_1.fakePromise)(this._buffer);
2288
+ }
2289
+ if (this.blobParts.length === 1) {
2290
+ if (isArrayBuffer(this.blobParts[0])) {
2291
+ return (0, utils_js_1.fakePromise)(this.blobParts[0]);
2292
+ }
2293
+ if (hasArrayBufferMethod(this.blobParts[0])) {
2294
+ return this.blobParts[0].arrayBuffer();
2295
+ }
2296
+ }
2297
+ // @ts-ignore - Mismatch between Buffer and ArrayBuffer
2298
+ return this.buffer();
2299
+ }
2300
+ bytes() {
2301
+ if (this._buffer) {
2302
+ return (0, utils_js_1.fakePromise)(this._buffer);
2303
+ }
2304
+ if (this.blobParts.length === 1) {
2305
+ if (node_buffer_1.Buffer.isBuffer(this.blobParts[0])) {
2306
+ this._buffer = this.blobParts[0];
2307
+ return (0, utils_js_1.fakePromise)(this._buffer);
2308
+ }
2309
+ if (this.blobParts[0] instanceof Uint8Array) {
2310
+ this._buffer = node_buffer_1.Buffer.from(this.blobParts[0]);
2311
+ return (0, utils_js_1.fakePromise)(this._buffer);
2312
+ }
2313
+ if (hasBytesMethod(this.blobParts[0])) {
2314
+ return this.blobParts[0].bytes();
2315
+ }
2316
+ if (hasBufferMethod(this.blobParts[0])) {
2317
+ return this.blobParts[0].buffer();
2318
+ }
2319
+ }
2320
+ return this.buffer();
2321
+ }
2322
+ _text = null;
2323
+ text() {
2324
+ if (this._text) {
2325
+ return (0, utils_js_1.fakePromise)(this._text);
2326
+ }
2327
+ if (this.blobParts.length === 1) {
2328
+ const blobPart = this.blobParts[0];
2329
+ if (typeof blobPart === 'string') {
2330
+ this._text = blobPart;
2331
+ return (0, utils_js_1.fakePromise)(this._text);
2332
+ }
2333
+ if (hasTextMethod(blobPart)) {
2334
+ return blobPart.text().then(text => {
2335
+ this._text = text;
2336
+ return this._text;
2337
+ });
2338
+ }
2339
+ const buf = getBlobPartAsBuffer(blobPart);
2340
+ this._text = buf.toString(this.encoding);
2341
+ return (0, utils_js_1.fakePromise)(this._text);
2342
+ }
2343
+ return this.buffer().then(buf => {
2344
+ this._text = buf.toString(this.encoding);
2345
+ return this._text;
2346
+ });
2347
+ }
2348
+ _json = null;
2349
+ json() {
2350
+ if (this._json) {
2351
+ return (0, utils_js_1.fakePromise)(this._json);
2352
+ }
2353
+ return this.text().then(text => {
2354
+ this._json = JSON.parse(text);
2355
+ return this._json;
2356
+ });
2357
+ }
2358
+ _formData = null;
2359
+ formData() {
2360
+ if (this._formData) {
2361
+ return (0, utils_js_1.fakePromise)(this._formData);
2362
+ }
2363
+ throw new Error('Not implemented');
2364
+ }
2365
+ get size() {
2366
+ if (this._size == null) {
2367
+ this._size = 0;
2368
+ for (const blobPart of this.blobParts) {
2369
+ if (typeof blobPart === 'string') {
2370
+ this._size += node_buffer_1.Buffer.byteLength(blobPart);
2371
+ }
2372
+ else if (hasSizeProperty(blobPart)) {
2373
+ this._size += blobPart.size;
2374
+ }
2375
+ else if ((0, utils_js_1.isArrayBufferView)(blobPart)) {
2376
+ this._size += blobPart.byteLength;
2377
+ }
2378
+ }
2379
+ }
2380
+ return this._size;
2381
+ }
2382
+ stream() {
2383
+ if (this.blobParts.length === 1) {
2384
+ const blobPart = this.blobParts[0];
2385
+ if (hasStreamMethod(blobPart)) {
2386
+ return blobPart.stream();
2387
+ }
2388
+ const buf = getBlobPartAsBuffer(blobPart);
2389
+ return new ReadableStream_js_1.PonyfillReadableStream({
2390
+ start: controller => {
2391
+ controller.enqueue(buf);
2392
+ controller.close();
2393
+ },
2394
+ });
2395
+ }
2396
+ if (this._buffer != null) {
2397
+ return new ReadableStream_js_1.PonyfillReadableStream({
2398
+ start: controller => {
2399
+ controller.enqueue(this._buffer);
2400
+ controller.close();
2401
+ },
2402
+ });
2403
+ }
2404
+ let blobPartIterator;
2405
+ return new ReadableStream_js_1.PonyfillReadableStream({
2406
+ start: controller => {
2407
+ if (this.blobParts.length === 0) {
2408
+ controller.close();
2409
+ return;
2410
+ }
2411
+ blobPartIterator = this.blobParts[Symbol.iterator]();
2412
+ },
2413
+ pull: controller => {
2414
+ const { value: blobPart, done } = blobPartIterator.next();
2415
+ if (done) {
2416
+ controller.close();
2417
+ return;
2418
+ }
2419
+ if (blobPart) {
2420
+ if (hasBufferMethod(blobPart)) {
2421
+ return blobPart.buffer().then(buf => {
2422
+ controller.enqueue(buf);
2423
+ });
2424
+ }
2425
+ if (hasBytesMethod(blobPart)) {
2426
+ return blobPart.bytes().then(bytes => {
2427
+ const buf = node_buffer_1.Buffer.from(bytes);
2428
+ controller.enqueue(buf);
2429
+ });
2430
+ }
2431
+ if (hasArrayBufferMethod(blobPart)) {
2432
+ return blobPart.arrayBuffer().then(arrayBuffer => {
2433
+ const buf = node_buffer_1.Buffer.from(arrayBuffer, undefined, blobPart.size);
2434
+ controller.enqueue(buf);
2435
+ });
2436
+ }
2437
+ const buf = getBlobPartAsBuffer(blobPart);
2438
+ controller.enqueue(buf);
2439
+ }
2440
+ },
2441
+ });
2442
+ }
2443
+ slice() {
2444
+ throw new Error('Not implemented');
2445
+ }
2446
+ }
2447
+ Blob.PonyfillBlob = PonyfillBlob;
2448
+ return Blob;
2449
+ }
2450
+
2451
+ var File = {};
2452
+
2453
+ var hasRequiredFile;
2454
+
2455
+ function requireFile () {
2456
+ if (hasRequiredFile) return File;
2457
+ hasRequiredFile = 1;
2458
+ Object.defineProperty(File, "__esModule", { value: true });
2459
+ File.PonyfillFile = void 0;
2460
+ const Blob_js_1 = requireBlob();
2461
+ class PonyfillFile extends Blob_js_1.PonyfillBlob {
2462
+ name;
2463
+ lastModified;
2464
+ constructor(fileBits, name, options) {
2465
+ super(fileBits, options);
2466
+ this.name = name;
2467
+ this.lastModified = options?.lastModified || Date.now();
2468
+ }
2469
+ webkitRelativePath = '';
2470
+ }
2471
+ File.PonyfillFile = PonyfillFile;
2472
+ return File;
2473
+ }
2474
+
2475
+ var FormData = {};
2476
+
2477
+ var IteratorObject = {};
2478
+
2479
+ var hasRequiredIteratorObject;
2480
+
2481
+ function requireIteratorObject () {
2482
+ if (hasRequiredIteratorObject) return IteratorObject;
2483
+ hasRequiredIteratorObject = 1;
2484
+ Object.defineProperty(IteratorObject, "__esModule", { value: true });
2485
+ IteratorObject.PonyfillIteratorObject = void 0;
2486
+ const node_util_1 = require$$1$1;
2487
+ const disposablestack_1 = require$$1__default;
2488
+ const utils_js_1 = requireUtils();
2489
+ class PonyfillIteratorObject {
2490
+ iterableIterator;
2491
+ [Symbol.toStringTag] = 'IteratorObject';
2492
+ constructor(iterableIterator, className) {
2493
+ this.iterableIterator = iterableIterator;
2494
+ this[Symbol.toStringTag] = className;
2495
+ }
2496
+ *map(callbackfn) {
2497
+ let index = 0;
2498
+ for (const value of this.iterableIterator) {
2499
+ yield callbackfn(value, index++);
2500
+ }
2501
+ return undefined;
2502
+ }
2503
+ *filter(callbackfn) {
2504
+ let index = 0;
2505
+ for (const value of this.iterableIterator) {
2506
+ if (callbackfn(value, index++)) {
2507
+ yield value;
2508
+ }
2509
+ }
2510
+ return undefined;
2511
+ }
2512
+ reduce(callbackfn, initialValue) {
2513
+ let index = 0;
2514
+ let accumulator = initialValue;
2515
+ for (const value of this.iterableIterator) {
2516
+ accumulator = callbackfn(accumulator, value, index++);
2517
+ }
2518
+ return accumulator;
2519
+ }
2520
+ forEach(callbackfn) {
2521
+ let index = 0;
2522
+ for (const value of this.iterableIterator) {
2523
+ callbackfn(value, index++);
2524
+ }
2525
+ }
2526
+ *take(limit) {
2527
+ let index = 0;
2528
+ for (const value of this.iterableIterator) {
2529
+ if (index >= limit) {
2530
+ break;
2531
+ }
2532
+ yield value;
2533
+ index++;
2534
+ }
2535
+ return undefined;
2536
+ }
2537
+ *drop(count) {
2538
+ let index = 0;
2539
+ for (const value of this.iterableIterator) {
2540
+ if (index >= count) {
2541
+ yield value;
2542
+ }
2543
+ index++;
2544
+ }
2545
+ return undefined;
2546
+ }
2547
+ *flatMap(callback) {
2548
+ let index = 0;
2549
+ for (const value of this.iterableIterator) {
2550
+ const iteratorOrIterable = callback(value, index++);
2551
+ if ((0, utils_js_1.isIterable)(iteratorOrIterable)) {
2552
+ for (const innerValue of iteratorOrIterable) {
2553
+ yield innerValue;
2554
+ }
2555
+ }
2556
+ else {
2557
+ for (const innerValue of {
2558
+ [Symbol.iterator]: () => iteratorOrIterable,
2559
+ }) {
2560
+ yield innerValue;
2561
+ }
2562
+ }
2563
+ }
2564
+ return undefined;
2565
+ }
2566
+ some(predicate) {
2567
+ let index = 0;
2568
+ for (const value of this.iterableIterator) {
2569
+ if (predicate(value, index++)) {
2570
+ return true;
2571
+ }
2572
+ }
2573
+ return false;
2574
+ }
2575
+ every(predicate) {
2576
+ let index = 0;
2577
+ for (const value of this.iterableIterator) {
2578
+ if (!predicate(value, index++)) {
2579
+ return false;
2580
+ }
2581
+ }
2582
+ return true;
2583
+ }
2584
+ find(predicate) {
2585
+ let index = 0;
2586
+ for (const value of this.iterableIterator) {
2587
+ if (predicate(value, index++)) {
2588
+ return value;
2589
+ }
2590
+ }
2591
+ return undefined;
2592
+ }
2593
+ toArray() {
2594
+ return Array.from(this.iterableIterator);
2595
+ }
2596
+ [disposablestack_1.DisposableSymbols.dispose]() {
2597
+ this.iterableIterator.return?.();
2598
+ }
2599
+ next(...[value]) {
2600
+ return this.iterableIterator.next(value);
2601
+ }
2602
+ [Symbol.iterator]() {
2603
+ return this;
2604
+ }
2605
+ [Symbol.for('nodejs.util.inspect.custom')]() {
2606
+ const record = {};
2607
+ this.forEach((value, key) => {
2608
+ const inspectedValue = (0, node_util_1.inspect)(value);
2609
+ record[key] = inspectedValue.includes(',')
2610
+ ? inspectedValue.split(',').map(el => el.trim())
2611
+ : inspectedValue;
2612
+ });
2613
+ return `${this[Symbol.toStringTag]} ${(0, node_util_1.inspect)(record)}`;
2614
+ }
2615
+ }
2616
+ IteratorObject.PonyfillIteratorObject = PonyfillIteratorObject;
2617
+ return IteratorObject;
2618
+ }
2619
+
2620
+ var hasRequiredFormData;
2621
+
2622
+ function requireFormData () {
2623
+ if (hasRequiredFormData) return FormData;
2624
+ hasRequiredFormData = 1;
2625
+ Object.defineProperty(FormData, "__esModule", { value: true });
2626
+ FormData.PonyfillFormData = void 0;
2627
+ FormData.getStreamFromFormData = getStreamFromFormData;
2628
+ const node_buffer_1 = require$$0$2;
2629
+ const IteratorObject_js_1 = requireIteratorObject();
2630
+ const ReadableStream_js_1 = requireReadableStream();
2631
+ class PonyfillFormData {
2632
+ map = new Map();
2633
+ append(name, value, fileName) {
2634
+ let values = this.map.get(name);
2635
+ if (!values) {
2636
+ values = [];
2637
+ this.map.set(name, values);
2638
+ }
2639
+ const entry = isBlob(value)
2640
+ ? getNormalizedFile(name, value, fileName)
2641
+ : value;
2642
+ values.push(entry);
2643
+ }
2644
+ delete(name) {
2645
+ this.map.delete(name);
2646
+ }
2647
+ get(name) {
2648
+ const values = this.map.get(name);
2649
+ return values ? values[0] : null;
2650
+ }
2651
+ getAll(name) {
2652
+ return this.map.get(name) || [];
2653
+ }
2654
+ has(name) {
2655
+ return this.map.has(name);
2656
+ }
2657
+ set(name, value, fileName) {
2658
+ const entry = isBlob(value)
2659
+ ? getNormalizedFile(name, value, fileName)
2660
+ : value;
2661
+ this.map.set(name, [entry]);
2662
+ }
2663
+ [Symbol.iterator]() {
2664
+ return this._entries();
2665
+ }
2666
+ *_entries() {
2667
+ for (const [key, values] of this.map) {
2668
+ for (const value of values) {
2669
+ yield [key, value];
2670
+ }
2671
+ }
2672
+ }
2673
+ entries() {
2674
+ return new IteratorObject_js_1.PonyfillIteratorObject(this._entries(), 'FormDataIterator');
2675
+ }
2676
+ _keys() {
2677
+ return this.map.keys();
2678
+ }
2679
+ keys() {
2680
+ return new IteratorObject_js_1.PonyfillIteratorObject(this._keys(), 'FormDataIterator');
2681
+ }
2682
+ *_values() {
2683
+ for (const values of this.map.values()) {
2684
+ for (const value of values) {
2685
+ yield value;
2686
+ }
2687
+ }
2688
+ }
2689
+ values() {
2690
+ return new IteratorObject_js_1.PonyfillIteratorObject(this._values(), 'FormDataIterator');
2691
+ }
2692
+ forEach(callback) {
2693
+ for (const [key, value] of this) {
2694
+ callback(value, key, this);
2695
+ }
2696
+ }
2697
+ }
2698
+ FormData.PonyfillFormData = PonyfillFormData;
2699
+ function getStreamFromFormData(formData, boundary = '---') {
2700
+ let entriesIterator;
2701
+ let sentInitialHeader = false;
2702
+ let currentAsyncIterator;
2703
+ let hasBefore = false;
2704
+ function handleNextEntry(controller) {
2705
+ const { done, value } = entriesIterator.next();
2706
+ if (done) {
2707
+ controller.enqueue(node_buffer_1.Buffer.from(`\r\n--${boundary}--\r\n`));
2708
+ return controller.close();
2709
+ }
2710
+ if (hasBefore) {
2711
+ controller.enqueue(node_buffer_1.Buffer.from(`\r\n--${boundary}\r\n`));
2712
+ }
2713
+ if (value) {
2714
+ const [key, blobOrString] = value;
2715
+ if (typeof blobOrString === 'string') {
2716
+ controller.enqueue(node_buffer_1.Buffer.from(`Content-Disposition: form-data; name="${key}"\r\n\r\n`));
2717
+ controller.enqueue(node_buffer_1.Buffer.from(blobOrString));
2718
+ }
2719
+ else {
2720
+ let filenamePart = '';
2721
+ if (blobOrString.name) {
2722
+ filenamePart = `; filename="${blobOrString.name}"`;
2723
+ }
2724
+ controller.enqueue(node_buffer_1.Buffer.from(`Content-Disposition: form-data; name="${key}"${filenamePart}\r\n`));
2725
+ controller.enqueue(node_buffer_1.Buffer.from(`Content-Type: ${blobOrString.type || 'application/octet-stream'}\r\n\r\n`));
2726
+ const entryStream = blobOrString.stream();
2727
+ // @ts-expect-error - ReadableStream is async iterable
2728
+ currentAsyncIterator = entryStream[Symbol.asyncIterator]();
2729
+ }
2730
+ hasBefore = true;
2731
+ }
2732
+ }
2733
+ return new ReadableStream_js_1.PonyfillReadableStream({
2734
+ start: () => {
2735
+ entriesIterator = formData.entries();
2736
+ },
2737
+ pull: controller => {
2738
+ if (!sentInitialHeader) {
2739
+ sentInitialHeader = true;
2740
+ return controller.enqueue(node_buffer_1.Buffer.from(`--${boundary}\r\n`));
2741
+ }
2742
+ if (currentAsyncIterator) {
2743
+ return currentAsyncIterator.next().then(({ done, value }) => {
2744
+ if (done) {
2745
+ currentAsyncIterator = undefined;
2746
+ }
2747
+ if (value) {
2748
+ return controller.enqueue(value);
2749
+ }
2750
+ else {
2751
+ return handleNextEntry(controller);
2752
+ }
2753
+ });
2754
+ }
2755
+ return handleNextEntry(controller);
2756
+ },
2757
+ cancel: err => {
2758
+ entriesIterator?.return?.(err);
2759
+ currentAsyncIterator?.return?.(err);
2760
+ },
2761
+ });
2762
+ }
2763
+ function getNormalizedFile(name, blob, fileName) {
2764
+ Object.defineProperty(blob, 'name', {
2765
+ configurable: true,
2766
+ enumerable: true,
2767
+ value: fileName || blob.name || name,
2768
+ });
2769
+ return blob;
2770
+ }
2771
+ function isBlob(value) {
2772
+ return value?.arrayBuffer != null;
2773
+ }
2774
+ return FormData;
2775
+ }
2776
+
2777
+ var hasRequiredBody;
2778
+
2779
+ function requireBody () {
2780
+ if (hasRequiredBody) return Body;
2781
+ hasRequiredBody = 1;
2782
+ Object.defineProperty(Body, "__esModule", { value: true });
2783
+ Body.PonyfillBody = void 0;
2784
+ /* eslint-disable @typescript-eslint/ban-ts-comment */
2785
+ const node_buffer_1 = require$$0$2;
2786
+ const node_stream_1 = require$$0$1;
2787
+ const busboy_1 = requireMain();
2788
+ const promise_helpers_1 = require$$4;
2789
+ const Blob_js_1 = requireBlob();
2790
+ const File_js_1 = requireFile();
2791
+ const FormData_js_1 = requireFormData();
2792
+ const ReadableStream_js_1 = requireReadableStream();
2793
+ const utils_js_1 = requireUtils();
2794
+ var BodyInitType;
2795
+ (function (BodyInitType) {
2796
+ BodyInitType["ReadableStream"] = "ReadableStream";
2797
+ BodyInitType["Blob"] = "Blob";
2798
+ BodyInitType["FormData"] = "FormData";
2799
+ BodyInitType["String"] = "String";
2800
+ BodyInitType["Readable"] = "Readable";
2801
+ BodyInitType["Buffer"] = "Buffer";
2802
+ BodyInitType["AsyncIterable"] = "AsyncIterable";
2803
+ })(BodyInitType || (BodyInitType = {}));
2804
+ class PonyfillBody {
2805
+ bodyInit;
2806
+ options;
2807
+ bodyUsed = false;
2808
+ contentType = null;
2809
+ contentLength = null;
2810
+ constructor(bodyInit, options = {}) {
2811
+ this.bodyInit = bodyInit;
2812
+ this.options = options;
2813
+ const { bodyFactory, contentType, contentLength, bodyType, buffer } = processBodyInit(bodyInit);
2814
+ this._bodyFactory = bodyFactory;
2815
+ this.contentType = contentType;
2816
+ this.contentLength = contentLength;
2817
+ this.bodyType = bodyType;
2818
+ this._buffer = buffer;
2819
+ this._signal = options.signal;
2820
+ }
2821
+ bodyType;
2822
+ _bodyFactory = () => null;
2823
+ _generatedBody = null;
2824
+ _buffer;
2825
+ _signal;
2826
+ generateBody() {
2827
+ if (this._generatedBody?.readable?.destroyed && this._buffer) {
2828
+ this._generatedBody.readable = node_stream_1.Readable.from(this._buffer);
2829
+ }
2830
+ if (this._generatedBody) {
2831
+ return this._generatedBody;
2832
+ }
2833
+ const body = this._bodyFactory();
2834
+ this._generatedBody = body;
2835
+ return body;
2836
+ }
2837
+ handleContentLengthHeader(forceSet = false) {
2838
+ const contentTypeInHeaders = this.headers.get('content-type');
2839
+ if (!contentTypeInHeaders) {
2840
+ if (this.contentType) {
2841
+ this.headers.set('content-type', this.contentType);
2842
+ }
2843
+ }
2844
+ else {
2845
+ this.contentType = contentTypeInHeaders;
2846
+ }
2847
+ const contentLengthInHeaders = this.headers.get('content-length');
2848
+ if (forceSet && this.bodyInit == null && !contentLengthInHeaders) {
2849
+ this.contentLength = 0;
2850
+ this.headers.set('content-length', '0');
2851
+ }
2852
+ if (!contentLengthInHeaders) {
2853
+ if (this.contentLength) {
2854
+ this.headers.set('content-length', this.contentLength.toString());
2855
+ }
2856
+ }
2857
+ else {
2858
+ this.contentLength = parseInt(contentLengthInHeaders, 10);
2859
+ }
2860
+ }
2861
+ get body() {
2862
+ const _body = this.generateBody();
2863
+ if (_body != null) {
2864
+ const ponyfillReadableStream = _body;
2865
+ const readable = _body.readable;
2866
+ return new Proxy(_body.readable, {
2867
+ get(_, prop) {
2868
+ if (prop in ponyfillReadableStream) {
2869
+ const ponyfillReadableStreamProp = ponyfillReadableStream[prop];
2870
+ if (typeof ponyfillReadableStreamProp === 'function') {
2871
+ return ponyfillReadableStreamProp.bind(ponyfillReadableStream);
2872
+ }
2873
+ return ponyfillReadableStreamProp;
2874
+ }
2875
+ if (prop in readable) {
2876
+ const readableProp = readable[prop];
2877
+ if (typeof readableProp === 'function') {
2878
+ return readableProp.bind(readable);
2879
+ }
2880
+ return readableProp;
2881
+ }
2882
+ },
2883
+ });
2884
+ }
2885
+ return null;
2886
+ }
2887
+ _chunks = null;
2888
+ _doCollectChunksFromReadableJob() {
2889
+ if (this.bodyType === BodyInitType.AsyncIterable) {
2890
+ if (Array.fromAsync) {
2891
+ return (0, promise_helpers_1.handleMaybePromise)(() => Array.fromAsync(this.bodyInit), chunks => {
2892
+ this._chunks = chunks;
2893
+ return this._chunks;
2894
+ });
2895
+ }
2896
+ const iterator = this.bodyInit[Symbol.asyncIterator]();
2897
+ const chunks = [];
2898
+ const collectValue = () => (0, promise_helpers_1.handleMaybePromise)(() => iterator.next(), ({ value, done }) => {
2899
+ if (value) {
2900
+ chunks.push(value);
2901
+ }
2902
+ if (!done) {
2903
+ return collectValue();
2904
+ }
2905
+ this._chunks = chunks;
2906
+ return this._chunks;
2907
+ });
2908
+ return collectValue();
2909
+ }
2910
+ const _body = this.generateBody();
2911
+ if (!_body) {
2912
+ this._chunks = [];
2913
+ return (0, utils_js_1.fakePromise)(this._chunks);
2914
+ }
2915
+ if (_body.readable.destroyed) {
2916
+ return (0, utils_js_1.fakePromise)((this._chunks = []));
2917
+ }
2918
+ const chunks = [];
2919
+ return new Promise((resolve, reject) => {
2920
+ _body.readable.on('data', chunk => {
2921
+ chunks.push(chunk);
2922
+ });
2923
+ _body.readable.once('error', reject);
2924
+ _body.readable.once('end', () => {
2925
+ resolve((this._chunks = chunks));
2926
+ });
2927
+ });
2928
+ }
2929
+ _collectChunksFromReadable() {
2930
+ if (this._chunks) {
2931
+ return (0, utils_js_1.fakePromise)(this._chunks);
2932
+ }
2933
+ this._chunks ||= this._doCollectChunksFromReadableJob();
2934
+ return this._chunks;
2935
+ }
2936
+ _blob = null;
2937
+ blob() {
2938
+ if (this._blob) {
2939
+ return (0, utils_js_1.fakePromise)(this._blob);
2940
+ }
2941
+ if (this.bodyType === BodyInitType.String) {
2942
+ this._text = this.bodyInit;
2943
+ this._blob = new Blob_js_1.PonyfillBlob([this._text], {
2944
+ type: this.contentType || 'text/plain;charset=UTF-8',
2945
+ size: this.contentLength,
2946
+ });
2947
+ }
2948
+ if (this.bodyType === BodyInitType.Blob) {
2949
+ this._blob = this.bodyInit;
2950
+ return (0, utils_js_1.fakePromise)(this._blob);
2951
+ }
2952
+ if (this._buffer) {
2953
+ this._blob = new Blob_js_1.PonyfillBlob([this._buffer], {
2954
+ type: this.contentType || '',
2955
+ size: this.contentLength,
2956
+ });
2957
+ return (0, utils_js_1.fakePromise)(this._blob);
2958
+ }
2959
+ return (0, utils_js_1.fakePromise)((0, promise_helpers_1.handleMaybePromise)(() => this._collectChunksFromReadable(), chunks => {
2960
+ this._blob = new Blob_js_1.PonyfillBlob(chunks, {
2961
+ type: this.contentType || '',
2962
+ size: this.contentLength,
2963
+ });
2964
+ return this._blob;
2965
+ }));
2966
+ }
2967
+ _formData = null;
2968
+ formData(opts) {
2969
+ if (this._formData) {
2970
+ return (0, utils_js_1.fakePromise)(this._formData);
2971
+ }
2972
+ if (this.bodyType === BodyInitType.FormData) {
2973
+ this._formData = this.bodyInit;
2974
+ return (0, utils_js_1.fakePromise)(this._formData);
2975
+ }
2976
+ this._formData = new FormData_js_1.PonyfillFormData();
2977
+ const _body = this.generateBody();
2978
+ if (_body == null) {
2979
+ return (0, utils_js_1.fakePromise)(this._formData);
2980
+ }
2981
+ const formDataLimits = {
2982
+ ...this.options.formDataLimits,
2983
+ ...opts?.formDataLimits,
2984
+ };
2985
+ return new Promise((resolve, reject) => {
2986
+ const stream = this.body?.readable;
2987
+ if (!stream) {
2988
+ return reject(new Error('No stream available'));
2989
+ }
2990
+ // form data file that is currently being processed, it's
2991
+ // important to keep track of it in case the stream ends early
2992
+ let currFile = null;
2993
+ const bb = new busboy_1.Busboy({
2994
+ headers: {
2995
+ 'content-length': typeof this.contentLength === 'number'
2996
+ ? this.contentLength.toString()
2997
+ : this.contentLength || '',
2998
+ 'content-type': this.contentType || '',
2999
+ },
3000
+ limits: formDataLimits,
3001
+ defCharset: 'utf-8',
3002
+ });
3003
+ if (this._signal) {
3004
+ (0, node_stream_1.addAbortSignal)(this._signal, bb);
3005
+ }
3006
+ let completed = false;
3007
+ const complete = (err) => {
3008
+ if (completed)
3009
+ return;
3010
+ completed = true;
3011
+ stream.unpipe(bb);
3012
+ bb.destroy();
3013
+ if (currFile) {
3014
+ currFile.destroy();
3015
+ currFile = null;
3016
+ }
3017
+ if (err) {
3018
+ reject(err);
3019
+ }
3020
+ else {
3021
+ // no error occured, this is a successful end/complete/finish
3022
+ resolve(this._formData);
3023
+ }
3024
+ };
3025
+ // we dont need to listen to the stream close event because bb will close or error when necessary
3026
+ // stream.on('close', complete);
3027
+ // stream can be aborted, for example
3028
+ stream.on('error', complete);
3029
+ bb.on('field', (name, value, fieldnameTruncated, valueTruncated) => {
3030
+ if (fieldnameTruncated) {
3031
+ return complete(new Error(`Field name size exceeded: ${formDataLimits?.fieldNameSize} bytes`));
3032
+ }
3033
+ if (valueTruncated) {
3034
+ return complete(new Error(`Field value size exceeded: ${formDataLimits?.fieldSize} bytes`));
3035
+ }
3036
+ this._formData.set(name, value);
3037
+ });
3038
+ bb.on('file', (name, fileStream, filename, _transferEncoding, mimeType) => {
3039
+ currFile = fileStream;
3040
+ const chunks = [];
3041
+ fileStream.on('data', chunk => {
3042
+ chunks.push(chunk);
3043
+ });
3044
+ fileStream.on('error', complete);
3045
+ fileStream.on('limit', () => {
3046
+ complete(new Error(`File size limit exceeded: ${formDataLimits?.fileSize} bytes`));
3047
+ });
3048
+ fileStream.on('close', () => {
3049
+ if (fileStream.truncated) {
3050
+ complete(new Error(`File size limit exceeded: ${formDataLimits?.fileSize} bytes`));
3051
+ }
3052
+ currFile = null;
3053
+ const file = new File_js_1.PonyfillFile(chunks, filename, { type: mimeType });
3054
+ this._formData.set(name, file);
3055
+ });
3056
+ });
3057
+ bb.on('fieldsLimit', () => {
3058
+ complete(new Error(`Fields limit exceeded: ${formDataLimits?.fields}`));
3059
+ });
3060
+ bb.on('filesLimit', () => {
3061
+ complete(new Error(`Files limit exceeded: ${formDataLimits?.files}`));
3062
+ });
3063
+ bb.on('partsLimit', () => {
3064
+ complete(new Error(`Parts limit exceeded: ${formDataLimits?.parts}`));
3065
+ });
3066
+ bb.on('end', complete);
3067
+ bb.on('finish', complete);
3068
+ bb.on('close', complete);
3069
+ bb.on('error', complete);
3070
+ stream.pipe(bb);
3071
+ });
3072
+ }
3073
+ buffer() {
3074
+ if (this._buffer) {
3075
+ return (0, utils_js_1.fakePromise)(this._buffer);
3076
+ }
3077
+ if (this._text) {
3078
+ this._buffer = node_buffer_1.Buffer.from(this._text, 'utf-8');
3079
+ return (0, utils_js_1.fakePromise)(this._buffer);
3080
+ }
3081
+ if (this.bodyType === BodyInitType.String) {
3082
+ return this.text().then(text => {
3083
+ this._text = text;
3084
+ this._buffer = node_buffer_1.Buffer.from(text, 'utf-8');
3085
+ return this._buffer;
3086
+ });
3087
+ }
3088
+ if (this.bodyType === BodyInitType.Blob) {
3089
+ if ((0, Blob_js_1.hasBufferMethod)(this.bodyInit)) {
3090
+ return this.bodyInit.buffer().then(buf => {
3091
+ this._buffer = buf;
3092
+ return this._buffer;
3093
+ });
3094
+ }
3095
+ if ((0, Blob_js_1.hasBytesMethod)(this.bodyInit)) {
3096
+ return this.bodyInit.bytes().then(bytes => {
3097
+ this._buffer = node_buffer_1.Buffer.from(bytes);
3098
+ return this._buffer;
3099
+ });
3100
+ }
3101
+ if ((0, Blob_js_1.hasArrayBufferMethod)(this.bodyInit)) {
3102
+ return this.bodyInit.arrayBuffer().then(buf => {
3103
+ this._buffer = node_buffer_1.Buffer.from(buf, undefined, buf.byteLength);
3104
+ return this._buffer;
3105
+ });
3106
+ }
3107
+ }
3108
+ return (0, utils_js_1.fakePromise)((0, promise_helpers_1.handleMaybePromise)(() => this._collectChunksFromReadable(), chunks => {
3109
+ if (chunks.length === 1) {
3110
+ this._buffer = chunks[0];
3111
+ return this._buffer;
3112
+ }
3113
+ this._buffer = node_buffer_1.Buffer.concat(chunks);
3114
+ return this._buffer;
3115
+ }));
3116
+ }
3117
+ bytes() {
3118
+ return this.buffer();
3119
+ }
3120
+ arrayBuffer() {
3121
+ // @ts-ignore - Mismatch between Buffer and ArrayBuffer
3122
+ return this.buffer();
3123
+ }
3124
+ _json = null;
3125
+ json() {
3126
+ if (this._json) {
3127
+ return (0, utils_js_1.fakePromise)(this._json);
3128
+ }
3129
+ return this.text().then(text => {
3130
+ try {
3131
+ this._json = JSON.parse(text);
3132
+ }
3133
+ catch (e) {
3134
+ if (e instanceof SyntaxError) {
3135
+ e.message += `, "${text}" is not valid JSON`;
3136
+ }
3137
+ throw e;
3138
+ }
3139
+ return this._json;
3140
+ });
3141
+ }
3142
+ _text = null;
3143
+ text() {
3144
+ if (this._text) {
3145
+ return (0, utils_js_1.fakePromise)(this._text);
3146
+ }
3147
+ if (this.bodyType === BodyInitType.String) {
3148
+ this._text = this.bodyInit;
3149
+ return (0, utils_js_1.fakePromise)(this._text);
3150
+ }
3151
+ return this.buffer().then(buffer => {
3152
+ this._text = buffer.toString('utf-8');
3153
+ return this._text;
3154
+ });
3155
+ }
3156
+ }
3157
+ Body.PonyfillBody = PonyfillBody;
3158
+ function processBodyInit(bodyInit) {
3159
+ if (bodyInit == null) {
3160
+ return {
3161
+ bodyFactory: () => null,
3162
+ contentType: null,
3163
+ contentLength: null,
3164
+ };
3165
+ }
3166
+ if (typeof bodyInit === 'string') {
3167
+ const contentLength = node_buffer_1.Buffer.byteLength(bodyInit);
3168
+ return {
3169
+ bodyType: BodyInitType.String,
3170
+ contentType: 'text/plain;charset=UTF-8',
3171
+ contentLength,
3172
+ bodyFactory() {
3173
+ const readable = node_stream_1.Readable.from(node_buffer_1.Buffer.from(bodyInit, 'utf-8'));
3174
+ return new ReadableStream_js_1.PonyfillReadableStream(readable);
3175
+ },
3176
+ };
3177
+ }
3178
+ if (node_buffer_1.Buffer.isBuffer(bodyInit)) {
3179
+ const buffer = bodyInit;
3180
+ return {
3181
+ bodyType: BodyInitType.Buffer,
3182
+ contentType: null,
3183
+ contentLength: bodyInit.length,
3184
+ buffer: bodyInit,
3185
+ bodyFactory() {
3186
+ const readable = node_stream_1.Readable.from(buffer);
3187
+ const body = new ReadableStream_js_1.PonyfillReadableStream(readable);
3188
+ return body;
3189
+ },
3190
+ };
3191
+ }
3192
+ if ((0, utils_js_1.isArrayBufferView)(bodyInit)) {
3193
+ const buffer = node_buffer_1.Buffer.from(bodyInit.buffer, bodyInit.byteOffset, bodyInit.byteLength);
3194
+ return {
3195
+ bodyType: BodyInitType.Buffer,
3196
+ contentLength: bodyInit.byteLength,
3197
+ contentType: null,
3198
+ buffer,
3199
+ bodyFactory() {
3200
+ const readable = node_stream_1.Readable.from(buffer);
3201
+ const body = new ReadableStream_js_1.PonyfillReadableStream(readable);
3202
+ return body;
3203
+ },
3204
+ };
3205
+ }
3206
+ if (bodyInit instanceof ReadableStream_js_1.PonyfillReadableStream && bodyInit.readable != null) {
3207
+ const readableStream = bodyInit;
3208
+ return {
3209
+ bodyType: BodyInitType.ReadableStream,
3210
+ bodyFactory: () => readableStream,
3211
+ contentType: null,
3212
+ contentLength: null,
3213
+ };
3214
+ }
3215
+ if (isBlob(bodyInit)) {
3216
+ const blob = bodyInit;
3217
+ return {
3218
+ bodyType: BodyInitType.Blob,
3219
+ contentType: bodyInit.type,
3220
+ contentLength: bodyInit.size,
3221
+ bodyFactory() {
3222
+ return blob.stream();
3223
+ },
3224
+ };
3225
+ }
3226
+ if (bodyInit instanceof ArrayBuffer) {
3227
+ const contentLength = bodyInit.byteLength;
3228
+ const buffer = node_buffer_1.Buffer.from(bodyInit, undefined, bodyInit.byteLength);
3229
+ return {
3230
+ bodyType: BodyInitType.Buffer,
3231
+ contentType: null,
3232
+ contentLength,
3233
+ buffer,
3234
+ bodyFactory() {
3235
+ const readable = node_stream_1.Readable.from(buffer);
3236
+ const body = new ReadableStream_js_1.PonyfillReadableStream(readable);
3237
+ return body;
3238
+ },
3239
+ };
3240
+ }
3241
+ if (bodyInit instanceof node_stream_1.Readable) {
3242
+ return {
3243
+ bodyType: BodyInitType.Readable,
3244
+ contentType: null,
3245
+ contentLength: null,
3246
+ bodyFactory() {
3247
+ const body = new ReadableStream_js_1.PonyfillReadableStream(bodyInit);
3248
+ return body;
3249
+ },
3250
+ };
3251
+ }
3252
+ if (isURLSearchParams(bodyInit)) {
3253
+ const contentType = 'application/x-www-form-urlencoded;charset=UTF-8';
3254
+ return {
3255
+ bodyType: BodyInitType.String,
3256
+ contentType,
3257
+ contentLength: null,
3258
+ bodyFactory() {
3259
+ const body = new ReadableStream_js_1.PonyfillReadableStream(node_stream_1.Readable.from(bodyInit.toString()));
3260
+ return body;
3261
+ },
3262
+ };
3263
+ }
3264
+ if (isFormData(bodyInit)) {
3265
+ const boundary = Math.random().toString(36).substr(2);
3266
+ const contentType = `multipart/form-data; boundary=${boundary}`;
3267
+ return {
3268
+ bodyType: BodyInitType.FormData,
3269
+ contentType,
3270
+ contentLength: null,
3271
+ bodyFactory() {
3272
+ return (0, FormData_js_1.getStreamFromFormData)(bodyInit, boundary);
3273
+ },
3274
+ };
3275
+ }
3276
+ if (isReadableStream(bodyInit)) {
3277
+ return {
3278
+ contentType: null,
3279
+ contentLength: null,
3280
+ bodyFactory() {
3281
+ return new ReadableStream_js_1.PonyfillReadableStream(bodyInit);
3282
+ },
3283
+ };
3284
+ }
3285
+ if (bodyInit[Symbol.iterator] || bodyInit[Symbol.asyncIterator]) {
3286
+ return {
3287
+ contentType: null,
3288
+ contentLength: null,
3289
+ bodyType: BodyInitType.AsyncIterable,
3290
+ bodyFactory() {
3291
+ const readable = node_stream_1.Readable.from(bodyInit);
3292
+ return new ReadableStream_js_1.PonyfillReadableStream(readable);
3293
+ },
3294
+ };
3295
+ }
3296
+ throw new Error('Unknown body type');
3297
+ }
3298
+ function isFormData(value) {
3299
+ return value?.forEach != null;
3300
+ }
3301
+ function isBlob(value) {
3302
+ return value?.stream != null && typeof value.stream === 'function';
3303
+ }
3304
+ function isURLSearchParams(value) {
3305
+ return value?.sort != null;
3306
+ }
3307
+ function isReadableStream(value) {
3308
+ return value?.getReader != null;
3309
+ }
3310
+ return Body;
3311
+ }
3312
+
3313
+ var Headers = {};
3314
+
3315
+ var hasRequiredHeaders;
3316
+
3317
+ function requireHeaders () {
3318
+ if (hasRequiredHeaders) return Headers;
3319
+ hasRequiredHeaders = 1;
3320
+ Object.defineProperty(Headers, "__esModule", { value: true });
3321
+ Headers.PonyfillHeaders = void 0;
3322
+ Headers.isHeadersLike = isHeadersLike;
3323
+ const node_util_1 = require$$1$1;
3324
+ const IteratorObject_js_1 = requireIteratorObject();
3325
+ function isHeadersLike(headers) {
3326
+ return headers?.get && headers?.forEach;
3327
+ }
3328
+ class PonyfillHeaders {
3329
+ headersInit;
3330
+ _map;
3331
+ objectNormalizedKeysOfHeadersInit = [];
3332
+ objectOriginalKeysOfHeadersInit = [];
3333
+ _setCookies;
3334
+ constructor(headersInit) {
3335
+ this.headersInit = headersInit;
3336
+ }
3337
+ // perf: we don't need to build `this.map` for Requests, as we can access the headers directly
3338
+ _get(key) {
3339
+ const normalized = key.toLowerCase();
3340
+ if (normalized === 'set-cookie' && this._setCookies?.length) {
3341
+ return this._setCookies.join(', ');
3342
+ }
3343
+ // If the map is built, reuse it
3344
+ if (this._map) {
3345
+ return this._map.get(normalized) || null;
3346
+ }
3347
+ // If the map is not built, try to get the value from the this.headersInit
3348
+ if (this.headersInit == null) {
3349
+ return null;
3350
+ }
3351
+ if (Array.isArray(this.headersInit)) {
3352
+ const found = this.headersInit.filter(([headerKey]) => headerKey.toLowerCase() === normalized);
3353
+ if (found.length === 0) {
3354
+ return null;
3355
+ }
3356
+ if (found.length === 1) {
3357
+ return found[0][1];
3358
+ }
3359
+ return found.map(([, value]) => value).join(', ');
3360
+ }
3361
+ else if (isHeadersLike(this.headersInit)) {
3362
+ return this.headersInit.get(normalized);
3363
+ }
3364
+ else {
3365
+ const initValue = this.headersInit[key] || this.headersInit[normalized];
3366
+ if (initValue != null) {
3367
+ return initValue;
3368
+ }
3369
+ if (!this.objectNormalizedKeysOfHeadersInit.length) {
3370
+ Object.keys(this.headersInit).forEach(k => {
3371
+ this.objectOriginalKeysOfHeadersInit.push(k);
3372
+ this.objectNormalizedKeysOfHeadersInit.push(k.toLowerCase());
3373
+ });
3374
+ }
3375
+ const index = this.objectNormalizedKeysOfHeadersInit.indexOf(normalized);
3376
+ if (index === -1) {
3377
+ return null;
3378
+ }
3379
+ const originalKey = this.objectOriginalKeysOfHeadersInit[index];
3380
+ return this.headersInit[originalKey];
3381
+ }
3382
+ }
3383
+ // perf: Build the map of headers lazily, only when we need to access all headers or write to it.
3384
+ // I could do a getter here, but I'm too lazy to type `getter`.
3385
+ getMap() {
3386
+ if (!this._map) {
3387
+ this._setCookies ||= [];
3388
+ if (this.headersInit != null) {
3389
+ if (Array.isArray(this.headersInit)) {
3390
+ this._map = new Map();
3391
+ for (const [key, value] of this.headersInit) {
3392
+ const normalizedKey = key.toLowerCase();
3393
+ if (normalizedKey === 'set-cookie') {
3394
+ this._setCookies.push(value);
3395
+ continue;
3396
+ }
3397
+ this._map.set(normalizedKey, value);
3398
+ }
3399
+ }
3400
+ else if (isHeadersLike(this.headersInit)) {
3401
+ this._map = new Map();
3402
+ this.headersInit.forEach((value, key) => {
3403
+ if (key === 'set-cookie') {
3404
+ this._setCookies ||= [];
3405
+ this._setCookies.push(value);
3406
+ return;
3407
+ }
3408
+ this._map.set(key, value);
3409
+ });
3410
+ }
3411
+ else {
3412
+ this._map = new Map();
3413
+ for (const initKey in this.headersInit) {
3414
+ const initValue = this.headersInit[initKey];
3415
+ if (initValue != null) {
3416
+ const normalizedKey = initKey.toLowerCase();
3417
+ if (normalizedKey === 'set-cookie') {
3418
+ this._setCookies ||= [];
3419
+ this._setCookies.push(initValue);
3420
+ continue;
3421
+ }
3422
+ this._map.set(normalizedKey, initValue);
3423
+ }
3424
+ }
3425
+ }
3426
+ }
3427
+ else {
3428
+ this._map = new Map();
3429
+ }
3430
+ }
3431
+ return this._map;
3432
+ }
3433
+ append(name, value) {
3434
+ const key = name.toLowerCase();
3435
+ if (key === 'set-cookie') {
3436
+ this._setCookies ||= [];
3437
+ this._setCookies.push(value);
3438
+ return;
3439
+ }
3440
+ const existingValue = this.getMap().get(key);
3441
+ const finalValue = existingValue ? `${existingValue}, ${value}` : value;
3442
+ this.getMap().set(key, finalValue);
3443
+ }
3444
+ get(name) {
3445
+ const value = this._get(name);
3446
+ if (value == null) {
3447
+ return null;
3448
+ }
3449
+ return value.toString();
3450
+ }
3451
+ has(name) {
3452
+ const key = name.toLowerCase();
3453
+ if (key === 'set-cookie') {
3454
+ return !!this._setCookies?.length;
3455
+ }
3456
+ return !!this._get(name); // we might need to check if header exists and not just check if it's not nullable
3457
+ }
3458
+ set(name, value) {
3459
+ const key = name.toLowerCase();
3460
+ if (key === 'set-cookie') {
3461
+ this._setCookies = [value];
3462
+ return;
3463
+ }
3464
+ if (!this._map && this.headersInit != null) {
3465
+ if (Array.isArray(this.headersInit)) {
3466
+ const found = this.headersInit.find(([headerKey]) => headerKey.toLowerCase() === key);
3467
+ if (found) {
3468
+ found[1] = value;
3469
+ }
3470
+ else {
3471
+ this.headersInit.push([key, value]);
3472
+ }
3473
+ return;
3474
+ }
3475
+ else if (isHeadersLike(this.headersInit)) {
3476
+ this.headersInit.set(key, value);
3477
+ return;
3478
+ }
3479
+ else {
3480
+ this.headersInit[key] = value;
3481
+ return;
3482
+ }
3483
+ }
3484
+ this.getMap().set(key, value);
3485
+ }
3486
+ delete(name) {
3487
+ const key = name.toLowerCase();
3488
+ if (key === 'set-cookie') {
3489
+ this._setCookies = [];
3490
+ return;
3491
+ }
3492
+ this.getMap().delete(key);
3493
+ }
3494
+ forEach(callback) {
3495
+ this._setCookies?.forEach(setCookie => {
3496
+ callback(setCookie, 'set-cookie', this);
3497
+ });
3498
+ if (!this._map) {
3499
+ if (this.headersInit) {
3500
+ if (Array.isArray(this.headersInit)) {
3501
+ this.headersInit.forEach(([key, value]) => {
3502
+ callback(value, key, this);
3503
+ });
3504
+ return;
3505
+ }
3506
+ if (isHeadersLike(this.headersInit)) {
3507
+ this.headersInit.forEach(callback);
3508
+ return;
3509
+ }
3510
+ Object.entries(this.headersInit).forEach(([key, value]) => {
3511
+ if (value != null) {
3512
+ callback(value, key, this);
3513
+ }
3514
+ });
3515
+ }
3516
+ return;
3517
+ }
3518
+ this.getMap().forEach((value, key) => {
3519
+ callback(value, key, this);
3520
+ });
3521
+ }
3522
+ *_keys() {
3523
+ if (this._setCookies?.length) {
3524
+ yield 'set-cookie';
3525
+ }
3526
+ if (!this._map) {
3527
+ if (this.headersInit) {
3528
+ if (Array.isArray(this.headersInit)) {
3529
+ yield* this.headersInit.map(([key]) => key)[Symbol.iterator]();
3530
+ return;
3531
+ }
3532
+ if (isHeadersLike(this.headersInit)) {
3533
+ yield* this.headersInit.keys();
3534
+ return;
3535
+ }
3536
+ yield* Object.keys(this.headersInit)[Symbol.iterator]();
3537
+ return;
3538
+ }
3539
+ }
3540
+ yield* this.getMap().keys();
3541
+ }
3542
+ keys() {
3543
+ return new IteratorObject_js_1.PonyfillIteratorObject(this._keys(), 'HeadersIterator');
3544
+ }
3545
+ *_values() {
3546
+ if (this._setCookies?.length) {
3547
+ yield* this._setCookies;
3548
+ }
3549
+ if (!this._map) {
3550
+ if (this.headersInit) {
3551
+ if (Array.isArray(this.headersInit)) {
3552
+ yield* this.headersInit.map(([, value]) => value)[Symbol.iterator]();
3553
+ return;
3554
+ }
3555
+ if (isHeadersLike(this.headersInit)) {
3556
+ yield* this.headersInit.values();
3557
+ return;
3558
+ }
3559
+ yield* Object.values(this.headersInit)[Symbol.iterator]();
3560
+ return;
3561
+ }
3562
+ }
3563
+ yield* this.getMap().values();
3564
+ }
3565
+ values() {
3566
+ return new IteratorObject_js_1.PonyfillIteratorObject(this._values(), 'HeadersIterator');
3567
+ }
3568
+ *_entries() {
3569
+ if (this._setCookies?.length) {
3570
+ yield* this._setCookies.map(cookie => ['set-cookie', cookie]);
3571
+ }
3572
+ if (!this._map) {
3573
+ if (this.headersInit) {
3574
+ if (Array.isArray(this.headersInit)) {
3575
+ yield* this.headersInit;
3576
+ return;
3577
+ }
3578
+ if (isHeadersLike(this.headersInit)) {
3579
+ yield* this.headersInit.entries();
3580
+ return;
3581
+ }
3582
+ yield* Object.entries(this.headersInit);
3583
+ return;
3584
+ }
3585
+ }
3586
+ yield* this.getMap().entries();
3587
+ }
3588
+ entries() {
3589
+ return new IteratorObject_js_1.PonyfillIteratorObject(this._entries(), 'HeadersIterator');
3590
+ }
3591
+ getSetCookie() {
3592
+ if (!this._setCookies) {
3593
+ this.getMap();
3594
+ }
3595
+ return this._setCookies;
3596
+ }
3597
+ [Symbol.iterator]() {
3598
+ return this.entries();
3599
+ }
3600
+ [Symbol.for('nodejs.util.inspect.custom')]() {
3601
+ const record = {};
3602
+ this.forEach((value, key) => {
3603
+ if (key === 'set-cookie') {
3604
+ record['set-cookie'] = this._setCookies || [];
3605
+ }
3606
+ else {
3607
+ record[key] = value?.includes(',') ? value.split(',').map(el => el.trim()) : value;
3608
+ }
3609
+ });
3610
+ return `Headers ${(0, node_util_1.inspect)(record)}`;
3611
+ }
3612
+ }
3613
+ Headers.PonyfillHeaders = PonyfillHeaders;
3614
+ return Headers;
3615
+ }
3616
+
3617
+ var hasRequiredResponse;
3618
+
3619
+ function requireResponse () {
3620
+ if (hasRequiredResponse) return Response;
3621
+ hasRequiredResponse = 1;
3622
+ Object.defineProperty(Response, "__esModule", { value: true });
3623
+ Response.PonyfillResponse = void 0;
3624
+ const node_http_1 = require$$0$3;
3625
+ const Body_js_1 = requireBody();
3626
+ const Headers_js_1 = requireHeaders();
3627
+ const JSON_CONTENT_TYPE = 'application/json; charset=utf-8';
3628
+ class PonyfillResponse extends Body_js_1.PonyfillBody {
3629
+ headers;
3630
+ constructor(body, init) {
3631
+ super(body || null, init);
3632
+ this.headers =
3633
+ init?.headers && (0, Headers_js_1.isHeadersLike)(init.headers)
3634
+ ? init.headers
3635
+ : new Headers_js_1.PonyfillHeaders(init?.headers);
3636
+ this.status = init?.status || 200;
3637
+ this.statusText = init?.statusText || node_http_1.STATUS_CODES[this.status] || 'OK';
3638
+ this.url = init?.url || '';
3639
+ this.redirected = init?.redirected || false;
3640
+ this.type = init?.type || 'default';
3641
+ this.handleContentLengthHeader();
3642
+ }
3643
+ get ok() {
3644
+ return this.status >= 200 && this.status < 300;
3645
+ }
3646
+ status;
3647
+ statusText;
3648
+ url;
3649
+ redirected;
3650
+ type;
3651
+ clone() {
3652
+ return this;
3653
+ }
3654
+ static error() {
3655
+ return new PonyfillResponse(null, {
3656
+ status: 500,
3657
+ statusText: 'Internal Server Error',
3658
+ });
3659
+ }
3660
+ static redirect(url, status = 302) {
3661
+ if (status < 300 || status > 399) {
3662
+ throw new RangeError('Invalid status code');
3663
+ }
3664
+ return new PonyfillResponse(null, {
3665
+ headers: {
3666
+ location: url,
3667
+ },
3668
+ status,
3669
+ });
3670
+ }
3671
+ static json(data, init) {
3672
+ const bodyInit = JSON.stringify(data);
3673
+ if (!init) {
3674
+ init = {
3675
+ headers: {
3676
+ 'content-type': JSON_CONTENT_TYPE,
3677
+ 'content-length': Buffer.byteLength(bodyInit).toString(),
3678
+ },
3679
+ };
3680
+ }
3681
+ else if (!init.headers) {
3682
+ init.headers = {
3683
+ 'content-type': JSON_CONTENT_TYPE,
3684
+ 'content-length': Buffer.byteLength(bodyInit).toString(),
3685
+ };
3686
+ }
3687
+ else if ((0, Headers_js_1.isHeadersLike)(init.headers)) {
3688
+ if (!init.headers.has('content-type')) {
3689
+ init.headers.set('content-type', JSON_CONTENT_TYPE);
3690
+ }
3691
+ if (!init.headers.has('content-length')) {
3692
+ init.headers.set('content-length', Buffer.byteLength(bodyInit).toString());
3693
+ }
3694
+ }
3695
+ else if (Array.isArray(init.headers)) {
3696
+ let contentTypeExists = false;
3697
+ let contentLengthExists = false;
3698
+ for (const [key] of init.headers) {
3699
+ if (contentLengthExists && contentTypeExists) {
3700
+ break;
3701
+ }
3702
+ if (!contentTypeExists && key.toLowerCase() === 'content-type') {
3703
+ contentTypeExists = true;
3704
+ }
3705
+ else if (!contentLengthExists && key.toLowerCase() === 'content-length') {
3706
+ contentLengthExists = true;
3707
+ }
3708
+ }
3709
+ if (!contentTypeExists) {
3710
+ init.headers.push(['content-type', JSON_CONTENT_TYPE]);
3711
+ }
3712
+ if (!contentLengthExists) {
3713
+ init.headers.push(['content-length', Buffer.byteLength(bodyInit).toString()]);
3714
+ }
3715
+ }
3716
+ else if (typeof init.headers === 'object') {
3717
+ if (init.headers?.['content-type'] == null) {
3718
+ init.headers['content-type'] = JSON_CONTENT_TYPE;
3719
+ }
3720
+ if (init.headers?.['content-length'] == null) {
3721
+ init.headers['content-length'] = Buffer.byteLength(bodyInit).toString();
3722
+ }
3723
+ }
3724
+ return new PonyfillResponse(bodyInit, init);
3725
+ }
3726
+ [Symbol.toStringTag] = 'Response';
3727
+ }
3728
+ Response.PonyfillResponse = PonyfillResponse;
3729
+ return Response;
3730
+ }
3731
+
3732
+ var hasRequiredFetchCurl;
3733
+
3734
+ function requireFetchCurl () {
3735
+ if (hasRequiredFetchCurl) return fetchCurl;
3736
+ hasRequiredFetchCurl = 1;
3737
+ Object.defineProperty(fetchCurl, "__esModule", { value: true });
3738
+ fetchCurl.fetchCurl = fetchCurl$1;
3739
+ const node_stream_1 = require$$0$1;
3740
+ const node_tls_1 = require$$1$2;
3741
+ const promise_helpers_1 = require$$4;
3742
+ const Response_js_1 = requireResponse();
3743
+ const utils_js_1 = requireUtils();
3744
+ function fetchCurl$1(fetchRequest) {
3745
+ const { Curl, CurlFeature, CurlPause, CurlProgressFunc } = globalThis['libcurl'];
3746
+ const curlHandle = new Curl();
3747
+ curlHandle.enable(CurlFeature.NoDataParsing);
3748
+ curlHandle.setOpt('URL', fetchRequest.url);
3749
+ if (process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0') {
3750
+ curlHandle.setOpt('SSL_VERIFYPEER', false);
3751
+ }
3752
+ if (process.env.NODE_EXTRA_CA_CERTS) {
3753
+ curlHandle.setOpt('CAINFO', process.env.NODE_EXTRA_CA_CERTS);
3754
+ }
3755
+ else {
3756
+ curlHandle.setOpt('CAINFO_BLOB', node_tls_1.rootCertificates.join('\n'));
3757
+ }
3758
+ curlHandle.enable(CurlFeature.StreamResponse);
3759
+ let signal;
3760
+ if (fetchRequest._signal === null) {
3761
+ signal = undefined;
3762
+ }
3763
+ else if (fetchRequest._signal) {
3764
+ signal = fetchRequest._signal;
3765
+ }
3766
+ curlHandle.setStreamProgressCallback(function () {
3767
+ return signal?.aborted ? (process.env.DEBUG ? CurlProgressFunc.Continue : 1) : 0;
3768
+ });
3769
+ if (fetchRequest['bodyType'] === 'String') {
3770
+ curlHandle.setOpt('POSTFIELDS', fetchRequest['bodyInit']);
3771
+ }
3772
+ else {
3773
+ const nodeReadable = (fetchRequest.body != null
3774
+ ? (0, utils_js_1.isNodeReadable)(fetchRequest.body)
3775
+ ? fetchRequest.body
3776
+ : node_stream_1.Readable.from(fetchRequest.body)
3777
+ : null);
3778
+ if (nodeReadable) {
3779
+ curlHandle.setOpt('UPLOAD', true);
3780
+ curlHandle.setUploadStream(nodeReadable);
3781
+ }
3782
+ }
3783
+ if (process.env.DEBUG) {
3784
+ curlHandle.setOpt('VERBOSE', true);
3785
+ }
3786
+ curlHandle.setOpt('TRANSFER_ENCODING', false);
3787
+ curlHandle.setOpt('HTTP_TRANSFER_DECODING', true);
3788
+ curlHandle.setOpt('FOLLOWLOCATION', fetchRequest.redirect === 'follow');
3789
+ curlHandle.setOpt('MAXREDIRS', 20);
3790
+ curlHandle.setOpt('ACCEPT_ENCODING', '');
3791
+ curlHandle.setOpt('CUSTOMREQUEST', fetchRequest.method);
3792
+ const headersSerializer = fetchRequest.headersSerializer || utils_js_1.defaultHeadersSerializer;
3793
+ let size;
3794
+ const curlHeaders = headersSerializer(fetchRequest.headers, value => {
3795
+ size = Number(value);
3796
+ });
3797
+ if (size != null) {
3798
+ curlHandle.setOpt('INFILESIZE', size);
3799
+ }
3800
+ curlHandle.setOpt('HTTPHEADER', curlHeaders);
3801
+ curlHandle.enable(CurlFeature.NoHeaderParsing);
3802
+ const deferredPromise = (0, promise_helpers_1.createDeferredPromise)();
3803
+ let streamResolved;
3804
+ function onAbort() {
3805
+ if (curlHandle.isOpen) {
3806
+ try {
3807
+ curlHandle.pause(CurlPause.Recv);
3808
+ }
3809
+ catch (e) {
3810
+ deferredPromise.reject(e);
3811
+ }
3812
+ }
3813
+ }
3814
+ signal?.addEventListener('abort', onAbort, { once: true });
3815
+ curlHandle.once('end', function endListener() {
3816
+ try {
3817
+ curlHandle.close();
3818
+ }
3819
+ catch (e) {
3820
+ deferredPromise.reject(e);
3821
+ }
3822
+ signal?.removeEventListener('abort', onAbort);
3823
+ });
3824
+ curlHandle.once('error', function errorListener(error) {
3825
+ if (streamResolved && !streamResolved.closed && !streamResolved.destroyed) {
3826
+ streamResolved.destroy(error);
3827
+ }
3828
+ else {
3829
+ if (error.message === 'Operation was aborted by an application callback') {
3830
+ error.message = 'The operation was aborted.';
3831
+ }
3832
+ deferredPromise.reject(error);
3833
+ }
3834
+ try {
3835
+ curlHandle.close();
3836
+ }
3837
+ catch (e) {
3838
+ deferredPromise.reject(e);
3839
+ }
3840
+ });
3841
+ curlHandle.once('stream', function streamListener(stream, status, headersBuf) {
3842
+ const outputStream = stream.pipe(new node_stream_1.PassThrough(), {
3843
+ end: true,
3844
+ });
3845
+ const headersFlat = headersBuf
3846
+ .toString('utf8')
3847
+ .split(/\r?\n|\r/g)
3848
+ .filter(headerFilter => {
3849
+ if (headerFilter && !headerFilter.startsWith('HTTP/')) {
3850
+ if (fetchRequest.redirect === 'error' &&
3851
+ headerFilter.toLowerCase().includes('location') &&
3852
+ (0, utils_js_1.shouldRedirect)(status)) {
3853
+ if (!stream.destroyed) {
3854
+ stream.resume();
3855
+ }
3856
+ outputStream.destroy();
3857
+ deferredPromise.reject(new Error('redirect is not allowed'));
3858
+ }
3859
+ return true;
3860
+ }
3861
+ return false;
3862
+ });
3863
+ const headersInit = headersFlat.map(headerFlat => headerFlat.split(/:\s(.+)/).slice(0, 2));
3864
+ const ponyfillResponse = new Response_js_1.PonyfillResponse(outputStream, {
3865
+ status,
3866
+ headers: headersInit,
3867
+ url: curlHandle.getInfo(Curl.info.REDIRECT_URL)?.toString() || fetchRequest.url,
3868
+ redirected: Number(curlHandle.getInfo(Curl.info.REDIRECT_COUNT)) > 0,
3869
+ });
3870
+ deferredPromise.resolve(ponyfillResponse);
3871
+ streamResolved = outputStream;
3872
+ });
3873
+ setImmediate(() => {
3874
+ curlHandle.perform();
3875
+ });
3876
+ return deferredPromise.promise;
3877
+ }
3878
+ return fetchCurl;
3879
+ }
3880
+
3881
+ var fetchNodeHttp = {};
3882
+
3883
+ var Request = {};
3884
+
3885
+ var URL$2 = {};
3886
+
3887
+ var hasRequiredURL;
3888
+
3889
+ function requireURL () {
3890
+ if (hasRequiredURL) return URL$2;
3891
+ hasRequiredURL = 1;
3892
+ Object.defineProperty(URL$2, "__esModule", { value: true });
3893
+ URL$2.PonyfillURL = void 0;
3894
+ const tslib_1 = require$$0$4;
3895
+ const node_buffer_1 = tslib_1.__importDefault(require$$0$2);
3896
+ const node_crypto_1 = require$$2;
3897
+ const NativeURL = globalThis.URL;
3898
+ class URL extends NativeURL {
3899
+ // This part is only needed to handle `PonyfillBlob` objects
3900
+ static blobRegistry = new Map();
3901
+ static createObjectURL(blob) {
3902
+ const blobUrl = `blob:whatwgnode:${(0, node_crypto_1.randomUUID)()}`;
3903
+ this.blobRegistry.set(blobUrl, blob);
3904
+ return blobUrl;
3905
+ }
3906
+ static revokeObjectURL(url) {
3907
+ if (!this.blobRegistry.has(url)) {
3908
+ NativeURL.revokeObjectURL(url);
3909
+ }
3910
+ else {
3911
+ this.blobRegistry.delete(url);
3912
+ }
3913
+ }
3914
+ static getBlobFromURL(url) {
3915
+ return (this.blobRegistry.get(url) || node_buffer_1.default?.resolveObjectURL?.(url));
3916
+ }
3917
+ }
3918
+ URL$2.PonyfillURL = URL;
3919
+ return URL$2;
3920
+ }
3921
+
3922
+ var hasRequiredRequest;
3923
+
3924
+ function requireRequest () {
3925
+ if (hasRequiredRequest) return Request;
3926
+ hasRequiredRequest = 1;
3927
+ Object.defineProperty(Request, "__esModule", { value: true });
3928
+ Request.PonyfillRequest = void 0;
3929
+ const node_http_1 = require$$0$3;
3930
+ const node_https_1 = require$$1$3;
3931
+ const Body_js_1 = requireBody();
3932
+ const Headers_js_1 = requireHeaders();
3933
+ const URL_js_1 = requireURL();
3934
+ function isRequest(input) {
3935
+ return input[Symbol.toStringTag] === 'Request';
3936
+ }
3937
+ function isURL(obj) {
3938
+ return obj?.href != null;
3939
+ }
3940
+ class PonyfillRequest extends Body_js_1.PonyfillBody {
3941
+ constructor(input, options) {
3942
+ let _url;
3943
+ let _parsedUrl;
3944
+ let bodyInit = null;
3945
+ let requestInit;
3946
+ if (typeof input === 'string') {
3947
+ _url = input;
3948
+ }
3949
+ else if (isURL(input)) {
3950
+ _parsedUrl = input;
3951
+ }
3952
+ else if (isRequest(input)) {
3953
+ if (input._parsedUrl) {
3954
+ _parsedUrl = input._parsedUrl;
3955
+ }
3956
+ else if (input._url) {
3957
+ _url = input._url;
3958
+ }
3959
+ else {
3960
+ _url = input.url;
3961
+ }
3962
+ bodyInit = input.body;
3963
+ requestInit = input;
3964
+ }
3965
+ if (options != null) {
3966
+ bodyInit = options.body || null;
3967
+ requestInit = options;
3968
+ }
3969
+ super(bodyInit, requestInit);
3970
+ this._url = _url;
3971
+ this._parsedUrl = _parsedUrl;
3972
+ this.cache = requestInit?.cache || 'default';
3973
+ this.credentials = requestInit?.credentials || 'same-origin';
3974
+ this.headers =
3975
+ requestInit?.headers && (0, Headers_js_1.isHeadersLike)(requestInit.headers)
3976
+ ? requestInit.headers
3977
+ : new Headers_js_1.PonyfillHeaders(requestInit?.headers);
3978
+ this.integrity = requestInit?.integrity || '';
3979
+ this.keepalive = requestInit?.keepalive != null ? requestInit?.keepalive : false;
3980
+ this.method = requestInit?.method?.toUpperCase() || 'GET';
3981
+ this.mode = requestInit?.mode || 'cors';
3982
+ this.redirect = requestInit?.redirect || 'follow';
3983
+ this.referrer = requestInit?.referrer || 'about:client';
3984
+ this.referrerPolicy = requestInit?.referrerPolicy || 'no-referrer';
3985
+ this.headersSerializer = requestInit?.headersSerializer;
3986
+ this.duplex = requestInit?.duplex || 'half';
3987
+ this.destination = 'document';
3988
+ this.priority = 'auto';
3989
+ if (this.method !== 'GET' && this.method !== 'HEAD') {
3990
+ this.handleContentLengthHeader(true);
3991
+ }
3992
+ if (requestInit?.agent != null) {
3993
+ const protocol = _parsedUrl?.protocol || _url || this.url;
3994
+ if (requestInit.agent === false) {
3995
+ this.agent = false;
3996
+ }
3997
+ else if (protocol.startsWith('http:') && requestInit.agent instanceof node_http_1.Agent) {
3998
+ this.agent = requestInit.agent;
3999
+ }
4000
+ else if (protocol.startsWith('https:') && requestInit.agent instanceof node_https_1.Agent) {
4001
+ this.agent = requestInit.agent;
4002
+ }
4003
+ }
4004
+ }
4005
+ headersSerializer;
4006
+ cache;
4007
+ credentials;
4008
+ destination;
4009
+ headers;
4010
+ integrity;
4011
+ keepalive;
4012
+ method;
4013
+ mode;
4014
+ priority;
4015
+ redirect;
4016
+ referrer;
4017
+ referrerPolicy;
4018
+ _url;
4019
+ get signal() {
4020
+ this._signal ||= new AbortController().signal;
4021
+ return this._signal;
4022
+ }
4023
+ get url() {
4024
+ if (this._url == null) {
4025
+ if (this._parsedUrl) {
4026
+ this._url = this._parsedUrl.toString();
4027
+ }
4028
+ else {
4029
+ throw new TypeError('Invalid URL');
4030
+ }
4031
+ }
4032
+ return this._url;
4033
+ }
4034
+ _parsedUrl;
4035
+ get parsedUrl() {
4036
+ if (this._parsedUrl == null) {
4037
+ if (this._url != null) {
4038
+ this._parsedUrl = new URL_js_1.PonyfillURL(this._url, 'http://localhost');
4039
+ }
4040
+ else {
4041
+ throw new TypeError('Invalid URL');
4042
+ }
4043
+ }
4044
+ return this._parsedUrl;
4045
+ }
4046
+ duplex;
4047
+ agent;
4048
+ clone() {
4049
+ return this;
4050
+ }
4051
+ [Symbol.toStringTag] = 'Request';
4052
+ }
4053
+ Request.PonyfillRequest = PonyfillRequest;
4054
+ return Request;
4055
+ }
4056
+
4057
+ var hasRequiredFetchNodeHttp;
4058
+
4059
+ function requireFetchNodeHttp () {
4060
+ if (hasRequiredFetchNodeHttp) return fetchNodeHttp;
4061
+ hasRequiredFetchNodeHttp = 1;
4062
+ Object.defineProperty(fetchNodeHttp, "__esModule", { value: true });
4063
+ fetchNodeHttp.fetchNodeHttp = fetchNodeHttp$1;
4064
+ const node_http_1 = require$$0$3;
4065
+ const node_https_1 = require$$1$3;
4066
+ const node_stream_1 = require$$0$1;
4067
+ const node_zlib_1 = require$$0$5;
4068
+ const promise_helpers_1 = require$$4;
4069
+ const Request_js_1 = requireRequest();
4070
+ const Response_js_1 = requireResponse();
4071
+ const URL_js_1 = requireURL();
4072
+ const utils_js_1 = requireUtils();
4073
+ function getRequestFnForProtocol(url) {
4074
+ if (url.startsWith('http:')) {
4075
+ return node_http_1.request;
4076
+ }
4077
+ else if (url.startsWith('https:')) {
4078
+ return node_https_1.request;
4079
+ }
4080
+ throw new Error(`Unsupported protocol: ${url.split(':')[0] || url}`);
4081
+ }
4082
+ function fetchNodeHttp$1(fetchRequest) {
4083
+ return new Promise((resolve, reject) => {
4084
+ try {
4085
+ const requestFn = getRequestFnForProtocol(fetchRequest.parsedUrl?.protocol || fetchRequest.url);
4086
+ const headersSerializer = fetchRequest.headersSerializer || utils_js_1.getHeadersObj;
4087
+ const nodeHeaders = headersSerializer(fetchRequest.headers);
4088
+ if (nodeHeaders['accept-encoding'] == null) {
4089
+ nodeHeaders['accept-encoding'] = 'gzip, deflate, br';
4090
+ }
4091
+ let signal;
4092
+ if (fetchRequest._signal == null) {
4093
+ signal = undefined;
4094
+ }
4095
+ else if (fetchRequest._signal) {
4096
+ signal = fetchRequest._signal;
4097
+ }
4098
+ let nodeRequest;
4099
+ // If it is our ponyfilled Request, it should have `parsedUrl` which is a `URL` object
4100
+ if (fetchRequest.parsedUrl) {
4101
+ nodeRequest = requestFn(fetchRequest.parsedUrl, {
4102
+ method: fetchRequest.method,
4103
+ headers: nodeHeaders,
4104
+ signal,
4105
+ agent: fetchRequest.agent,
4106
+ });
4107
+ }
4108
+ else {
4109
+ nodeRequest = requestFn(fetchRequest.url, {
4110
+ method: fetchRequest.method,
4111
+ headers: nodeHeaders,
4112
+ signal,
4113
+ agent: fetchRequest.agent,
4114
+ });
4115
+ }
4116
+ nodeRequest.once('error', reject);
4117
+ nodeRequest.once('response', nodeResponse => {
4118
+ let outputStream;
4119
+ const contentEncoding = nodeResponse.headers['content-encoding'];
4120
+ switch (contentEncoding) {
4121
+ case 'x-gzip':
4122
+ case 'gzip':
4123
+ outputStream = (0, node_zlib_1.createGunzip)();
4124
+ break;
4125
+ case 'x-deflate':
4126
+ case 'deflate':
4127
+ outputStream = (0, node_zlib_1.createInflate)();
4128
+ break;
4129
+ case 'x-deflate-raw':
4130
+ case 'deflate-raw':
4131
+ outputStream = (0, node_zlib_1.createInflateRaw)();
4132
+ break;
4133
+ case 'br':
4134
+ outputStream = (0, node_zlib_1.createBrotliDecompress)();
4135
+ break;
4136
+ }
4137
+ if (nodeResponse.headers.location && (0, utils_js_1.shouldRedirect)(nodeResponse.statusCode)) {
4138
+ if (fetchRequest.redirect === 'error') {
4139
+ const redirectError = new Error('Redirects are not allowed');
4140
+ reject(redirectError);
4141
+ nodeResponse.resume();
4142
+ return;
4143
+ }
4144
+ if (fetchRequest.redirect === 'follow') {
4145
+ const redirectedUrl = new URL_js_1.PonyfillURL(nodeResponse.headers.location, fetchRequest.parsedUrl || fetchRequest.url);
4146
+ const redirectResponse$ = fetchNodeHttp$1(new Request_js_1.PonyfillRequest(redirectedUrl, fetchRequest));
4147
+ resolve(redirectResponse$.then(redirectResponse => {
4148
+ redirectResponse.redirected = true;
4149
+ return redirectResponse;
4150
+ }));
4151
+ nodeResponse.resume();
4152
+ return;
4153
+ }
4154
+ }
4155
+ outputStream ||= new node_stream_1.PassThrough();
4156
+ (0, utils_js_1.pipeThrough)({
4157
+ src: nodeResponse,
4158
+ dest: outputStream,
4159
+ signal,
4160
+ onError: e => {
4161
+ if (!nodeResponse.destroyed) {
4162
+ nodeResponse.destroy(e);
4163
+ }
4164
+ if (!outputStream.destroyed) {
4165
+ outputStream.destroy(e);
4166
+ }
4167
+ reject(e);
4168
+ },
4169
+ });
4170
+ const statusCode = nodeResponse.statusCode || 200;
4171
+ let statusText = nodeResponse.statusMessage || node_http_1.STATUS_CODES[statusCode];
4172
+ if (statusText == null) {
4173
+ statusText = '';
4174
+ }
4175
+ const ponyfillResponse = new Response_js_1.PonyfillResponse(outputStream || nodeResponse, {
4176
+ status: statusCode,
4177
+ statusText,
4178
+ headers: nodeResponse.headers,
4179
+ url: fetchRequest.url,
4180
+ signal,
4181
+ });
4182
+ resolve(ponyfillResponse);
4183
+ });
4184
+ if (fetchRequest['_buffer'] != null) {
4185
+ (0, promise_helpers_1.handleMaybePromise)(() => (0, utils_js_1.safeWrite)(fetchRequest['_buffer'], nodeRequest), () => (0, utils_js_1.endStream)(nodeRequest), reject);
4186
+ }
4187
+ else {
4188
+ const nodeReadable = (fetchRequest.body != null
4189
+ ? (0, utils_js_1.isNodeReadable)(fetchRequest.body)
4190
+ ? fetchRequest.body
4191
+ : node_stream_1.Readable.from(fetchRequest.body)
4192
+ : null);
4193
+ if (nodeReadable) {
4194
+ nodeReadable.pipe(nodeRequest);
4195
+ }
4196
+ else {
4197
+ (0, utils_js_1.endStream)(nodeRequest);
4198
+ }
4199
+ }
4200
+ }
4201
+ catch (e) {
4202
+ reject(e);
4203
+ }
4204
+ });
4205
+ }
4206
+ return fetchNodeHttp;
4207
+ }
4208
+
4209
+ var hasRequiredFetch;
4210
+
4211
+ function requireFetch () {
4212
+ if (hasRequiredFetch) return fetch;
4213
+ hasRequiredFetch = 1;
4214
+ Object.defineProperty(fetch, "__esModule", { value: true });
4215
+ fetch.fetchPonyfill = fetchPonyfill;
4216
+ const node_buffer_1 = require$$0$2;
4217
+ const node_fs_1 = require$$1$4;
4218
+ const node_url_1 = require$$2$1;
4219
+ const fetchCurl_js_1 = requireFetchCurl();
4220
+ const fetchNodeHttp_js_1 = requireFetchNodeHttp();
4221
+ const Request_js_1 = requireRequest();
4222
+ const Response_js_1 = requireResponse();
4223
+ const URL_js_1 = requireURL();
4224
+ const utils_js_1 = requireUtils();
4225
+ const BASE64_SUFFIX = ';base64';
4226
+ async function getResponseForFile(url) {
4227
+ const path = (0, node_url_1.fileURLToPath)(url);
4228
+ try {
4229
+ await node_fs_1.promises.access(path, node_fs_1.promises.constants.R_OK);
4230
+ const stats = await node_fs_1.promises.stat(path, {
4231
+ bigint: true,
4232
+ });
4233
+ const readable = (0, node_fs_1.createReadStream)(path);
4234
+ return new Response_js_1.PonyfillResponse(readable, {
4235
+ status: 200,
4236
+ statusText: 'OK',
4237
+ headers: {
4238
+ 'content-type': 'application/octet-stream',
4239
+ 'last-modified': stats.mtime.toUTCString(),
4240
+ },
4241
+ });
4242
+ }
4243
+ catch (err) {
4244
+ if (err.code === 'ENOENT') {
4245
+ return new Response_js_1.PonyfillResponse(null, {
4246
+ status: 404,
4247
+ statusText: 'Not Found',
4248
+ });
4249
+ }
4250
+ else if (err.code === 'EACCES') {
4251
+ return new Response_js_1.PonyfillResponse(null, {
4252
+ status: 403,
4253
+ statusText: 'Forbidden',
4254
+ });
4255
+ }
4256
+ throw err;
4257
+ }
4258
+ }
4259
+ function getResponseForDataUri(url) {
4260
+ const [mimeType = 'text/plain', ...datas] = url.substring(5).split(',');
4261
+ const data = decodeURIComponent(datas.join(','));
4262
+ if (mimeType.endsWith(BASE64_SUFFIX)) {
4263
+ const buffer = node_buffer_1.Buffer.from(data, 'base64url');
4264
+ const realMimeType = mimeType.slice(0, -BASE64_SUFFIX.length);
4265
+ return new Response_js_1.PonyfillResponse(buffer, {
4266
+ status: 200,
4267
+ statusText: 'OK',
4268
+ headers: {
4269
+ 'content-type': realMimeType,
4270
+ },
4271
+ });
4272
+ }
4273
+ return new Response_js_1.PonyfillResponse(data, {
4274
+ status: 200,
4275
+ statusText: 'OK',
4276
+ headers: {
4277
+ 'content-type': mimeType,
4278
+ },
4279
+ });
4280
+ }
4281
+ function getResponseForBlob(url) {
4282
+ const blob = URL_js_1.PonyfillURL.getBlobFromURL(url);
4283
+ if (!blob) {
4284
+ throw new TypeError('Invalid Blob URL');
4285
+ }
4286
+ return new Response_js_1.PonyfillResponse(blob, {
4287
+ status: 200,
4288
+ headers: {
4289
+ 'content-type': blob.type,
4290
+ 'content-length': blob.size.toString(),
4291
+ },
4292
+ });
4293
+ }
4294
+ function isURL(obj) {
4295
+ return obj != null && obj.href != null;
4296
+ }
4297
+ function fetchPonyfill(info, init) {
4298
+ if (typeof info === 'string' || isURL(info)) {
4299
+ const ponyfillRequest = new Request_js_1.PonyfillRequest(info, init);
4300
+ return fetchPonyfill(ponyfillRequest);
4301
+ }
4302
+ const fetchRequest = info;
4303
+ if (fetchRequest.url.startsWith('data:')) {
4304
+ const response = getResponseForDataUri(fetchRequest.url);
4305
+ return (0, utils_js_1.fakePromise)(response);
4306
+ }
4307
+ if (fetchRequest.url.startsWith('file:')) {
4308
+ const response = getResponseForFile(fetchRequest.url);
4309
+ return response;
4310
+ }
4311
+ if (fetchRequest.url.startsWith('blob:')) {
4312
+ const response = getResponseForBlob(fetchRequest.url);
4313
+ return (0, utils_js_1.fakePromise)(response);
4314
+ }
4315
+ if (globalThis.libcurl && !fetchRequest.agent) {
4316
+ return (0, fetchCurl_js_1.fetchCurl)(fetchRequest);
4317
+ }
4318
+ return (0, fetchNodeHttp_js_1.fetchNodeHttp)(fetchRequest);
4319
+ }
4320
+ return fetch;
4321
+ }
4322
+
4323
+ var TextEncoderDecoder = {};
4324
+
4325
+ var hasRequiredTextEncoderDecoder;
4326
+
4327
+ function requireTextEncoderDecoder () {
4328
+ if (hasRequiredTextEncoderDecoder) return TextEncoderDecoder;
4329
+ hasRequiredTextEncoderDecoder = 1;
4330
+ Object.defineProperty(TextEncoderDecoder, "__esModule", { value: true });
4331
+ TextEncoderDecoder.PonyfillTextDecoder = TextEncoderDecoder.PonyfillTextEncoder = void 0;
4332
+ TextEncoderDecoder.PonyfillBtoa = PonyfillBtoa;
4333
+ const node_buffer_1 = require$$0$2;
4334
+ const utils_js_1 = requireUtils();
4335
+ class PonyfillTextEncoder {
4336
+ encoding;
4337
+ constructor(encoding = 'utf-8') {
4338
+ this.encoding = encoding;
4339
+ }
4340
+ encode(input) {
4341
+ return node_buffer_1.Buffer.from(input, this.encoding);
4342
+ }
4343
+ encodeInto(source, destination) {
4344
+ const buffer = this.encode(source);
4345
+ const copied = buffer.copy(destination);
4346
+ return {
4347
+ read: copied,
4348
+ written: copied,
4349
+ };
4350
+ }
4351
+ }
4352
+ TextEncoderDecoder.PonyfillTextEncoder = PonyfillTextEncoder;
4353
+ class PonyfillTextDecoder {
4354
+ encoding;
4355
+ fatal = false;
4356
+ ignoreBOM = false;
4357
+ constructor(encoding = 'utf-8', options) {
4358
+ this.encoding = encoding;
4359
+ if (options) {
4360
+ this.fatal = options.fatal || false;
4361
+ this.ignoreBOM = options.ignoreBOM || false;
4362
+ }
4363
+ }
4364
+ decode(input) {
4365
+ if (node_buffer_1.Buffer.isBuffer(input)) {
4366
+ return input.toString(this.encoding);
4367
+ }
4368
+ if ((0, utils_js_1.isArrayBufferView)(input)) {
4369
+ return node_buffer_1.Buffer.from(input.buffer, input.byteOffset, input.byteLength).toString(this.encoding);
4370
+ }
4371
+ return node_buffer_1.Buffer.from(input).toString(this.encoding);
4372
+ }
4373
+ }
4374
+ TextEncoderDecoder.PonyfillTextDecoder = PonyfillTextDecoder;
4375
+ function PonyfillBtoa(input) {
4376
+ return node_buffer_1.Buffer.from(input, 'binary').toString('base64');
4377
+ }
4378
+ return TextEncoderDecoder;
4379
+ }
4380
+
4381
+ var URLSearchParams = {};
4382
+
4383
+ var hasRequiredURLSearchParams;
4384
+
4385
+ function requireURLSearchParams () {
4386
+ if (hasRequiredURLSearchParams) return URLSearchParams;
4387
+ hasRequiredURLSearchParams = 1;
4388
+ Object.defineProperty(URLSearchParams, "__esModule", { value: true });
4389
+ URLSearchParams.PonyfillURLSearchParams = void 0;
4390
+ URLSearchParams.PonyfillURLSearchParams = globalThis.URLSearchParams;
4391
+ return URLSearchParams;
4392
+ }
4393
+
4394
+ var WritableStream = {};
4395
+
4396
+ var hasRequiredWritableStream;
4397
+
4398
+ function requireWritableStream () {
4399
+ if (hasRequiredWritableStream) return WritableStream;
4400
+ hasRequiredWritableStream = 1;
4401
+ Object.defineProperty(WritableStream, "__esModule", { value: true });
4402
+ WritableStream.PonyfillWritableStream = void 0;
4403
+ const node_events_1 = require$$0;
4404
+ const node_stream_1 = require$$0$1;
4405
+ const promise_helpers_1 = require$$4;
4406
+ const utils_js_1 = requireUtils();
4407
+ class PonyfillWritableStream {
4408
+ writable;
4409
+ constructor(underlyingSink) {
4410
+ if (underlyingSink instanceof node_stream_1.Writable) {
4411
+ this.writable = underlyingSink;
4412
+ }
4413
+ else if (underlyingSink) {
4414
+ const writable = new node_stream_1.Writable({
4415
+ write(chunk, _encoding, callback) {
4416
+ try {
4417
+ const result = underlyingSink.write?.(chunk, controller);
4418
+ if (result instanceof Promise) {
4419
+ result.then(() => {
4420
+ callback();
4421
+ }, err => {
4422
+ callback(err);
4423
+ });
4424
+ }
4425
+ else {
4426
+ callback();
4427
+ }
4428
+ }
4429
+ catch (err) {
4430
+ callback(err);
4431
+ }
4432
+ },
4433
+ final(callback) {
4434
+ const result = underlyingSink.close?.();
4435
+ if (result instanceof Promise) {
4436
+ result.then(() => {
4437
+ callback();
4438
+ }, err => {
4439
+ callback(err);
4440
+ });
4441
+ }
4442
+ else {
4443
+ callback();
4444
+ }
4445
+ },
4446
+ });
4447
+ this.writable = writable;
4448
+ const abortCtrl = new AbortController();
4449
+ const controller = {
4450
+ signal: abortCtrl.signal,
4451
+ error(e) {
4452
+ writable.destroy(e);
4453
+ },
4454
+ };
4455
+ writable.once('error', err => abortCtrl.abort(err));
4456
+ writable.once('close', () => abortCtrl.abort());
4457
+ }
4458
+ else {
4459
+ this.writable = new node_stream_1.Writable();
4460
+ }
4461
+ }
4462
+ getWriter() {
4463
+ const writable = this.writable;
4464
+ return {
4465
+ get closed() {
4466
+ return (0, node_events_1.once)(writable, 'close');
4467
+ },
4468
+ get desiredSize() {
4469
+ return writable.writableLength;
4470
+ },
4471
+ get ready() {
4472
+ return (0, node_events_1.once)(writable, 'drain');
4473
+ },
4474
+ releaseLock() {
4475
+ // no-op
4476
+ },
4477
+ write(chunk) {
4478
+ const promise = (0, utils_js_1.fakePromise)();
4479
+ if (chunk == null) {
4480
+ return promise;
4481
+ }
4482
+ return promise.then(() => (0, utils_js_1.safeWrite)(chunk, writable));
4483
+ },
4484
+ close() {
4485
+ if (!writable.errored && writable.closed) {
4486
+ return (0, utils_js_1.fakePromise)();
4487
+ }
4488
+ if (writable.errored) {
4489
+ return (0, promise_helpers_1.fakeRejectPromise)(writable.errored);
4490
+ }
4491
+ return (0, utils_js_1.fakePromise)().then(() => (0, utils_js_1.endStream)(writable));
4492
+ },
4493
+ abort(reason) {
4494
+ writable.destroy(reason);
4495
+ return (0, node_events_1.once)(writable, 'close');
4496
+ },
4497
+ };
4498
+ }
4499
+ close() {
4500
+ if (!this.writable.errored && this.writable.closed) {
4501
+ return (0, utils_js_1.fakePromise)();
4502
+ }
4503
+ if (this.writable.errored) {
4504
+ return (0, promise_helpers_1.fakeRejectPromise)(this.writable.errored);
4505
+ }
4506
+ return (0, utils_js_1.fakePromise)().then(() => (0, utils_js_1.endStream)(this.writable));
4507
+ }
4508
+ abort(reason) {
4509
+ this.writable.destroy(reason);
4510
+ return (0, node_events_1.once)(this.writable, 'close');
4511
+ }
4512
+ locked = false;
4513
+ }
4514
+ WritableStream.PonyfillWritableStream = PonyfillWritableStream;
4515
+ return WritableStream;
4516
+ }
4517
+
4518
+ var TransformStream = {};
4519
+
4520
+ var hasRequiredTransformStream;
4521
+
4522
+ function requireTransformStream () {
4523
+ if (hasRequiredTransformStream) return TransformStream;
4524
+ hasRequiredTransformStream = 1;
4525
+ Object.defineProperty(TransformStream, "__esModule", { value: true });
4526
+ TransformStream.PonyfillTransformStream = void 0;
4527
+ const node_stream_1 = require$$0$1;
4528
+ const ReadableStream_js_1 = requireReadableStream();
4529
+ const utils_js_1 = requireUtils();
4530
+ const WritableStream_js_1 = requireWritableStream();
4531
+ class PonyfillTransformStream {
4532
+ transform;
4533
+ writable;
4534
+ readable;
4535
+ constructor(transformer) {
4536
+ if (transformer instanceof node_stream_1.Transform) {
4537
+ this.transform = transformer;
4538
+ }
4539
+ else if (transformer) {
4540
+ const controller = {
4541
+ enqueue(chunk) {
4542
+ transform.push(chunk);
4543
+ },
4544
+ error(reason) {
4545
+ transform.destroy(reason);
4546
+ },
4547
+ terminate() {
4548
+ (0, utils_js_1.endStream)(transform);
4549
+ },
4550
+ get desiredSize() {
4551
+ return transform.writableLength;
4552
+ },
4553
+ };
4554
+ const transform = new node_stream_1.Transform({
4555
+ read() { },
4556
+ write(chunk, _encoding, callback) {
4557
+ try {
4558
+ const result = transformer.transform?.(chunk, controller);
4559
+ if (result instanceof Promise) {
4560
+ result.then(() => {
4561
+ callback();
4562
+ }, err => {
4563
+ callback(err);
4564
+ });
4565
+ }
4566
+ else {
4567
+ callback();
4568
+ }
4569
+ }
4570
+ catch (err) {
4571
+ callback(err);
4572
+ }
4573
+ },
4574
+ final(callback) {
4575
+ try {
4576
+ const result = transformer.flush?.(controller);
4577
+ if (result instanceof Promise) {
4578
+ result.then(() => {
4579
+ callback();
4580
+ }, err => {
4581
+ callback(err);
4582
+ });
4583
+ }
4584
+ else {
4585
+ callback();
4586
+ }
4587
+ }
4588
+ catch (err) {
4589
+ callback(err);
4590
+ }
4591
+ },
4592
+ });
4593
+ this.transform = transform;
4594
+ }
4595
+ else {
4596
+ this.transform = new node_stream_1.Transform();
4597
+ }
4598
+ this.writable = new WritableStream_js_1.PonyfillWritableStream(this.transform);
4599
+ this.readable = new ReadableStream_js_1.PonyfillReadableStream(this.transform);
4600
+ }
4601
+ }
4602
+ TransformStream.PonyfillTransformStream = PonyfillTransformStream;
4603
+ return TransformStream;
4604
+ }
4605
+
4606
+ var CompressionStream = {};
4607
+
4608
+ var hasRequiredCompressionStream;
4609
+
4610
+ function requireCompressionStream () {
4611
+ if (hasRequiredCompressionStream) return CompressionStream;
4612
+ hasRequiredCompressionStream = 1;
4613
+ Object.defineProperty(CompressionStream, "__esModule", { value: true });
4614
+ CompressionStream.PonyfillCompressionStream = void 0;
4615
+ const node_zlib_1 = require$$0$5;
4616
+ const TransformStream_js_1 = requireTransformStream();
4617
+ class PonyfillCompressionStream extends TransformStream_js_1.PonyfillTransformStream {
4618
+ static supportedFormats = globalThis.process?.version?.startsWith('v2')
4619
+ ? ['gzip', 'deflate', 'br']
4620
+ : ['gzip', 'deflate', 'deflate-raw', 'br'];
4621
+ constructor(compressionFormat) {
4622
+ switch (compressionFormat) {
4623
+ case 'x-gzip':
4624
+ case 'gzip':
4625
+ super((0, node_zlib_1.createGzip)());
4626
+ break;
4627
+ case 'x-deflate':
4628
+ case 'deflate':
4629
+ super((0, node_zlib_1.createDeflate)());
4630
+ break;
4631
+ case 'deflate-raw':
4632
+ super((0, node_zlib_1.createDeflateRaw)());
4633
+ break;
4634
+ case 'br':
4635
+ super((0, node_zlib_1.createBrotliCompress)());
4636
+ break;
4637
+ default:
4638
+ throw new Error(`Unsupported compression format: ${compressionFormat}`);
4639
+ }
4640
+ }
4641
+ }
4642
+ CompressionStream.PonyfillCompressionStream = PonyfillCompressionStream;
4643
+ return CompressionStream;
4644
+ }
4645
+
4646
+ var DecompressionStream = {};
4647
+
4648
+ var hasRequiredDecompressionStream;
4649
+
4650
+ function requireDecompressionStream () {
4651
+ if (hasRequiredDecompressionStream) return DecompressionStream;
4652
+ hasRequiredDecompressionStream = 1;
4653
+ Object.defineProperty(DecompressionStream, "__esModule", { value: true });
4654
+ DecompressionStream.PonyfillDecompressionStream = void 0;
4655
+ const node_zlib_1 = require$$0$5;
4656
+ const TransformStream_js_1 = requireTransformStream();
4657
+ class PonyfillDecompressionStream extends TransformStream_js_1.PonyfillTransformStream {
4658
+ static supportedFormats = globalThis.process?.version?.startsWith('v2')
4659
+ ? ['gzip', 'deflate', 'br']
4660
+ : ['gzip', 'deflate', 'deflate-raw', 'br'];
4661
+ constructor(compressionFormat) {
4662
+ switch (compressionFormat) {
4663
+ case 'x-gzip':
4664
+ case 'gzip':
4665
+ super((0, node_zlib_1.createGunzip)());
4666
+ break;
4667
+ case 'x-deflate':
4668
+ case 'deflate':
4669
+ super((0, node_zlib_1.createInflate)());
4670
+ break;
4671
+ case 'deflate-raw':
4672
+ super((0, node_zlib_1.createInflateRaw)());
4673
+ break;
4674
+ case 'br':
4675
+ super((0, node_zlib_1.createBrotliDecompress)());
4676
+ break;
4677
+ default:
4678
+ throw new TypeError(`Unsupported compression format: '${compressionFormat}'`);
4679
+ }
4680
+ }
4681
+ }
4682
+ DecompressionStream.PonyfillDecompressionStream = PonyfillDecompressionStream;
4683
+ return DecompressionStream;
4684
+ }
4685
+
4686
+ var TextEncoderDecoderStream = {};
4687
+
4688
+ var hasRequiredTextEncoderDecoderStream;
4689
+
4690
+ function requireTextEncoderDecoderStream () {
4691
+ if (hasRequiredTextEncoderDecoderStream) return TextEncoderDecoderStream;
4692
+ hasRequiredTextEncoderDecoderStream = 1;
4693
+ Object.defineProperty(TextEncoderDecoderStream, "__esModule", { value: true });
4694
+ TextEncoderDecoderStream.PonyfillTextEncoderStream = TextEncoderDecoderStream.PonyfillTextDecoderStream = void 0;
4695
+ const TextEncoderDecoder_js_1 = requireTextEncoderDecoder();
4696
+ const TransformStream_js_1 = requireTransformStream();
4697
+ class PonyfillTextDecoderStream extends TransformStream_js_1.PonyfillTransformStream {
4698
+ textDecoder;
4699
+ constructor(encoding, options) {
4700
+ super({
4701
+ transform: (chunk, controller) => controller.enqueue(this.textDecoder.decode(chunk, { stream: true })),
4702
+ });
4703
+ this.textDecoder = new TextEncoderDecoder_js_1.PonyfillTextDecoder(encoding, options);
4704
+ }
4705
+ get encoding() {
4706
+ return this.textDecoder.encoding;
4707
+ }
4708
+ get fatal() {
4709
+ return this.textDecoder.fatal;
4710
+ }
4711
+ get ignoreBOM() {
4712
+ return this.textDecoder.ignoreBOM;
4713
+ }
4714
+ }
4715
+ TextEncoderDecoderStream.PonyfillTextDecoderStream = PonyfillTextDecoderStream;
4716
+ class PonyfillTextEncoderStream extends TransformStream_js_1.PonyfillTransformStream {
4717
+ textEncoder;
4718
+ constructor(encoding) {
4719
+ super({
4720
+ transform: (chunk, controller) => controller.enqueue(this.textEncoder.encode(chunk)),
4721
+ });
4722
+ this.textEncoder = new TextEncoderDecoder_js_1.PonyfillTextEncoder(encoding);
4723
+ }
4724
+ get encoding() {
4725
+ return this.textEncoder.encoding;
4726
+ }
4727
+ encode(input) {
4728
+ return this.textEncoder.encode(input);
4729
+ }
4730
+ }
4731
+ TextEncoderDecoderStream.PonyfillTextEncoderStream = PonyfillTextEncoderStream;
4732
+ return TextEncoderDecoderStream;
4733
+ }
4734
+
4735
+ var hasRequiredCjs;
4736
+
4737
+ function requireCjs () {
4738
+ if (hasRequiredCjs) return cjs;
4739
+ hasRequiredCjs = 1;
4740
+ (function (exports) {
4741
+ Object.defineProperty(exports, "__esModule", { value: true });
4742
+ exports.TextEncoderStream = exports.TextDecoderStream = exports.IteratorObject = exports.DecompressionStream = exports.CompressionStream = exports.TransformStream = exports.WritableStream = exports.URLSearchParams = exports.URL = exports.btoa = exports.TextDecoder = exports.TextEncoder = exports.Blob = exports.FormData = exports.File = exports.ReadableStream = exports.Response = exports.Request = exports.Body = exports.Headers = exports.fetch = void 0;
4743
+ var fetch_js_1 = requireFetch();
4744
+ Object.defineProperty(exports, "fetch", { enumerable: true, get: function () { return fetch_js_1.fetchPonyfill; } });
4745
+ var Headers_js_1 = requireHeaders();
4746
+ Object.defineProperty(exports, "Headers", { enumerable: true, get: function () { return Headers_js_1.PonyfillHeaders; } });
4747
+ var Body_js_1 = requireBody();
4748
+ Object.defineProperty(exports, "Body", { enumerable: true, get: function () { return Body_js_1.PonyfillBody; } });
4749
+ var Request_js_1 = requireRequest();
4750
+ Object.defineProperty(exports, "Request", { enumerable: true, get: function () { return Request_js_1.PonyfillRequest; } });
4751
+ var Response_js_1 = requireResponse();
4752
+ Object.defineProperty(exports, "Response", { enumerable: true, get: function () { return Response_js_1.PonyfillResponse; } });
4753
+ var ReadableStream_js_1 = requireReadableStream();
4754
+ Object.defineProperty(exports, "ReadableStream", { enumerable: true, get: function () { return ReadableStream_js_1.PonyfillReadableStream; } });
4755
+ var File_js_1 = requireFile();
4756
+ Object.defineProperty(exports, "File", { enumerable: true, get: function () { return File_js_1.PonyfillFile; } });
4757
+ var FormData_js_1 = requireFormData();
4758
+ Object.defineProperty(exports, "FormData", { enumerable: true, get: function () { return FormData_js_1.PonyfillFormData; } });
4759
+ var Blob_js_1 = requireBlob();
4760
+ Object.defineProperty(exports, "Blob", { enumerable: true, get: function () { return Blob_js_1.PonyfillBlob; } });
4761
+ var TextEncoderDecoder_js_1 = requireTextEncoderDecoder();
4762
+ Object.defineProperty(exports, "TextEncoder", { enumerable: true, get: function () { return TextEncoderDecoder_js_1.PonyfillTextEncoder; } });
4763
+ Object.defineProperty(exports, "TextDecoder", { enumerable: true, get: function () { return TextEncoderDecoder_js_1.PonyfillTextDecoder; } });
4764
+ Object.defineProperty(exports, "btoa", { enumerable: true, get: function () { return TextEncoderDecoder_js_1.PonyfillBtoa; } });
4765
+ var URL_js_1 = requireURL();
4766
+ Object.defineProperty(exports, "URL", { enumerable: true, get: function () { return URL_js_1.PonyfillURL; } });
4767
+ var URLSearchParams_js_1 = requireURLSearchParams();
4768
+ Object.defineProperty(exports, "URLSearchParams", { enumerable: true, get: function () { return URLSearchParams_js_1.PonyfillURLSearchParams; } });
4769
+ var WritableStream_js_1 = requireWritableStream();
4770
+ Object.defineProperty(exports, "WritableStream", { enumerable: true, get: function () { return WritableStream_js_1.PonyfillWritableStream; } });
4771
+ var TransformStream_js_1 = requireTransformStream();
4772
+ Object.defineProperty(exports, "TransformStream", { enumerable: true, get: function () { return TransformStream_js_1.PonyfillTransformStream; } });
4773
+ var CompressionStream_js_1 = requireCompressionStream();
4774
+ Object.defineProperty(exports, "CompressionStream", { enumerable: true, get: function () { return CompressionStream_js_1.PonyfillCompressionStream; } });
4775
+ var DecompressionStream_js_1 = requireDecompressionStream();
4776
+ Object.defineProperty(exports, "DecompressionStream", { enumerable: true, get: function () { return DecompressionStream_js_1.PonyfillDecompressionStream; } });
4777
+ var IteratorObject_js_1 = requireIteratorObject();
4778
+ Object.defineProperty(exports, "IteratorObject", { enumerable: true, get: function () { return IteratorObject_js_1.PonyfillIteratorObject; } });
4779
+ var TextEncoderDecoderStream_js_1 = requireTextEncoderDecoderStream();
4780
+ Object.defineProperty(exports, "TextDecoderStream", { enumerable: true, get: function () { return TextEncoderDecoderStream_js_1.PonyfillTextDecoderStream; } });
4781
+ Object.defineProperty(exports, "TextEncoderStream", { enumerable: true, get: function () { return TextEncoderDecoderStream_js_1.PonyfillTextEncoderStream; } });
4782
+ } (cjs));
4783
+ return cjs;
4784
+ }
4785
+
4786
+ const shouldSkipPonyfill$1 = shouldSkipPonyfill$2;
4787
+ let newNodeFetch;
4788
+
4789
+ var createNodePonyfill$1 = function createNodePonyfill(opts = {}) {
4790
+ const ponyfills = {};
4791
+
4792
+ ponyfills.URLPattern = globalThis.URLPattern;
4793
+
4794
+ // We call this previously to patch `Bun`
4795
+ if (!ponyfills.URLPattern) {
4796
+ const urlPatternModule = requireUrlpatternPolyfill();
4797
+ ponyfills.URLPattern = urlPatternModule.URLPattern;
4798
+ }
4799
+
4800
+ if (opts.skipPonyfill || shouldSkipPonyfill$1()) {
4801
+ return {
4802
+ fetch: globalThis.fetch,
4803
+ Headers: globalThis.Headers,
4804
+ Request: globalThis.Request,
4805
+ Response: globalThis.Response,
4806
+ FormData: globalThis.FormData,
4807
+ ReadableStream: globalThis.ReadableStream,
4808
+ WritableStream: globalThis.WritableStream,
4809
+ TransformStream: globalThis.TransformStream,
4810
+ CompressionStream: globalThis.CompressionStream,
4811
+ DecompressionStream: globalThis.DecompressionStream,
4812
+ TextDecoderStream: globalThis.TextDecoderStream,
4813
+ TextEncoderStream: globalThis.TextEncoderStream,
4814
+ Blob: globalThis.Blob,
4815
+ File: globalThis.File,
4816
+ crypto: globalThis.crypto,
4817
+ btoa: globalThis.btoa,
4818
+ TextEncoder: globalThis.TextEncoder,
4819
+ TextDecoder: globalThis.TextDecoder,
4820
+ URLPattern: ponyfills.URLPattern,
4821
+ URL: globalThis.URL,
4822
+ URLSearchParams: globalThis.URLSearchParams
4823
+ };
4824
+ }
4825
+
4826
+ newNodeFetch ||= requireCjs();
4827
+
4828
+ ponyfills.fetch = newNodeFetch.fetch;
4829
+ ponyfills.Request = newNodeFetch.Request;
4830
+ ponyfills.Response = newNodeFetch.Response;
4831
+ ponyfills.Headers = newNodeFetch.Headers;
4832
+ ponyfills.FormData = newNodeFetch.FormData;
4833
+ ponyfills.ReadableStream = newNodeFetch.ReadableStream;
4834
+
4835
+ ponyfills.URL = newNodeFetch.URL;
4836
+ ponyfills.URLSearchParams = newNodeFetch.URLSearchParams;
4837
+
4838
+ ponyfills.WritableStream = newNodeFetch.WritableStream;
4839
+ ponyfills.TransformStream = newNodeFetch.TransformStream;
4840
+ ponyfills.CompressionStream = newNodeFetch.CompressionStream;
4841
+ ponyfills.DecompressionStream = newNodeFetch.DecompressionStream;
4842
+ ponyfills.TextDecoderStream = newNodeFetch.TextDecoderStream;
4843
+ ponyfills.TextEncoderStream = newNodeFetch.TextEncoderStream;
4844
+
4845
+ ponyfills.Blob = newNodeFetch.Blob;
4846
+ ponyfills.File = newNodeFetch.File;
4847
+ ponyfills.crypto = globalThis.crypto;
4848
+ ponyfills.btoa = newNodeFetch.btoa;
4849
+ ponyfills.TextEncoder = newNodeFetch.TextEncoder;
4850
+ ponyfills.TextDecoder = newNodeFetch.TextDecoder;
4851
+
4852
+ if (opts.formDataLimits) {
4853
+ ponyfills.Body = class Body extends newNodeFetch.Body {
4854
+ constructor(body, userOpts) {
4855
+ super(body, {
4856
+ formDataLimits: opts.formDataLimits,
4857
+ ...userOpts,
4858
+ });
4859
+ }
4860
+ };
4861
+ ponyfills.Request = class Request extends newNodeFetch.Request {
4862
+ constructor(input, userOpts) {
4863
+ super(input, {
4864
+ formDataLimits: opts.formDataLimits,
4865
+ ...userOpts,
4866
+ });
4867
+ }
4868
+ };
4869
+ ponyfills.Response = class Response extends newNodeFetch.Response {
4870
+ constructor(body, userOpts) {
4871
+ super(body, {
4872
+ formDataLimits: opts.formDataLimits,
4873
+ ...userOpts,
4874
+ });
4875
+ }
4876
+ };
4877
+ }
4878
+
4879
+ if (!ponyfills.crypto) {
4880
+ const cryptoModule = require$$3$1;
4881
+ ponyfills.crypto = cryptoModule.webcrypto;
4882
+ }
4883
+
4884
+ return ponyfills;
4885
+ };
4886
+
4887
+ const createNodePonyfill = createNodePonyfill$1;
4888
+ const shouldSkipPonyfill = shouldSkipPonyfill$2;
4889
+ const ponyfills = createNodePonyfill();
4890
+
4891
+ if (!shouldSkipPonyfill()) {
4892
+ try {
4893
+ const nodelibcurlName = 'node-libcurl';
4894
+ globalThis.libcurl = globalThis.libcurl || commonjsRequire(nodelibcurlName);
4895
+ } catch (e) { }
4896
+ }
4897
+
4898
+ ponyfills.fetch;
4899
+ ponyfills.Headers;
4900
+ ponyfills.Request;
4901
+ ponyfills.Response;
4902
+ ponyfills.FormData;
4903
+ ponyfills.ReadableStream;
4904
+ ponyfills.WritableStream;
4905
+ ponyfills.TransformStream;
4906
+ ponyfills.CompressionStream;
4907
+ ponyfills.DecompressionStream;
4908
+ ponyfills.TextDecoderStream;
4909
+ ponyfills.TextEncoderStream;
4910
+ ponyfills.Blob;
4911
+ ponyfills.File;
4912
+ ponyfills.crypto;
4913
+ ponyfills.btoa;
4914
+ ponyfills.TextEncoder;
4915
+ ponyfills.TextDecoder;
4916
+ ponyfills.URLPattern;
4917
+ var URL$1 = ponyfills.URL;
4918
+ ponyfills.URLSearchParams;
4919
+
75
4920
  function checkIfDataSatisfiesSelectionSet(selectionSet, data) {
76
4921
  if (Array.isArray(data)) {
77
4922
  return data.every(
@@ -327,6 +5172,33 @@ function getDirectiveNameForFederationDirective({
327
5172
  }
328
5173
  return normalizedDirectiveName;
329
5174
  }
5175
+ const specs = [
5176
+ function extractPersistedOperationIdByApolloSpec(params) {
5177
+ if (params.extensions != null && typeof params.extensions === "object" && params.extensions?.["persistedQuery"] != null && typeof params.extensions?.["persistedQuery"] === "object" && params.extensions?.["persistedQuery"]?.["version"] === 1 && typeof params.extensions?.["persistedQuery"]?.["sha256Hash"] === "string") {
5178
+ return params.extensions?.["persistedQuery"]?.["sha256Hash"];
5179
+ }
5180
+ return null;
5181
+ },
5182
+ function extractPersistedOperationIdByHiveSpec(params, request, _context) {
5183
+ if ("documentId" in params && typeof params.documentId === "string") {
5184
+ return params.documentId;
5185
+ }
5186
+ const documentId = new URL$1(request.url).searchParams.get("documentId");
5187
+ if (documentId) {
5188
+ return documentId;
5189
+ }
5190
+ return null;
5191
+ }
5192
+ ];
5193
+ const defaultExtractPersistedOperationId = function defaultExtractPersistedOperationId2(params, request, context) {
5194
+ for (const spec of specs) {
5195
+ const id = spec(params, request, context);
5196
+ if (id) {
5197
+ return id;
5198
+ }
5199
+ }
5200
+ return null;
5201
+ };
330
5202
 
331
5203
  const defaultLoadedPlacePrefix = "GraphOS Managed Federation";
332
5204
  function decideMaxRetries({
@@ -1986,6 +6858,7 @@ function createGatewayRuntime(config) {
1986
6858
  });
1987
6859
  } else if (config.persistedDocuments && "getPersistedOperation" in config.persistedDocuments) {
1988
6860
  const plugin = usePersistedOperations({
6861
+ extractPersistedOperationId: defaultExtractPersistedOperationId,
1989
6862
  ...configContext,
1990
6863
  ...config.persistedDocuments
1991
6864
  });