@gjsify/fetch 0.3.21 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/lib/esm/_virtual/_rolldown/runtime.js +1 -0
  2. package/lib/esm/body.js +1 -1
  3. package/lib/esm/errors/abort-error.js +1 -1
  4. package/lib/esm/errors/base.js +1 -1
  5. package/lib/esm/errors/fetch-error.js +1 -1
  6. package/lib/esm/headers.js +1 -1
  7. package/lib/esm/index.js +1 -1
  8. package/lib/esm/request.js +1 -1
  9. package/lib/esm/response.js +1 -1
  10. package/lib/esm/utils/data-uri.js +1 -1
  11. package/lib/esm/utils/get-search.js +1 -1
  12. package/lib/esm/utils/is-redirect.js +1 -1
  13. package/lib/esm/utils/is.js +1 -1
  14. package/lib/esm/utils/multipart-parser.js +1 -1
  15. package/lib/esm/utils/referrer.js +1 -1
  16. package/lib/esm/utils/soup-helpers.js +1 -1
  17. package/lib/esm/xhr.js +1 -1
  18. package/package.json +61 -58
  19. package/src/body.ts +0 -448
  20. package/src/errors/abort-error.ts +0 -10
  21. package/src/errors/base.ts +0 -22
  22. package/src/errors/fetch-error.ts +0 -26
  23. package/src/headers.ts +0 -232
  24. package/src/index.spec.ts +0 -339
  25. package/src/index.ts +0 -316
  26. package/src/register/fetch.ts +0 -16
  27. package/src/register/xhr.ts +0 -20
  28. package/src/register.ts +0 -5
  29. package/src/request.ts +0 -423
  30. package/src/response.ts +0 -227
  31. package/src/test.browser.mts +0 -130
  32. package/src/test.mts +0 -9
  33. package/src/types/index.ts +0 -1
  34. package/src/types/system-error.ts +0 -11
  35. package/src/utils/blob-from.ts +0 -8
  36. package/src/utils/data-uri.ts +0 -29
  37. package/src/utils/get-search.ts +0 -9
  38. package/src/utils/is-redirect.ts +0 -11
  39. package/src/utils/is.ts +0 -88
  40. package/src/utils/multipart-parser.ts +0 -448
  41. package/src/utils/referrer.ts +0 -350
  42. package/src/utils/soup-helpers.ts +0 -37
  43. package/src/xhr.ts +0 -270
  44. package/tsconfig.json +0 -22
  45. package/tsconfig.tsbuildinfo +0 -1
@@ -0,0 +1 @@
1
+ var e=Object.defineProperty,__name=(t,n)=>e(t,`name`,{value:n,configurable:!0});export{__name};
package/lib/esm/body.js CHANGED
@@ -1 +1 @@
1
- import{Blob as e}from"./utils/blob-from.js";import{FetchBaseError as t}from"./errors/base.js";import{FetchError as n}from"./errors/fetch-error.js";import{isBlob as r,isURLSearchParameters as i}from"./utils/is.js";import{URLSearchParams as a}from"@gjsify/url";import{Buffer as o}from"node:buffer";import{PassThrough as s,Readable as c,Stream as l,pipeline as u}from"node:stream";import{FormData as d,formDataToBlob as f}from"@gjsify/formdata";const pipeline$1=(e,t)=>new Promise((n,r)=>{u(e,t,e=>{e?r(e):n()})}),p=Symbol(`Body internals`);function isAnyArrayBuffer(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer}var Body=class{[p]={body:null,stream:null,boundary:``,disturbed:!1,error:null};size=0;constructor(e,s={size:0}){if(this.size=s.size||0,e==null)this[p].body=null;else if(i(e))this[p].body=o.from(e.toString());else if(r(e))this[p].body=e;else if(o.isBuffer(e))this[p].body=e;else if(isAnyArrayBuffer(e))this[p].body=o.from(e);else if(ArrayBuffer.isView(e))this[p].body=o.from(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof c)this[p].body=e;else if(typeof ReadableStream<`u`&&e instanceof ReadableStream)this[p].body=readableStreamToReadable(e);else if(e instanceof d){let t=f(e);this[p].body=t,this[p].boundary=t.type?.split(`boundary=`)?.[1]??``}else typeof e==`string`?this[p].body=o.from(e):e instanceof a?this[p].body=o.from(e.toString()):(console.warn(`Unknown body type "${typeof e}", try to parse the body to string!`),this[p].body=o.from(String(e)));let u=this[p].body;o.isBuffer(u)?this[p].stream=c.from(u):r(u)?this[p].stream=c.from(blobToAsyncIterable(u)):u instanceof c&&(this[p].stream=u),u instanceof l&&u.on(`error`,e=>{let r=e instanceof t?e:new n(`Invalid response body while trying to fetch ${this.url}: ${e.message}`,`system`,e);this[p].error=r})}get body(){let e=this[p].stream;if(!e)return null;if(typeof ReadableStream<`u`){let t=!1;return new ReadableStream({start(n){e.on(`data`,e=>{if(!t)try{n.enqueue(e instanceof Uint8Array?e:new Uint8Array(e))}catch{}}),e.on(`end`,()=>{if(!t){t=!0;try{n.close()}catch{}}}),e.on(`error`,e=>{if(!t){t=!0;try{n.error(e)}catch{}}})},cancel(){t=!0,e.destroy()}})}return null}get _stream(){return this[p].stream}get _rawBodyBuffer(){let e=this[p].body;return e===null?null:o.isBuffer(e)?e:e instanceof Uint8Array?o.from(e.buffer,e.byteOffset,e.byteLength):null}get bodyUsed(){return this[p].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:n}=await consumeBody(this);return e.slice(t,t+n)}async formData(){let e=this.headers?.get(`content-type`);if(e?.startsWith(`application/x-www-form-urlencoded`)){let e=new d,t=new a(await this.text());for(let[n,r]of t)e.append(n,r);return e}let{toFormData:t}=await import(`./utils/multipart-parser.js`);return t(this.body,e)}async blob(){let t=this.headers?.get(`content-type`)||this[p].body&&this[p].body.type||``;return new e([await this.arrayBuffer()],{type:t})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await consumeBody(this);return new TextDecoder().decode(e)}};Object.defineProperties(Body.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});async function consumeBody(e){if(e[p].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[p].disturbed=!0,e[p].error)throw e[p].error;let{_stream:r}=e;if(r===null||!(r instanceof l))return o.alloc(0);let i=[],a=0;try{for await(let t of r){if(e.size>0&&a+t.length>e.size){let t=new n(`content size at ${e.url} over limit: ${e.size}`,`max-size`);throw r.destroy(t),t}a+=t.length,i.push(t)}}catch(r){let i=r instanceof Error?r:Error(String(r));throw r instanceof t?r:new n(`Invalid response body while trying to fetch ${e.url}: ${i.message}`,`system`,i)}try{return i.every(e=>typeof e==`string`)?o.from(i.join(``)):o.concat(i,a)}catch(t){let r=t instanceof Error?t:Error(String(t));throw new n(`Could not create Buffer from response body for ${e.url}: ${r.message}`,`system`,r)}}const clone=(e,t)=>{let n,r,{body:i}=e[p];if(e.bodyUsed)throw Error(`cannot clone body after it is used`);return i instanceof l&&typeof i.getBoundary!=`function`&&(n=new s({highWaterMark:t}),r=new s({highWaterMark:t}),i.pipe(n),i.pipe(r),e[p].stream=n,i=r),i},extractContentType=(e,t)=>e===null?null:typeof e==`string`?`text/plain;charset=UTF-8`:i(e)?`application/x-www-form-urlencoded;charset=UTF-8`:r(e)?e.type||null:o.isBuffer(e)||isAnyArrayBuffer(e)||ArrayBuffer.isView(e)?null:e instanceof d?`multipart/form-data; boundary=${t[p].boundary}`:e instanceof l?null:`text/plain;charset=UTF-8`,getTotalBytes=e=>{let{body:t}=e[p];if(t===null)return 0;if(r(t))return t.size;if(o.isBuffer(t))return t.length;if(t&&typeof t.getLengthSync==`function`){let e=t;return e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null}return null},writeToStream=async(e,{body:t})=>{t===null?e.end():await pipeline$1(t,e)};function readableStreamToReadable(e){let t=e.getReader();return new c({async read(){try{let{done:e,value:n}=await t.read();e?this.push(null):this.push(o.from(n))}catch(e){this.destroy(e)}},destroy(e,n){t.cancel().then(()=>n(null),n)}})}async function*blobToAsyncIterable(e){if(typeof e.stream==`function`){let t=e.stream().getReader();for(;;){let{done:e,value:n}=await t.read();if(e)break;yield n}}else yield new Uint8Array(await e.arrayBuffer())}export{clone,Body as default,extractContentType,getTotalBytes,writeToStream};
1
+ import{__name as e}from"./_virtual/_rolldown/runtime.js";import{Blob as t}from"./utils/blob-from.js";import{FetchBaseError as n}from"./errors/base.js";import{FetchError as r}from"./errors/fetch-error.js";import{isBlob as i,isURLSearchParameters as a}from"./utils/is.js";import{URLSearchParams as o}from"@gjsify/url";import{Buffer as s}from"node:buffer";import{PassThrough as c,Readable as l,Stream as u,pipeline as d}from"node:stream";import{FormData as f,formDataToBlob as p}from"@gjsify/formdata";const m=e((e,t)=>new Promise((n,r)=>{d(e,t,e=>{e?r(e):n()})}),`pipeline`),h=Symbol(`Body internals`);function isAnyArrayBuffer(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer}var Body=class{[h]={body:null,stream:null,boundary:``,disturbed:!1,error:null};size=0;constructor(e,t={size:0}){if(this.size=t.size||0,e==null)this[h].body=null;else if(a(e))this[h].body=s.from(e.toString());else if(i(e))this[h].body=e;else if(s.isBuffer(e))this[h].body=e;else if(isAnyArrayBuffer(e))this[h].body=s.from(e);else if(ArrayBuffer.isView(e))this[h].body=s.from(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof l)this[h].body=e;else if(typeof ReadableStream<`u`&&e instanceof ReadableStream)this[h].body=readableStreamToReadable(e);else if(e instanceof f){let t=p(e);this[h].body=t,this[h].boundary=t.type?.split(`boundary=`)?.[1]??``}else typeof e==`string`?this[h].body=s.from(e):e instanceof o?this[h].body=s.from(e.toString()):(console.warn(`Unknown body type "${typeof e}", try to parse the body to string!`),this[h].body=s.from(String(e)));let c=this[h].body;s.isBuffer(c)?this[h].stream=l.from(c):i(c)?this[h].stream=l.from(blobToAsyncIterable(c)):c instanceof l&&(this[h].stream=c),c instanceof u&&c.on(`error`,e=>{let t=e instanceof n?e:new r(`Invalid response body while trying to fetch ${this.url}: ${e.message}`,`system`,e);this[h].error=t})}get body(){let e=this[h].stream;if(!e)return null;if(typeof ReadableStream<`u`){let t=!1;return new ReadableStream({start(n){e.on(`data`,e=>{if(!t)try{n.enqueue(e instanceof Uint8Array?e:new Uint8Array(e))}catch{}}),e.on(`end`,()=>{if(!t){t=!0;try{n.close()}catch{}}}),e.on(`error`,e=>{if(!t){t=!0;try{n.error(e)}catch{}}})},cancel(){t=!0,e.destroy()}})}return null}get _stream(){return this[h].stream}get _rawBodyBuffer(){let e=this[h].body;return e===null?null:s.isBuffer(e)?e:e instanceof Uint8Array?s.from(e.buffer,e.byteOffset,e.byteLength):null}get bodyUsed(){return this[h].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:n}=await consumeBody(this);return e.slice(t,t+n)}async formData(){let e=this.headers?.get(`content-type`);if(e?.startsWith(`application/x-www-form-urlencoded`)){let e=new f,t=new o(await this.text());for(let[n,r]of t)e.append(n,r);return e}let{toFormData:t}=await import(`./utils/multipart-parser.js`);return t(this.body,e)}async blob(){let e=this.headers?.get(`content-type`)||this[h].body&&this[h].body.type||``;return new t([await this.arrayBuffer()],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await consumeBody(this);return new TextDecoder().decode(e)}};Object.defineProperties(Body.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});async function consumeBody(e){if(e[h].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[h].disturbed=!0,e[h].error)throw e[h].error;let{_stream:t}=e;if(t===null||!(t instanceof u))return s.alloc(0);let i=[],a=0;try{for await(let n of t){if(e.size>0&&a+n.length>e.size){let n=new r(`content size at ${e.url} over limit: ${e.size}`,`max-size`);throw t.destroy(n),n}a+=n.length,i.push(n)}}catch(t){let i=t instanceof Error?t:Error(String(t));throw t instanceof n?t:new r(`Invalid response body while trying to fetch ${e.url}: ${i.message}`,`system`,i)}try{return i.every(e=>typeof e==`string`)?s.from(i.join(``)):s.concat(i,a)}catch(t){let n=t instanceof Error?t:Error(String(t));throw new r(`Could not create Buffer from response body for ${e.url}: ${n.message}`,`system`,n)}}const clone=(e,t)=>{let n,r,{body:i}=e[h];if(e.bodyUsed)throw Error(`cannot clone body after it is used`);return i instanceof u&&typeof i.getBoundary!=`function`&&(n=new c({highWaterMark:t}),r=new c({highWaterMark:t}),i.pipe(n),i.pipe(r),e[h].stream=n,i=r),i},extractContentType=(e,t)=>e===null?null:typeof e==`string`?`text/plain;charset=UTF-8`:a(e)?`application/x-www-form-urlencoded;charset=UTF-8`:i(e)?e.type||null:s.isBuffer(e)||isAnyArrayBuffer(e)||ArrayBuffer.isView(e)?null:e instanceof f?`multipart/form-data; boundary=${t[h].boundary}`:e instanceof u?null:`text/plain;charset=UTF-8`,getTotalBytes=e=>{let{body:t}=e[h];if(t===null)return 0;if(i(t))return t.size;if(s.isBuffer(t))return t.length;if(t&&typeof t.getLengthSync==`function`){let e=t;return e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null}return null},writeToStream=async(e,{body:t})=>{t===null?e.end():await m(t,e)};function readableStreamToReadable(e){let t=e.getReader();return new l({async read(){try{let{done:e,value:n}=await t.read();e?this.push(null):this.push(s.from(n))}catch(e){this.destroy(e)}},destroy(e,n){t.cancel().then(()=>n(null),n)}})}async function*blobToAsyncIterable(e){if(typeof e.stream==`function`){let t=e.stream().getReader();for(;;){let{done:e,value:n}=await t.read();if(e)break;yield n}}else yield new Uint8Array(await e.arrayBuffer())}export{clone,Body as default,extractContentType,getTotalBytes,writeToStream};
@@ -1 +1 @@
1
- import{FetchBaseError as e}from"./base.js";var AbortError=class extends e{constructor(e,t=`aborted`){super(e,t)}};export{AbortError};
1
+ import"../_virtual/_rolldown/runtime.js";import{FetchBaseError as e}from"./base.js";var AbortError=class extends e{constructor(e,t=`aborted`){super(e,t)}};export{AbortError};
@@ -1 +1 @@
1
- var FetchBaseError=class extends Error{type;constructor(e,t){super(e),typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}};export{FetchBaseError};
1
+ import"../_virtual/_rolldown/runtime.js";var FetchBaseError=class extends Error{type;constructor(e,t){super(e),typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}};export{FetchBaseError};
@@ -1 +1 @@
1
- import{FetchBaseError as e}from"./base.js";var FetchError=class extends e{code;errno;erroredSysCall;constructor(e,t,n){super(e,t),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}};export{FetchError};
1
+ import"../_virtual/_rolldown/runtime.js";import{FetchBaseError as e}from"./base.js";var FetchError=class extends e{code;errno;erroredSysCall;constructor(e,t,n){super(e,t),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}};export{FetchError};
@@ -1 +1 @@
1
- import e from"@girs/soup-3.0";import{validateHeaderName as t,validateHeaderValue as n}from"@gjsify/http/validators";const r=Symbol(`Headers.headers`);function isBoxedPrimitive(e){return e instanceof String||e instanceof Number||e instanceof Boolean||typeof Symbol<`u`&&e instanceof Symbol||typeof BigInt<`u`&&e instanceof BigInt}var i=class Headers{[r];constructor(e){if(this[r]=new Map,e!=null){if(e instanceof Headers){for(let[t,n]of e[r])this[r].set(t,[...n]);return}if(typeof e==`object`&&!isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)for(let[r,i]of Object.entries(e))t(r),n(r,String(i)),this.append(r,String(i));else{if(typeof r!=`function`)throw TypeError(`Header pairs must be iterable`);for(let r of e){if(typeof r!=`object`||isBoxedPrimitive(r))throw TypeError(`Each header pair must be an iterable object`);let e=[...r];if(e.length!==2)throw TypeError(`Each header pair must be a name/value tuple`);t(e[0]),n(e[0],String(e[1])),this.append(e[0],String(e[1]))}}}else throw TypeError(`Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)'`)}}append(e,i){t(e),n(e,i);let a=String(e).toLowerCase(),o=String(i),s=this[r].get(a);s?s.push(o):this[r].set(a,[o])}set(e,i){t(e),n(e,i);let a=String(e).toLowerCase();this[r].set(a,[String(i)])}delete(e){this[r].delete(String(e).toLowerCase())}has(e){return this[r].has(String(e).toLowerCase())}get(e){let t=this[r].get(String(e).toLowerCase());if(!t||t.length===0)return null;let n=t.join(`, `);return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}getAll(e){return this[r].get(String(e).toLowerCase())??[]}getSetCookie(){return this[r].get(`set-cookie`)??[]}forEach(e,t){for(let n of this.keys())Reflect.apply(e,t,[this.get(n),n,this])}*keys(){let e=[...this[r].keys()].sort(),t=new Set;for(let n of e)t.has(n)||(t.add(n),yield n)}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return`Headers`}toString(){return Object.prototype.toString.call(this)}raw(){let e={};for(let t of this.keys())e[t]=this.getAll(t);return e}_appendToSoupMessage(t,n=e.MessageHeadersType.REQUEST){let r=t?t.get_request_headers():new e.MessageHeaders(n);for(let[e,t]of this.entries())r.append(e,t);return r}static _newFromSoupMessage(t,n=e.MessageHeadersType.RESPONSE){let r=new Headers,i;return i=n===e.MessageHeadersType.RESPONSE?t.get_response_headers():t.get_request_headers(),i.foreach((e,t)=>{r.append(e,t)}),r}[Symbol.for(`nodejs.util.inspect.custom`)](){let e={};for(let t of this.keys()){let n=this.getAll(t);t===`host`?e[t]=n[0]:e[t]=n.length>1?n:n[0]}return e}};Object.defineProperties(i.prototype,[`get`,`entries`,`forEach`,`values`].reduce((e,t)=>(e[t]={enumerable:!0},e),{}));export{i as default};
1
+ import"./_virtual/_rolldown/runtime.js";import e from"@girs/soup-3.0";import{validateHeaderName as t,validateHeaderValue as n}from"@gjsify/http/validators";const r=Symbol(`Headers.headers`);function isBoxedPrimitive(e){return e instanceof String||e instanceof Number||e instanceof Boolean||typeof Symbol<`u`&&e instanceof Symbol||typeof BigInt<`u`&&e instanceof BigInt}var i=class Headers{[r];constructor(e){if(this[r]=new Map,e!=null){if(e instanceof Headers){for(let[t,n]of e[r])this[r].set(t,[...n]);return}if(typeof e==`object`&&!isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)for(let[r,i]of Object.entries(e))t(r),n(r,String(i)),this.append(r,String(i));else{if(typeof r!=`function`)throw TypeError(`Header pairs must be iterable`);for(let r of e){if(typeof r!=`object`||isBoxedPrimitive(r))throw TypeError(`Each header pair must be an iterable object`);let e=[...r];if(e.length!==2)throw TypeError(`Each header pair must be a name/value tuple`);t(e[0]),n(e[0],String(e[1])),this.append(e[0],String(e[1]))}}}else throw TypeError(`Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)'`)}}append(e,i){t(e),n(e,i);let a=String(e).toLowerCase(),o=String(i),s=this[r].get(a);s?s.push(o):this[r].set(a,[o])}set(e,i){t(e),n(e,i);let a=String(e).toLowerCase();this[r].set(a,[String(i)])}delete(e){this[r].delete(String(e).toLowerCase())}has(e){return this[r].has(String(e).toLowerCase())}get(e){let t=this[r].get(String(e).toLowerCase());if(!t||t.length===0)return null;let n=t.join(`, `);return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}getAll(e){return this[r].get(String(e).toLowerCase())??[]}getSetCookie(){return this[r].get(`set-cookie`)??[]}forEach(e,t){for(let n of this.keys())Reflect.apply(e,t,[this.get(n),n,this])}*keys(){let e=[...this[r].keys()].sort(),t=new Set;for(let n of e)t.has(n)||(t.add(n),yield n)}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return`Headers`}toString(){return Object.prototype.toString.call(this)}raw(){let e={};for(let t of this.keys())e[t]=this.getAll(t);return e}_appendToSoupMessage(t,n=e.MessageHeadersType.REQUEST){let r=t?t.get_request_headers():new e.MessageHeaders(n);for(let[e,t]of this.entries())r.append(e,t);return r}static _newFromSoupMessage(t,n=e.MessageHeadersType.RESPONSE){let r=new Headers,i;return i=n===e.MessageHeadersType.RESPONSE?t.get_response_headers():t.get_request_headers(),i.foreach((e,t)=>{r.append(e,t)}),r}[Symbol.for(`nodejs.util.inspect.custom`)](){let e={};for(let t of this.keys()){let n=this.getAll(t);t===`host`?e[t]=n[0]:e[t]=n.length>1?n:n[0]}return e}};Object.defineProperties(i.prototype,[`get`,`entries`,`forEach`,`values`].reduce((e,t)=>(e[t]={enumerable:!0},e),{}));export{i as default};
package/lib/esm/index.js CHANGED
@@ -1 +1 @@
1
- import{Blob as e,File as t}from"./utils/blob-from.js";import{FetchError as n}from"./errors/fetch-error.js";import{isDomainOrSubdomain as r,isSameProtocol as i}from"./utils/is.js";import{clone as a}from"./body.js";import o from"./headers.js";import{parseDataUri as s}from"./utils/data-uri.js";import{isRedirect as c}from"./utils/is-redirect.js";import{Response as l}from"./response.js";import{parseReferrerPolicyFromHeader as u}from"./utils/referrer.js";import{Request as d,getSoupRequestOptions as f}from"./request.js";import{AbortError as p}from"./errors/abort-error.js";import{XMLHttpRequest as m,XMLHttpRequestUpload as h}from"./xhr.js";import{URL as g}from"@gjsify/url";import _ from"node:stream";import{FormData as v}from"@gjsify/formdata";import y from"@girs/glib-2.0";const b=new Set([`data:`,`http:`,`https:`,`file:`]);function rewriteRootRelativeUrl(e){if(typeof e!=`string`||!e.startsWith(`/`)||e.startsWith(`//`))return e;let t=globalThis.__GJSIFY_DEBUG_FETCH===!0;try{let n=globalThis.imports,r=n?.system?.programPath??n?.system?.programInvocationName??``;if(!r)return e;let i=`file://${y.path_get_dirname(r)}${e}`;return t&&console.log(`[fetch] rewrite ${e} → ${i}`),i}catch(n){return t&&console.warn(`[fetch] rewrite FAILED: ${n?.message??n}`),e}}async function fetch(e,t={}){e=rewriteRootRelativeUrl(e);let m=new d(e,t),{parsedURL:h,options:v}=f(m);if(!b.has(h.protocol))throw TypeError(`@gjsify/fetch cannot load ${e}. URL scheme "${h.protocol.replace(/:$/,``)}" is not supported.`);if(h.protocol===`data:`){let{buffer:e,typeFull:t}=s(m.url);return new l(Buffer.from(e),{headers:{"Content-Type":t}})}if(h.protocol===`file:`){let e=globalThis.__GJSIFY_DEBUG_FETCH===!0;e&&console.log(`[fetch] file:// ${m.url}`);try{let t=y.filename_from_uri(m.url)[0];e&&console.log(`[fetch] file:// path=${t}`);let[r,i]=y.file_get_contents(t);if(e&&console.log(`[fetch] file:// ok=${r} bytes=${i?.byteLength??`?`}`),!r)throw new n(`Failed to read file: ${t}`,`system`);let a=i,o=new Uint8Array(a.byteLength);o.set(a);let s=new l(o);return e&&console.log(`[fetch] file:// response created`),s}catch(t){let r=t instanceof Error?t:Error(String(t));throw e&&console.warn(`[fetch] file:// FAIL: ${r.message}`),new n(`request to ${m.url} failed, reason: ${r.message}`,`system`,r)}}let{signal:x}=m;if(x&&x.aborted)throw new p(`The operation was aborted.`);let S,C;try{let e=await m._send(v);S=e.readable,C=e.cancellable}catch(e){let t=e instanceof Error?e:Error(String(e));throw new n(`request to ${m.url} failed, reason: ${t.message}`,`system`,t)}let abortHandler=()=>{C.cancel()};x&&x.addEventListener(`abort`,abortHandler,{once:!0});let finalize=()=>{x&&x.removeEventListener(`abort`,abortHandler)};C.connect(()=>{S.destroy(new p(`The operation was aborted.`))}),S.on(`error`,e=>{finalize()});let w=m._message,T=o._newFromSoupMessage(w),E=w.status_code,D=w.get_reason_phrase();if(c(E)){let e=T.get(`Location`),s=null;try{s=e===null?null:new g(e,m.url)}catch{if(m.redirect!==`manual`)throw finalize(),new n(`uri requested responds with an invalid redirect URL: ${e}`,`invalid-redirect`)}switch(m.redirect){case`error`:throw finalize(),new n(`uri requested responds with a redirect, redirect mode is set to error: ${m.url}`,`no-redirect`);case`manual`:break;case`follow`:{if(s===null)break;if(m.counter>=m.follow)throw finalize(),new n(`maximum redirect reached at: ${m.url}`,`max-redirect`);let e={headers:new o(m.headers),follow:m.follow,counter:m.counter+1,agent:m.agent,compress:m.compress,method:m.method,body:a(m),signal:m.signal,size:m.size,referrer:m.referrer,referrerPolicy:m.referrerPolicy};if(!r(m.url,s)||!i(m.url,s))for(let t of[`authorization`,`www-authenticate`,`cookie`,`cookie2`])e.headers.delete(t);if(E!==303&&m.body&&t.body instanceof _.Readable)throw finalize(),new n(`Cannot follow redirect with body being a readable stream`,`unsupported-redirect`);(E===303||(E===301||E===302)&&m.method===`POST`)&&(e.method=`GET`,e.body=void 0,e.headers.delete(`content-length`));let c=u(T);return c&&(e.referrerPolicy=c),finalize(),fetch(new d(s,e))}default:throw TypeError(`Redirect option '${m.redirect}' is not a valid value of RequestRedirect`)}}let O={url:m.url,status:E,statusText:D,headers:T,size:m.size,counter:m.counter,highWaterMark:m.highWaterMark},k=T.get(`Content-Encoding`);if(!m.compress||m.method===`HEAD`||k===null||E===204||E===304)return finalize(),new l(S,O);if(typeof DecompressionStream<`u`){let e=null;if(k===`gzip`||k===`x-gzip`?e=`gzip`:(k===`deflate`||k===`x-deflate`)&&(e=`deflate`),e){let t=new l(S,O).body;if(t){let n=t.pipeThrough(new DecompressionStream(e));return finalize(),new l(n,O)}}}return finalize(),new l(S,O)}export{p as AbortError,e as Blob,n as FetchError,t as File,v as FormData,o as Headers,d as Request,l as Response,m as XMLHttpRequest,h as XMLHttpRequestUpload,fetch as default,c as isRedirect};
1
+ import"./_virtual/_rolldown/runtime.js";import{Blob as e,File as t}from"./utils/blob-from.js";import{FetchError as n}from"./errors/fetch-error.js";import{isDomainOrSubdomain as r,isSameProtocol as i}from"./utils/is.js";import{clone as a}from"./body.js";import o from"./headers.js";import{parseDataUri as s}from"./utils/data-uri.js";import{isRedirect as c}from"./utils/is-redirect.js";import{Response as l}from"./response.js";import{parseReferrerPolicyFromHeader as u}from"./utils/referrer.js";import{Request as d,getSoupRequestOptions as f}from"./request.js";import{AbortError as p}from"./errors/abort-error.js";import{XMLHttpRequest as m,XMLHttpRequestUpload as h}from"./xhr.js";import{URL as g}from"@gjsify/url";import _ from"node:stream";import{FormData as v}from"@gjsify/formdata";import y from"@girs/glib-2.0";const b=new Set([`data:`,`http:`,`https:`,`file:`]);function rewriteRootRelativeUrl(e){if(typeof e!=`string`||!e.startsWith(`/`)||e.startsWith(`//`))return e;let t=globalThis.__GJSIFY_DEBUG_FETCH===!0;try{let n=globalThis.imports,r=n?.system?.programPath??n?.system?.programInvocationName??``;if(!r)return e;let i=`file://${y.path_get_dirname(r)}${e}`;return t&&console.log(`[fetch] rewrite ${e} → ${i}`),i}catch(n){return t&&console.warn(`[fetch] rewrite FAILED: ${n?.message??n}`),e}}async function fetch(e,t={}){e=rewriteRootRelativeUrl(e);let m=new d(e,t),{parsedURL:h,options:v}=f(m);if(!b.has(h.protocol))throw TypeError(`@gjsify/fetch cannot load ${e}. URL scheme "${h.protocol.replace(/:$/,``)}" is not supported.`);if(h.protocol===`data:`){let{buffer:e,typeFull:t}=s(m.url);return new l(Buffer.from(e),{headers:{"Content-Type":t}})}if(h.protocol===`file:`){let e=globalThis.__GJSIFY_DEBUG_FETCH===!0;e&&console.log(`[fetch] file:// ${m.url}`);try{let t=y.filename_from_uri(m.url)[0];e&&console.log(`[fetch] file:// path=${t}`);let[r,i]=y.file_get_contents(t);if(e&&console.log(`[fetch] file:// ok=${r} bytes=${i?.byteLength??`?`}`),!r)throw new n(`Failed to read file: ${t}`,`system`);let a=i,o=new Uint8Array(a.byteLength);o.set(a);let s=new l(o);return e&&console.log(`[fetch] file:// response created`),s}catch(t){let r=t instanceof Error?t:Error(String(t));throw e&&console.warn(`[fetch] file:// FAIL: ${r.message}`),new n(`request to ${m.url} failed, reason: ${r.message}`,`system`,r)}}let{signal:x}=m;if(x&&x.aborted)throw new p(`The operation was aborted.`);let S,C;try{let e=await m._send(v);S=e.readable,C=e.cancellable}catch(e){let t=e instanceof Error?e:Error(String(e));throw new n(`request to ${m.url} failed, reason: ${t.message}`,`system`,t)}let abortHandler=()=>{C.cancel()};x&&x.addEventListener(`abort`,abortHandler,{once:!0});let finalize=()=>{x&&x.removeEventListener(`abort`,abortHandler)};C.connect(()=>{S.destroy(new p(`The operation was aborted.`))}),S.on(`error`,e=>{finalize()});let w=m._message,T=o._newFromSoupMessage(w),E=w.status_code,D=w.get_reason_phrase();if(c(E)){let e=T.get(`Location`),s=null;try{s=e===null?null:new g(e,m.url)}catch{if(m.redirect!==`manual`)throw finalize(),new n(`uri requested responds with an invalid redirect URL: ${e}`,`invalid-redirect`)}switch(m.redirect){case`error`:throw finalize(),new n(`uri requested responds with a redirect, redirect mode is set to error: ${m.url}`,`no-redirect`);case`manual`:break;case`follow`:{if(s===null)break;if(m.counter>=m.follow)throw finalize(),new n(`maximum redirect reached at: ${m.url}`,`max-redirect`);let e={headers:new o(m.headers),follow:m.follow,counter:m.counter+1,agent:m.agent,compress:m.compress,method:m.method,body:a(m),signal:m.signal,size:m.size,referrer:m.referrer,referrerPolicy:m.referrerPolicy};if(!r(m.url,s)||!i(m.url,s))for(let t of[`authorization`,`www-authenticate`,`cookie`,`cookie2`])e.headers.delete(t);if(E!==303&&m.body&&t.body instanceof _.Readable)throw finalize(),new n(`Cannot follow redirect with body being a readable stream`,`unsupported-redirect`);(E===303||(E===301||E===302)&&m.method===`POST`)&&(e.method=`GET`,e.body=void 0,e.headers.delete(`content-length`));let c=u(T);return c&&(e.referrerPolicy=c),finalize(),fetch(new d(s,e))}default:throw TypeError(`Redirect option '${m.redirect}' is not a valid value of RequestRedirect`)}}let O={url:m.url,status:E,statusText:D,headers:T,size:m.size,counter:m.counter,highWaterMark:m.highWaterMark},k=T.get(`Content-Encoding`);if(!m.compress||m.method===`HEAD`||k===null||E===204||E===304)return finalize(),new l(S,O);if(typeof DecompressionStream<`u`){let e=null;if(k===`gzip`||k===`x-gzip`?e=`gzip`:(k===`deflate`||k===`x-deflate`)&&(e=`deflate`),e){let t=new l(S,O).body;if(t){let n=t.pipeThrough(new DecompressionStream(e));return finalize(),new l(n,O)}}}return finalize(),new l(S,O)}export{p as AbortError,e as Blob,n as FetchError,t as File,v as FormData,o as Headers,d as Request,l as Response,m as XMLHttpRequest,h as XMLHttpRequestUpload,fetch as default,c as isRedirect};
@@ -1 +1 @@
1
- import{isAbortSignal as e}from"./utils/is.js";import t,{clone as n,extractContentType as r,getTotalBytes as i}from"./body.js";import a from"./headers.js";import{inputStreamToReadable as o,soupSendAsync as s}from"./utils/soup-helpers.js";import{DEFAULT_REFERRER_POLICY as c,determineRequestsReferrer as l,validateReferrerPolicy as u}from"./utils/referrer.js";import{URL as d}from"@gjsify/url";import f from"@girs/soup-3.0";import p from"@girs/glib-2.0";import m from"@girs/gio-2.0";const h=Symbol(`Request internals`),isRequest=e=>typeof e==`object`&&typeof e.url==`string`;var g=class Request extends t{cache;credentials;destination;get headers(){return this[h].headers}integrity;keepalive;get method(){return this[h].method}mode;get redirect(){return this[h].redirect}get referrer(){if(this[h].referrer===`no-referrer`)return``;if(this[h].referrer===`client`)return`about:client`;if(this[h].referrer)return this[h].referrer.toString()}get referrerPolicy(){return this[h].referrerPolicy}set referrerPolicy(e){this[h].referrerPolicy=u(e)}get signal(){return this[h].signal}get url(){return this[h].parsedURL.toString()}get _uri(){return p.Uri.parse(this.url,p.UriFlags.NONE)}get _session(){return this[h].session}get _message(){return this[h].message}get _inputStream(){return this[h].inputStream}get[Symbol.toStringTag](){return`Request`}[h];follow;compress=!1;counter=0;agent=``;highWaterMark=16384;insecureHTTPParser=!1;constructor(t,i){let o=t,s=i||{},c,l={};if(isRequest(t)?(c=new d(o.url),l=o):c=new d(t),c.username!==``||c.password!==``)throw TypeError(`${c} is an url with embedded credentials.`);let u=s.method||l.method||`GET`;if(/^(delete|get|head|options|post|put)$/i.test(u)&&(u=u.toUpperCase()),(i?.body!=null||isRequest(t)&&o.body!==null)&&(u===`GET`||u===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body`);let m=i?.body?i.body:isRequest(t)&&o.body!==null?n(t):null;super(m,{size:s.size||0});let g=new a(i?.headers||o.headers||{});if(m!==null&&!g.has(`Content-Type`)){let e=r(m,this);e&&g.set(`Content-Type`,e)}let _=isRequest(t)?o.signal:null;if(i&&`signal`in i&&(_=i.signal),_!=null&&!e(_))throw TypeError(`Expected signal to be an instanceof AbortSignal or EventTarget`);let v=i?.referrer==null?o.referrer:i.referrer;if(v===``)v=`no-referrer`;else if(v){let e=new d(v);v=/^about:(\/\/)?client$/.test(e.toString())?`client`:e}else v=void 0;let y=c.protocol,b=null,x=null;(y===`http:`||y===`https:`)&&(b=new f.Session,x=new f.Message({method:u,uri:p.Uri.parse(c.toString(),p.UriFlags.NONE)})),this[h]={method:u,redirect:i?.redirect||o.redirect||`follow`,headers:g,parsedURL:c,signal:_,referrer:v,referrerPolicy:``,session:b,message:x},this.follow=s.follow===void 0?o.follow===void 0?20:o.follow:s.follow,this.compress=s.compress===void 0?o.compress===void 0?!0:o.compress:s.compress,this.counter=s.counter||o.counter||0,this.agent=s.agent||o.agent,this.highWaterMark=s.highWaterMark||o.highWaterMark||16384,this.insecureHTTPParser=s.insecureHTTPParser||o.insecureHTTPParser||!1,this.referrerPolicy=i?.referrerPolicy||o.referrerPolicy||``}async _send(e){let{session:t,message:n}=this[h];if(!t||!n)throw Error(`Cannot send request: no Soup session (non-HTTP URL?)`);try{t.remove_feature_by_type(f.ContentDecoder.$gtype)}catch{}e.headers._appendToSoupMessage(n);let r=this._rawBodyBuffer;if(r!==null&&r.byteLength>0){let t=e.headers.get(`content-type`)||null;n.set_request_body_from_bytes(t,new p.Bytes(r))}let i=new m.Cancellable;return this[h].inputStream=await s(t,n,p.PRIORITY_DEFAULT,i),this[h].readable=o(this[h].inputStream),{inputStream:this[h].inputStream,readable:this[h].readable,cancellable:i}}clone(){return new Request(this)}async arrayBuffer(){return super.arrayBuffer()}async blob(){return super.blob()}async formData(){return super.formData()}async json(){return super.json()}async text(){return super.text()}};Object.defineProperties(g.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});const getSoupRequestOptions=e=>{let{parsedURL:t}=e[h],n=new a(e[h].headers);n.has(`Accept`)||n.set(`Accept`,`*/*`);let r=null;if(e.body===null&&/^(post|put)$/i.test(e.method)&&(r=`0`),e.body!==null){let t=i(e);typeof t==`number`&&!Number.isNaN(t)&&(r=String(t))}r&&n.set(`Content-Length`,r),e.referrerPolicy===``&&(e.referrerPolicy=c),e.referrer&&e.referrer!==`no-referrer`?e[h].referrer=l(e):e[h].referrer=`no-referrer`,e[h].referrer instanceof d&&n.set(`Referer`,e.referrer),n.has(`User-Agent`)||n.set(`User-Agent`,`gjsify-fetch`),e.compress&&!n.has(`Accept-Encoding`)&&n.set(`Accept-Encoding`,`gzip, deflate`);let{agent:o}=e;return typeof o==`function`&&(o=o(t)),!n.has(`Connection`)&&!o&&n.set(`Connection`,`close`),{parsedURL:t,options:{headers:n}}};export{g as Request,g as default,getSoupRequestOptions};
1
+ import"./_virtual/_rolldown/runtime.js";import{isAbortSignal as e}from"./utils/is.js";import t,{clone as n,extractContentType as r,getTotalBytes as i}from"./body.js";import a from"./headers.js";import{inputStreamToReadable as o,soupSendAsync as s}from"./utils/soup-helpers.js";import{DEFAULT_REFERRER_POLICY as c,determineRequestsReferrer as l,validateReferrerPolicy as u}from"./utils/referrer.js";import{URL as d}from"@gjsify/url";import f from"@girs/soup-3.0";import p from"@girs/glib-2.0";import m from"@girs/gio-2.0";const h=Symbol(`Request internals`),isRequest=e=>typeof e==`object`&&typeof e.url==`string`;var g=class Request extends t{cache;credentials;destination;get headers(){return this[h].headers}integrity;keepalive;get method(){return this[h].method}mode;get redirect(){return this[h].redirect}get referrer(){if(this[h].referrer===`no-referrer`)return``;if(this[h].referrer===`client`)return`about:client`;if(this[h].referrer)return this[h].referrer.toString()}get referrerPolicy(){return this[h].referrerPolicy}set referrerPolicy(e){this[h].referrerPolicy=u(e)}get signal(){return this[h].signal}get url(){return this[h].parsedURL.toString()}get _uri(){return p.Uri.parse(this.url,p.UriFlags.NONE)}get _session(){return this[h].session}get _message(){return this[h].message}get _inputStream(){return this[h].inputStream}get[Symbol.toStringTag](){return`Request`}[h];follow;compress=!1;counter=0;agent=``;highWaterMark=16384;insecureHTTPParser=!1;constructor(t,i){let o=t,s=i||{},c,l={};if(isRequest(t)?(c=new d(o.url),l=o):c=new d(t),c.username!==``||c.password!==``)throw TypeError(`${c} is an url with embedded credentials.`);let u=s.method||l.method||`GET`;if(/^(delete|get|head|options|post|put)$/i.test(u)&&(u=u.toUpperCase()),(i?.body!=null||isRequest(t)&&o.body!==null)&&(u===`GET`||u===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body`);let m=i?.body?i.body:isRequest(t)&&o.body!==null?n(t):null;super(m,{size:s.size||0});let g=new a(i?.headers||o.headers||{});if(m!==null&&!g.has(`Content-Type`)){let e=r(m,this);e&&g.set(`Content-Type`,e)}let _=isRequest(t)?o.signal:null;if(i&&`signal`in i&&(_=i.signal),_!=null&&!e(_))throw TypeError(`Expected signal to be an instanceof AbortSignal or EventTarget`);let v=i?.referrer==null?o.referrer:i.referrer;if(v===``)v=`no-referrer`;else if(v){let e=new d(v);v=/^about:(\/\/)?client$/.test(e.toString())?`client`:e}else v=void 0;let y=c.protocol,b=null,x=null;(y===`http:`||y===`https:`)&&(b=new f.Session,x=new f.Message({method:u,uri:p.Uri.parse(c.toString(),p.UriFlags.NONE)})),this[h]={method:u,redirect:i?.redirect||o.redirect||`follow`,headers:g,parsedURL:c,signal:_,referrer:v,referrerPolicy:``,session:b,message:x},this.follow=s.follow===void 0?o.follow===void 0?20:o.follow:s.follow,this.compress=s.compress===void 0?o.compress===void 0?!0:o.compress:s.compress,this.counter=s.counter||o.counter||0,this.agent=s.agent||o.agent,this.highWaterMark=s.highWaterMark||o.highWaterMark||16384,this.insecureHTTPParser=s.insecureHTTPParser||o.insecureHTTPParser||!1,this.referrerPolicy=i?.referrerPolicy||o.referrerPolicy||``}async _send(e){let{session:t,message:n}=this[h];if(!t||!n)throw Error(`Cannot send request: no Soup session (non-HTTP URL?)`);try{t.remove_feature_by_type(f.ContentDecoder.$gtype)}catch{}e.headers._appendToSoupMessage(n);let r=this._rawBodyBuffer;if(r!==null&&r.byteLength>0){let t=e.headers.get(`content-type`)||null;n.set_request_body_from_bytes(t,new p.Bytes(r))}let i=new m.Cancellable;return this[h].inputStream=await s(t,n,p.PRIORITY_DEFAULT,i),this[h].readable=o(this[h].inputStream),{inputStream:this[h].inputStream,readable:this[h].readable,cancellable:i}}clone(){return new Request(this)}async arrayBuffer(){return super.arrayBuffer()}async blob(){return super.blob()}async formData(){return super.formData()}async json(){return super.json()}async text(){return super.text()}};Object.defineProperties(g.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});const getSoupRequestOptions=e=>{let{parsedURL:t}=e[h],n=new a(e[h].headers);n.has(`Accept`)||n.set(`Accept`,`*/*`);let r=null;if(e.body===null&&/^(post|put)$/i.test(e.method)&&(r=`0`),e.body!==null){let t=i(e);typeof t==`number`&&!Number.isNaN(t)&&(r=String(t))}r&&n.set(`Content-Length`,r),e.referrerPolicy===``&&(e.referrerPolicy=c),e.referrer&&e.referrer!==`no-referrer`?e[h].referrer=l(e):e[h].referrer=`no-referrer`,e[h].referrer instanceof d&&n.set(`Referer`,e.referrer),n.has(`User-Agent`)||n.set(`User-Agent`,`gjsify-fetch`),e.compress&&!n.has(`Accept-Encoding`)&&n.set(`Accept-Encoding`,`gzip, deflate`);let{agent:o}=e;return typeof o==`function`&&(o=o(t)),!n.has(`Connection`)&&!o&&n.set(`Connection`,`close`),{parsedURL:t,options:{headers:n}}};export{g as Request,g as default,getSoupRequestOptions};
@@ -1 +1 @@
1
- import e,{clone as t,extractContentType as n}from"./body.js";import r from"./headers.js";import{isRedirect as i}from"./utils/is-redirect.js";import{URL as a}from"@gjsify/url";import o from"@girs/glib-2.0";import s from"@girs/gio-2.0";const c=Symbol(`Response internals`);var l=class Response extends e{[c];_inputStream=null;constructor(e=null,t={}){super(e,t);let i=t.status==null?200:t.status,a=new r(t.headers);if(e!==null&&!a.has(`Content-Type`)){let t=n(e,this);t&&a.append(`Content-Type`,t)}this[c]={type:`default`,url:t.url,status:i,statusText:t.statusText||``,headers:a,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[c].type}get url(){return this[c].url||``}get status(){return this[c].status}get ok(){return this[c].status>=200&&this[c].status<300}get redirected(){return this[c].counter>0}get statusText(){return this[c].statusText}get headers(){return this[c].headers}get highWaterMark(){return this[c].highWaterMark}clone(){return new Response(t(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,t=302){if(!i(t))throw RangeError(`Failed to execute "redirect" on "response": Invalid status code`);return new Response(null,{headers:{location:new a(e).toString()},status:t})}static error(){let e=new Response(null,{status:0,statusText:``});return e[c].type=`error`,e}static json(e,t){let n=JSON.stringify(e),i={...t},a=new r(i.headers);return a.has(`content-type`)||a.set(`content-type`,`application/json`),i.headers=a,new Response(n,i)}get[Symbol.toStringTag](){return`Response`}async text(){if(!this._inputStream)return super.text();let e=s.MemoryOutputStream.new_resizable();await new Promise((t,n)=>{e.splice_async(this._inputStream,s.OutputStreamSpliceFlags.CLOSE_TARGET|s.OutputStreamSpliceFlags.CLOSE_SOURCE,o.PRIORITY_DEFAULT,null,(r,i)=>{try{t(e.splice_finish(i))}catch(e){n(e)}})});let t=e.steal_as_bytes();return new TextDecoder().decode(t.toArray())}};Object.defineProperties(l.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});export{l as Response,l as default};
1
+ import"./_virtual/_rolldown/runtime.js";import e,{clone as t,extractContentType as n}from"./body.js";import r from"./headers.js";import{isRedirect as i}from"./utils/is-redirect.js";import{URL as a}from"@gjsify/url";import o from"@girs/glib-2.0";import s from"@girs/gio-2.0";const c=Symbol(`Response internals`);var l=class Response extends e{[c];_inputStream=null;constructor(e=null,t={}){super(e,t);let i=t.status==null?200:t.status,a=new r(t.headers);if(e!==null&&!a.has(`Content-Type`)){let t=n(e,this);t&&a.append(`Content-Type`,t)}this[c]={type:`default`,url:t.url,status:i,statusText:t.statusText||``,headers:a,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[c].type}get url(){return this[c].url||``}get status(){return this[c].status}get ok(){return this[c].status>=200&&this[c].status<300}get redirected(){return this[c].counter>0}get statusText(){return this[c].statusText}get headers(){return this[c].headers}get highWaterMark(){return this[c].highWaterMark}clone(){return new Response(t(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,t=302){if(!i(t))throw RangeError(`Failed to execute "redirect" on "response": Invalid status code`);return new Response(null,{headers:{location:new a(e).toString()},status:t})}static error(){let e=new Response(null,{status:0,statusText:``});return e[c].type=`error`,e}static json(e,t){let n=JSON.stringify(e),i={...t},a=new r(i.headers);return a.has(`content-type`)||a.set(`content-type`,`application/json`),i.headers=a,new Response(n,i)}get[Symbol.toStringTag](){return`Response`}async text(){if(!this._inputStream)return super.text();let e=s.MemoryOutputStream.new_resizable();await new Promise((t,n)=>{e.splice_async(this._inputStream,s.OutputStreamSpliceFlags.CLOSE_TARGET|s.OutputStreamSpliceFlags.CLOSE_SOURCE,o.PRIORITY_DEFAULT,null,(r,i)=>{try{t(e.splice_finish(i))}catch(e){n(e)}})});let t=e.steal_as_bytes();return new TextDecoder().decode(t.toArray())}};Object.defineProperties(l.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});export{l as Response,l as default};
@@ -1 +1 @@
1
- function parseDataUri(e){let t=e.match(/^data:([^,]*?)(;base64)?,(.*)$/s);if(!t)throw TypeError(`Invalid data URI: ${e.slice(0,50)}...`);let n=t[1]||`text/plain;charset=US-ASCII`,r=!!t[2],i=t[3],a;if(r){let e=atob(i);a=new Uint8Array(e.length);for(let t=0;t<e.length;t++)a[t]=e.charCodeAt(t)}else a=new TextEncoder().encode(decodeURIComponent(i));return{buffer:a,typeFull:n}}export{parseDataUri};
1
+ import"../_virtual/_rolldown/runtime.js";function parseDataUri(e){let t=e.match(/^data:([^,]*?)(;base64)?,(.*)$/s);if(!t)throw TypeError(`Invalid data URI: ${e.slice(0,50)}...`);let n=t[1]||`text/plain;charset=US-ASCII`,r=!!t[2],i=t[3],a;if(r){let e=atob(i);a=new Uint8Array(e.length);for(let t=0;t<e.length;t++)a[t]=e.charCodeAt(t)}else a=new TextEncoder().encode(decodeURIComponent(i));return{buffer:a,typeFull:n}}export{parseDataUri};
@@ -1 +1 @@
1
- const getSearch=e=>{if(e.search)return e.search;let t=e.href.length-1,n=e.hash||(e.href[t]===`#`?`#`:``);return e.href[t-n.length]===`?`?`?`:``};export{getSearch};
1
+ import"../_virtual/_rolldown/runtime.js";const getSearch=e=>{if(e.search)return e.search;let t=e.href.length-1,n=e.hash||(e.href[t]===`#`?`#`:``);return e.href[t-n.length]===`?`?`?`:``};export{getSearch};
@@ -1 +1 @@
1
- const e=new Set([301,302,303,307,308]),isRedirect=t=>e.has(t);export{isRedirect};
1
+ import"../_virtual/_rolldown/runtime.js";const e=new Set([301,302,303,307,308]),isRedirect=t=>e.has(t);export{isRedirect};
@@ -1 +1 @@
1
- import{URL as e}from"@gjsify/url";const t=Symbol.toStringTag,isURLSearchParameters=e=>typeof e==`object`&&typeof e.append==`function`&&typeof e.delete==`function`&&typeof e.get==`function`&&typeof e.getAll==`function`&&typeof e.has==`function`&&typeof e.set==`function`&&typeof e.sort==`function`&&e[t]===`URLSearchParams`,isBlob=e=>{if(!e||typeof e!=`object`)return!1;let n=e;return typeof n.arrayBuffer==`function`&&typeof n.type==`string`&&typeof n.stream==`function`&&typeof n.constructor==`function`&&/^(Blob|File)$/.test(n[t])},isAbortSignal=e=>{if(typeof e!=`object`||!e)return!1;let n=e;return n[t]===`AbortSignal`||n[t]===`EventTarget`},isDomainOrSubdomain=(t,n)=>{let r=new e(n).hostname,i=new e(t).hostname;return r===i||r.endsWith(`.${i}`)},isSameProtocol=(t,n)=>new e(n).protocol===new e(t).protocol;export{isAbortSignal,isBlob,isDomainOrSubdomain,isSameProtocol,isURLSearchParameters};
1
+ import"../_virtual/_rolldown/runtime.js";import{URL as e}from"@gjsify/url";const t=Symbol.toStringTag,isURLSearchParameters=e=>typeof e==`object`&&typeof e.append==`function`&&typeof e.delete==`function`&&typeof e.get==`function`&&typeof e.getAll==`function`&&typeof e.has==`function`&&typeof e.set==`function`&&typeof e.sort==`function`&&e[t]===`URLSearchParams`,isBlob=e=>{if(!e||typeof e!=`object`)return!1;let n=e;return typeof n.arrayBuffer==`function`&&typeof n.type==`string`&&typeof n.stream==`function`&&typeof n.constructor==`function`&&/^(Blob|File)$/.test(n[t])},isAbortSignal=e=>{if(typeof e!=`object`||!e)return!1;let n=e;return n[t]===`AbortSignal`||n[t]===`EventTarget`},isDomainOrSubdomain=(t,n)=>{let r=new e(n).hostname,i=new e(t).hostname;return r===i||r.endsWith(`.${i}`)},isSameProtocol=(t,n)=>new e(n).protocol===new e(t).protocol;export{isAbortSignal,isBlob,isDomainOrSubdomain,isSameProtocol,isURLSearchParameters};
@@ -1,2 +1,2 @@
1
- import{File as e}from"./blob-from.js";import{FormData as t}from"@gjsify/formdata";var n=function(e){return e[e.START_BOUNDARY=0]=`START_BOUNDARY`,e[e.HEADER_FIELD_START=1]=`HEADER_FIELD_START`,e[e.HEADER_FIELD=2]=`HEADER_FIELD`,e[e.HEADER_VALUE_START=3]=`HEADER_VALUE_START`,e[e.HEADER_VALUE=4]=`HEADER_VALUE`,e[e.HEADER_VALUE_ALMOST_DONE=5]=`HEADER_VALUE_ALMOST_DONE`,e[e.HEADERS_ALMOST_DONE=6]=`HEADERS_ALMOST_DONE`,e[e.PART_DATA_START=7]=`PART_DATA_START`,e[e.PART_DATA=8]=`PART_DATA`,e[e.END=9]=`END`,e}(n||{});let r=1;const i={PART_BOUNDARY:r,LAST_BOUNDARY:r*=2},lower=e=>e|32,noop=(...e)=>{};var MultipartParser=class{index=0;flags=0;boundary;lookbehind;state=0;onHeaderEnd=noop;onHeaderField=noop;onHeadersEnd=noop;onHeaderValue=noop;onPartBegin=noop;onPartData=noop;onPartEnd=noop;boundaryChars={};constructor(e){e=`\r
1
+ import"../_virtual/_rolldown/runtime.js";import{File as e}from"./blob-from.js";import{FormData as t}from"@gjsify/formdata";var n=function(e){return e[e.START_BOUNDARY=0]=`START_BOUNDARY`,e[e.HEADER_FIELD_START=1]=`HEADER_FIELD_START`,e[e.HEADER_FIELD=2]=`HEADER_FIELD`,e[e.HEADER_VALUE_START=3]=`HEADER_VALUE_START`,e[e.HEADER_VALUE=4]=`HEADER_VALUE`,e[e.HEADER_VALUE_ALMOST_DONE=5]=`HEADER_VALUE_ALMOST_DONE`,e[e.HEADERS_ALMOST_DONE=6]=`HEADERS_ALMOST_DONE`,e[e.PART_DATA_START=7]=`PART_DATA_START`,e[e.PART_DATA=8]=`PART_DATA`,e[e.END=9]=`END`,e}(n||{});let r=1;const i={PART_BOUNDARY:r,LAST_BOUNDARY:r*=2},lower=e=>e|32,noop=(...e)=>{};var MultipartParser=class{index=0;flags=0;boundary;lookbehind;state=0;onHeaderEnd=noop;onHeaderField=noop;onHeadersEnd=noop;onHeaderValue=noop;onPartBegin=noop;onPartData=noop;onPartEnd=noop;boundaryChars={};constructor(e){e=`\r
2
2
  --`+e;let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n),this.boundaryChars[t[n]]=!0;this.boundary=t,this.lookbehind=new Uint8Array(this.boundary.length+8)}write(e){let t=0,n=e.length,r=this.index,{lookbehind:a,boundary:o,boundaryChars:s,index:c,state:l,flags:u}=this,d=this.boundary.length,f=d-1,p=e.length,m,h,mark=e=>{this[e+`Mark`]=t},clear=e=>{delete this[e+`Mark`]},callback=(e,t,n,r)=>{(t===void 0||t!==n)&&this[e](r&&r.subarray(t,n))},dataCallback=(n,r=!1)=>{let i=n+`Mark`;i in this&&(r?(callback(n,this[i],t,e),delete this[i]):(callback(n,this[i],e.length,e),this[i]=0))};for(t=0;t<n;t++)switch(m=e[t],l){case 0:if(c===o.length-2){if(m===45)u|=i.LAST_BOUNDARY;else if(m!==13)return;c++;break}else if(c-1==o.length-2){if(u&i.LAST_BOUNDARY&&m===45)l=9,u=0;else if(!(u&i.LAST_BOUNDARY)&&m===10)c=0,callback(`onPartBegin`),l=1;else return;break}m!==o[c+2]&&(c=-2),m===o[c+2]&&c++;break;case 1:l=2,mark(`onHeaderField`),c=0;case 2:if(m===13){clear(`onHeaderField`),l=6;break}if(c++,m===45)break;if(m===58){if(c===1)return;dataCallback(`onHeaderField`,!0),l=3;break}if(h=lower(m),h<97||h>122)return;break;case 3:if(m===32)break;mark(`onHeaderValue`),l=4;case 4:m===13&&(dataCallback(`onHeaderValue`,!0),callback(`onHeaderEnd`),l=5);break;case 5:if(m!==10)return;l=1;break;case 6:if(m!==10)return;callback(`onHeadersEnd`),l=7;break;case 7:l=8,mark(`onPartData`);case 8:if(r=c,c===0){for(t+=f;t<p&&!(e[t]in s);)t+=d;t-=f,m=e[t]}if(c<o.length)o[c]===m?(c===0&&dataCallback(`onPartData`,!0),c++):c=0;else if(c===o.length)c++,m===13?u|=i.PART_BOUNDARY:m===45?u|=i.LAST_BOUNDARY:c=0;else if(c-1===o.length)if(u&i.PART_BOUNDARY){if(c=0,m===10){u&=~i.PART_BOUNDARY,callback(`onPartEnd`),callback(`onPartBegin`),l=1;break}}else u&i.LAST_BOUNDARY&&m===45?(callback(`onPartEnd`),l=9,u=0):c=0;if(c>0)a[c-1]=m;else if(r>0){let e=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);callback(`onPartData`,0,r,e),r=0,mark(`onPartData`),t--}break;case 9:break;default:throw Error(`Unexpected state entered: ${l}`)}dataCallback(`onHeaderField`),dataCallback(`onHeaderValue`),dataCallback(`onPartData`),this.index=c,this.state=l,this.flags=u}end(){if(this.state===1&&this.index===0||this.state===8&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==9)throw Error(`MultipartParser.end(): stream ended unexpectedly`)}};function _fileName(e){let t=e.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!t)return;let n=t[2]||t[3]||``,r=n.slice(n.lastIndexOf(`\\`)+1);return r=r.replace(/%22/g,`"`),r=r.replace(/&#(\d{4});/g,(e,t)=>String.fromCharCode(t)),r}async function toFormData(n,r){if(!/multipart/i.test(r))throw TypeError(`Failed to fetch`);let i=r.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!i)throw TypeError(`no or bad content-type header, no multipart boundary`);let a=new MultipartParser(i[1]||i[2]),o,s,c,l,u,d,f=[],p=new t,onPartData=e=>{c+=m.decode(e,{stream:!0})},appendToFile=e=>{f.push(e)},appendFileToFormData=()=>{let t=new e(f,d,{type:u});p.append(l,t)},appendEntryToFormData=()=>{p.append(l,c)},m=new TextDecoder(`utf-8`);m.decode(),a.onPartBegin=function(){a.onPartData=onPartData,a.onPartEnd=appendEntryToFormData,o=``,s=``,c=``,l=``,u=``,d=null,f.length=0},a.onHeaderField=function(e){o+=m.decode(e,{stream:!0})},a.onHeaderValue=function(e){s+=m.decode(e,{stream:!0})},a.onHeaderEnd=function(){if(s+=m.decode(),o=o.toLowerCase(),o===`content-disposition`){let e=s.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);e&&(l=e[2]||e[3]||``),d=_fileName(s),d&&(a.onPartData=appendToFile,a.onPartEnd=appendFileToFormData)}else o===`content-type`&&(u=s);s=``,o=``};for await(let e of n)a.write(e);return a.end(),p}export{toFormData};
@@ -1 +1 @@
1
- import{URL as e}from"@gjsify/url";import{isIP as t}from"node:net";function stripURLForUseAsAReferrer(t,n=!1){if(t==null||t===`no-referrer`)return`no-referrer`;let r=new e(t);return/^(about|blob|data):$/.test(r.protocol)?`no-referrer`:(r.username=``,r.password=``,r.hash=``,n&&(r.pathname=``,r.search=``),r)}const n=new Set([``,`no-referrer`,`no-referrer-when-downgrade`,`same-origin`,`origin`,`strict-origin`,`origin-when-cross-origin`,`strict-origin-when-cross-origin`,`unsafe-url`]),r=`strict-origin-when-cross-origin`;function validateReferrerPolicy(e){if(!n.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function isOriginPotentiallyTrustworthy(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let n=e.host.replace(/(^\[)|(]$)/g,``),r=t(n);return r===4&&/^127\./.test(n)||r===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(n)?!0:e.host===`localhost`||e.host.endsWith(`.localhost`)?!1:e.protocol===`file:`}function isUrlPotentiallyTrustworthy(t){return/^about:(blank|srcdoc)$/.test(t.toString())||(typeof t==`string`&&(t=new e(t)),t.protocol===`data:`)||/^(blob|filesystem):$/.test(t.protocol)?!0:isOriginPotentiallyTrustworthy(t)}function determineRequestsReferrer(t,n={}){let{referrerURLCallback:r,referrerOriginCallback:i}=n;if(t.referrer===`no-referrer`||t.referrerPolicy===``)return null;let a=t.referrerPolicy;if(t.referrer===`about:client`)return`no-referrer`;let o=new e(t.referrer),s=stripURLForUseAsAReferrer(o),c=stripURLForUseAsAReferrer(o,!0);s.toString().length>4096&&(s=c),r&&(s=r(s)),i&&(c=i(c));let l=new e(t.url);switch(a){case`no-referrer`:return`no-referrer`;case`origin`:return c;case`unsafe-url`:return s;case`strict-origin`:return isUrlPotentiallyTrustworthy(s)&&!isUrlPotentiallyTrustworthy(l)?`no-referrer`:c.toString();case`strict-origin-when-cross-origin`:return s.origin===l.origin?s:isUrlPotentiallyTrustworthy(s)&&!isUrlPotentiallyTrustworthy(l)?`no-referrer`:c;case`same-origin`:return s.origin===l.origin?s:`no-referrer`;case`origin-when-cross-origin`:return s.origin===l.origin?s:c;case`no-referrer-when-downgrade`:return isUrlPotentiallyTrustworthy(s)&&!isUrlPotentiallyTrustworthy(l)?`no-referrer`:s;default:throw TypeError(`Invalid referrerPolicy: ${a}`)}}function parseReferrerPolicyFromHeader(e){let t=(e.get(`referrer-policy`)||``).split(/[,\s]+/),r=``;for(let e of t)e&&n.has(e)&&(r=e);return r}export{r as DEFAULT_REFERRER_POLICY,n as ReferrerPolicy,determineRequestsReferrer,isOriginPotentiallyTrustworthy,isUrlPotentiallyTrustworthy,parseReferrerPolicyFromHeader,stripURLForUseAsAReferrer,validateReferrerPolicy};
1
+ import"../_virtual/_rolldown/runtime.js";import{URL as e}from"@gjsify/url";import{isIP as t}from"node:net";function stripURLForUseAsAReferrer(t,n=!1){if(t==null||t===`no-referrer`)return`no-referrer`;let r=new e(t);return/^(about|blob|data):$/.test(r.protocol)?`no-referrer`:(r.username=``,r.password=``,r.hash=``,n&&(r.pathname=``,r.search=``),r)}const n=new Set([``,`no-referrer`,`no-referrer-when-downgrade`,`same-origin`,`origin`,`strict-origin`,`origin-when-cross-origin`,`strict-origin-when-cross-origin`,`unsafe-url`]),r=`strict-origin-when-cross-origin`;function validateReferrerPolicy(e){if(!n.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function isOriginPotentiallyTrustworthy(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let n=e.host.replace(/(^\[)|(]$)/g,``),r=t(n);return r===4&&/^127\./.test(n)||r===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(n)?!0:e.host===`localhost`||e.host.endsWith(`.localhost`)?!1:e.protocol===`file:`}function isUrlPotentiallyTrustworthy(t){return/^about:(blank|srcdoc)$/.test(t.toString())||(typeof t==`string`&&(t=new e(t)),t.protocol===`data:`)||/^(blob|filesystem):$/.test(t.protocol)?!0:isOriginPotentiallyTrustworthy(t)}function determineRequestsReferrer(t,n={}){let{referrerURLCallback:r,referrerOriginCallback:i}=n;if(t.referrer===`no-referrer`||t.referrerPolicy===``)return null;let a=t.referrerPolicy;if(t.referrer===`about:client`)return`no-referrer`;let o=new e(t.referrer),s=stripURLForUseAsAReferrer(o),c=stripURLForUseAsAReferrer(o,!0);s.toString().length>4096&&(s=c),r&&(s=r(s)),i&&(c=i(c));let l=new e(t.url);switch(a){case`no-referrer`:return`no-referrer`;case`origin`:return c;case`unsafe-url`:return s;case`strict-origin`:return isUrlPotentiallyTrustworthy(s)&&!isUrlPotentiallyTrustworthy(l)?`no-referrer`:c.toString();case`strict-origin-when-cross-origin`:return s.origin===l.origin?s:isUrlPotentiallyTrustworthy(s)&&!isUrlPotentiallyTrustworthy(l)?`no-referrer`:c;case`same-origin`:return s.origin===l.origin?s:`no-referrer`;case`origin-when-cross-origin`:return s.origin===l.origin?s:c;case`no-referrer-when-downgrade`:return isUrlPotentiallyTrustworthy(s)&&!isUrlPotentiallyTrustworthy(l)?`no-referrer`:s;default:throw TypeError(`Invalid referrerPolicy: ${a}`)}}function parseReferrerPolicyFromHeader(e){let t=(e.get(`referrer-policy`)||``).split(/[,\s]+/),r=``;for(let e of t)e&&n.has(e)&&(r=e);return r}export{r as DEFAULT_REFERRER_POLICY,n as ReferrerPolicy,determineRequestsReferrer,isOriginPotentiallyTrustworthy,isUrlPotentiallyTrustworthy,parseReferrerPolicyFromHeader,stripURLForUseAsAReferrer,validateReferrerPolicy};
@@ -1 +1 @@
1
- import{Readable as e}from"node:stream";import t from"@girs/glib-2.0";import{inputStreamAsyncIterator as n}from"@gjsify/utils";async function soupSendAsync(e,n,r=t.PRIORITY_DEFAULT,i=null){return new Promise((t,a)=>{e.send_async(n,r,i,(n,r)=>{try{t(e.send_finish(r))}catch(e){a(e)}})})}function inputStreamToReadable(t,r={}){return e.from(n(t),r)}export{inputStreamToReadable,soupSendAsync};
1
+ import"../_virtual/_rolldown/runtime.js";import{Readable as e}from"node:stream";import t from"@girs/glib-2.0";import{inputStreamAsyncIterator as n}from"@gjsify/utils";async function soupSendAsync(e,n,r=t.PRIORITY_DEFAULT,i=null){return new Promise((t,a)=>{e.send_async(n,r,i,(n,r)=>{try{t(e.send_finish(r))}catch(e){a(e)}})})}function inputStreamToReadable(t,r={}){return e.from(n(t),r)}export{inputStreamToReadable,soupSendAsync};
package/lib/esm/xhr.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"./index.js";import t from"gi://GLib?version=2.0";let n=0;function guessBlobExt(e){let t=e.toLowerCase().split(`?`)[0],n=t.lastIndexOf(`.`),r=n>-1?t.slice(n):``;switch(r){case`.png`:case`.jpg`:case`.jpeg`:case`.gif`:case`.webp`:case`.svg`:case`.bmp`:case`.ttf`:case`.otf`:case`.woff`:case`.woff2`:case`.mp3`:case`.wav`:case`.ogg`:case`.flac`:case`.m4a`:case`.mp4`:case`.webm`:case`.mkv`:case`.xml`:case`.tmx`:case`.json`:return r;default:return`.bin`}}function writeBlobToTempFile(e,r){let i=t.build_filenamev([t.get_tmp_dir(),`gjsify-blob-${n++}${guessBlobExt(r)}`]);return t.file_set_contents(i,e),i}const r=0,i=1,a=2,o=3,s=4;var XMLHttpRequest=class extends EventTarget{static UNSENT=0;static OPENED=1;static HEADERS_RECEIVED=2;static LOADING=3;static DONE=4;UNSENT=0;OPENED=1;HEADERS_RECEIVED=2;LOADING=3;DONE=4;readyState=0;status=0;statusText=``;responseType=``;responseText=``;response=null;responseURL=``;withCredentials=!1;timeout=0;upload=new XMLHttpRequestUpload;onreadystatechange=null;onload=null;onerror=null;onabort=null;ontimeout=null;onloadstart=null;onloadend=null;onprogress=null;_method=`GET`;_url=``;_headers=new Map;_responseHeaders=new Map;_controller=new AbortController;_aborted=!1;_timeoutId=null;open(e,t,n=!0,r,i){this._method=e.toUpperCase(),this._url=t,this._headers.clear(),this._responseHeaders.clear(),this._aborted=!1,this._controller=new AbortController,this._setReadyState(1)}setRequestHeader(e,t){if(this.readyState<1)throw new DOMException(`Must open first`,`InvalidStateError`);this._headers.set(e.toLowerCase(),t)}getResponseHeader(e){return this._responseHeaders.get(e.toLowerCase())??null}getAllResponseHeaders(){let e=[];return this._responseHeaders.forEach((t,n)=>e.push(`${n}: ${t}`)),e.join(`\r
1
+ import"./_virtual/_rolldown/runtime.js";import e from"./index.js";import t from"gi://GLib?version=2.0";let n=0;function guessBlobExt(e){let t=e.toLowerCase().split(`?`)[0],n=t.lastIndexOf(`.`),r=n>-1?t.slice(n):``;switch(r){case`.png`:case`.jpg`:case`.jpeg`:case`.gif`:case`.webp`:case`.svg`:case`.bmp`:case`.ttf`:case`.otf`:case`.woff`:case`.woff2`:case`.mp3`:case`.wav`:case`.ogg`:case`.flac`:case`.m4a`:case`.mp4`:case`.webm`:case`.mkv`:case`.xml`:case`.tmx`:case`.json`:return r;default:return`.bin`}}function writeBlobToTempFile(e,r){let i=t.build_filenamev([t.get_tmp_dir(),`gjsify-blob-${n++}${guessBlobExt(r)}`]);return t.file_set_contents(i,e),i}const r=0,i=1,a=2,o=3,s=4;var XMLHttpRequest=class extends EventTarget{static UNSENT=0;static OPENED=1;static HEADERS_RECEIVED=2;static LOADING=3;static DONE=4;UNSENT=0;OPENED=1;HEADERS_RECEIVED=2;LOADING=3;DONE=4;readyState=0;status=0;statusText=``;responseType=``;responseText=``;response=null;responseURL=``;withCredentials=!1;timeout=0;upload=new XMLHttpRequestUpload;onreadystatechange=null;onload=null;onerror=null;onabort=null;ontimeout=null;onloadstart=null;onloadend=null;onprogress=null;_method=`GET`;_url=``;_headers=new Map;_responseHeaders=new Map;_controller=new AbortController;_aborted=!1;_timeoutId=null;open(e,t,n=!0,r,i){this._method=e.toUpperCase(),this._url=t,this._headers.clear(),this._responseHeaders.clear(),this._aborted=!1,this._controller=new AbortController,this._setReadyState(1)}setRequestHeader(e,t){if(this.readyState<1)throw new DOMException(`Must open first`,`InvalidStateError`);this._headers.set(e.toLowerCase(),t)}getResponseHeader(e){return this._responseHeaders.get(e.toLowerCase())??null}getAllResponseHeaders(){let e=[];return this._responseHeaders.forEach((t,n)=>e.push(`${n}: ${t}`)),e.join(`\r
2
2
  `)}send(t){if(this.readyState!==1)throw new DOMException(`Must open first`,`InvalidStateError`);if(this._aborted)return;let n={};this._headers.forEach((e,t)=>{n[t]=e});let r={method:this._method,headers:n,credentials:this.withCredentials?`include`:`omit`,signal:this._controller.signal};t!=null&&this._method!==`GET`&&this._method!==`HEAD`&&(r.body=t),this.timeout>0&&(this._timeoutId=setTimeout(()=>{this._controller.abort(),this._onTimeout()},this.timeout)),this.dispatchEvent(new Event(`loadstart`)),this.onloadstart&&this.onloadstart(new ProgressEvent(`loadstart`)),e(this._url,r).then(async e=>{if(!this._aborted){switch(this._timeoutId&&=(clearTimeout(this._timeoutId),null),this.status=e.status,this.statusText=e.statusText,this.responseURL=e.url,e.headers.forEach((e,t)=>{this._responseHeaders.set(t.toLowerCase(),e)}),this._setReadyState(2),this._setReadyState(3),this.responseType){case`arraybuffer`:{let t=await e.arrayBuffer();this.response=t,this.responseText=``;break}case`blob`:{let t=await e.arrayBuffer(),n=writeBlobToTempFile(new Uint8Array(t),this._url),r=new Blob([t],{type:this._responseHeaders.get(`content-type`)??``});r._tmpPath=n,this.response=r,this.responseText=``;break}case`json`:{let t=await e.text();this.responseText=``;try{this.response=t.length>0?JSON.parse(t):null}catch{this.response=null}break}case`document`:{let t=await e.text();this.responseText=t,this.response=t;break}default:{let t=await e.text(),n=t.charCodeAt(0)===65279?t.slice(1):t;this.responseText=n,this.response=n;break}}this._setReadyState(4),this.dispatchEvent(new ProgressEvent(`load`)),this.dispatchEvent(new ProgressEvent(`loadend`)),this.onload&&this.onload(new ProgressEvent(`load`)),this.onloadend&&this.onloadend(new ProgressEvent(`loadend`))}}).catch(e=>{if(this._timeoutId&&=(clearTimeout(this._timeoutId),null),this._aborted)return;this._setReadyState(4);let t=new ProgressEvent(`error`);this.dispatchEvent(t),this.onerror&&this.onerror(t),this.onloadend&&this.onloadend(new ProgressEvent(`loadend`))})}abort(){if(this._aborted)return;this._aborted=!0,this._timeoutId&&=(clearTimeout(this._timeoutId),null),this._controller.abort(),this.readyState!==0&&this.readyState!==4&&(this._setReadyState(4),this.status=0);let e=new ProgressEvent(`abort`);this.dispatchEvent(e),this.onabort&&this.onabort(e),this.onloadend&&this.onloadend(new ProgressEvent(`loadend`))}overrideMimeType(e){}_onTimeout(){if(this._aborted)return;this._aborted=!0,this._setReadyState(4);let e=new ProgressEvent(`timeout`);this.dispatchEvent(e),this.ontimeout&&this.ontimeout(e)}_setReadyState(e){this.readyState=e;let t=new Event(`readystatechange`);this.dispatchEvent(t),this.onreadystatechange&&this.onreadystatechange(t)}},XMLHttpRequestUpload=class extends EventTarget{onprogress=null;onloadstart=null;onloadend=null;onload=null;onerror=null;onabort=null;ontimeout=null};export{s as DONE,a as HEADERS_RECEIVED,o as LOADING,i as OPENED,r as UNSENT,XMLHttpRequest,XMLHttpRequestUpload};
package/package.json CHANGED
@@ -1,63 +1,66 @@
1
1
  {
2
- "name": "@gjsify/fetch",
3
- "version": "0.3.21",
4
- "description": "Web and Node.js fetch module for Gjs",
5
- "module": "lib/esm/index.js",
6
- "types": "lib/index.d.ts",
7
- "type": "module",
8
- "exports": {
9
- ".": {
10
- "types": "./lib/index.d.ts",
11
- "default": "./lib/esm/index.js"
2
+ "name": "@gjsify/fetch",
3
+ "version": "0.4.3",
4
+ "description": "Web and Node.js fetch module for Gjs",
5
+ "module": "lib/esm/index.js",
6
+ "types": "lib/index.d.ts",
7
+ "files": [
8
+ "lib"
9
+ ],
10
+ "type": "module",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./lib/index.d.ts",
14
+ "default": "./lib/esm/index.js"
15
+ },
16
+ "./register": {
17
+ "types": "./lib/register.d.ts",
18
+ "default": "./lib/esm/register.js"
19
+ },
20
+ "./register/fetch": {
21
+ "default": "./lib/esm/register/fetch.js"
22
+ },
23
+ "./register/xhr": {
24
+ "default": "./lib/esm/register/xhr.js"
25
+ }
12
26
  },
13
- "./register": {
14
- "types": "./lib/register.d.ts",
15
- "default": "./lib/esm/register.js"
27
+ "sideEffects": [
28
+ "./lib/esm/register.js",
29
+ "./lib/esm/register/*.js"
30
+ ],
31
+ "scripts": {
32
+ "clear": "rm -rf lib tsconfig.tsbuildinfo tsconfig.types.tsbuildinfo test.gjs.mjs test.node.mjs || exit 0",
33
+ "check": "tsc --noEmit",
34
+ "build": "gjsify run build:gjsify && gjsify run build:types",
35
+ "build:gjsify": "gjsify build --library 'src/**/*.{ts,js}' --exclude 'src/**/*.spec.{mts,ts}' 'src/test.{mts,ts}'",
36
+ "build:types": "tsc",
37
+ "build:test": "gjsify run build:test:gjs && gjsify run build:test:node",
38
+ "build:test:gjs": "gjsify build src/test.mts --app gjs --outfile test.gjs.mjs",
39
+ "build:test:browser": "gjsify build src/test.browser.mts --app browser --outfile dist/test.browser.mjs",
40
+ "build:test:node": "gjsify build src/test.mts --app node --outfile test.node.mjs",
41
+ "test": "gjsify run build:gjsify && gjsify run build:test:node && gjsify run test:node",
42
+ "test:gjs": "gjsify run test.gjs.mjs",
43
+ "test:node": "node test.node.mjs"
16
44
  },
17
- "./register/fetch": {
18
- "default": "./lib/esm/register/fetch.js"
45
+ "keywords": [
46
+ "gjs",
47
+ "node",
48
+ "fetch"
49
+ ],
50
+ "devDependencies": {
51
+ "@gjsify/cli": "workspace:^",
52
+ "@gjsify/unit": "workspace:^",
53
+ "@types/node": "^25.6.2",
54
+ "typescript": "^6.0.3"
19
55
  },
20
- "./register/xhr": {
21
- "default": "./lib/esm/register/xhr.js"
56
+ "dependencies": {
57
+ "@girs/gio-2.0": "2.88.0-4.0.0-rc.15",
58
+ "@girs/gjs": "4.0.0-rc.15",
59
+ "@girs/glib-2.0": "2.88.0-4.0.0-rc.15",
60
+ "@girs/soup-3.0": "3.6.6-4.0.0-rc.15",
61
+ "@gjsify/formdata": "workspace:^",
62
+ "@gjsify/http": "workspace:^",
63
+ "@gjsify/url": "workspace:^",
64
+ "@gjsify/utils": "workspace:^"
22
65
  }
23
- },
24
- "sideEffects": [
25
- "./lib/esm/register.js",
26
- "./lib/esm/register/*.js"
27
- ],
28
- "scripts": {
29
- "clear": "rm -rf lib tsconfig.tsbuildinfo tsconfig.types.tsbuildinfo test.gjs.mjs test.node.mjs || exit 0",
30
- "check": "tsc --noEmit",
31
- "build": "yarn build:gjsify && yarn build:types",
32
- "build:gjsify": "gjsify build --library 'src/**/*.{ts,js}' --exclude 'src/**/*.spec.{mts,ts}' 'src/test.{mts,ts}'",
33
- "build:types": "tsc",
34
- "build:test": "yarn build:test:gjs && yarn build:test:node",
35
- "build:test:gjs": "gjsify build src/test.mts --app gjs --outfile test.gjs.mjs",
36
- "build:test:browser": "gjsify build src/test.browser.mts --app browser --outfile dist/test.browser.mjs",
37
- "build:test:node": "gjsify build src/test.mts --app node --outfile test.node.mjs",
38
- "test": "yarn build:gjsify && yarn build:test:node && yarn test:node",
39
- "test:gjs": "gjsify run test.gjs.mjs",
40
- "test:node": "node test.node.mjs"
41
- },
42
- "keywords": [
43
- "gjs",
44
- "node",
45
- "fetch"
46
- ],
47
- "devDependencies": {
48
- "@gjsify/cli": "^0.3.21",
49
- "@gjsify/unit": "^0.3.21",
50
- "@types/node": "^25.6.2",
51
- "typescript": "^6.0.3"
52
- },
53
- "dependencies": {
54
- "@girs/gio-2.0": "2.88.0-4.0.0-rc.14",
55
- "@girs/gjs": "4.0.0-rc.14",
56
- "@girs/glib-2.0": "2.88.0-4.0.0-rc.14",
57
- "@girs/soup-3.0": "3.6.6-4.0.0-rc.14",
58
- "@gjsify/formdata": "^0.3.21",
59
- "@gjsify/http": "^0.3.21",
60
- "@gjsify/url": "^0.3.21",
61
- "@gjsify/utils": "^0.3.21"
62
- }
63
- }
66
+ }