@ecosy/core 0.3.2 → 0.3.4
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/env.js +1 -1
- package/dist/env.mjs +1 -1
- package/dist/http.d.ts +8 -7
- package/dist/http.js +1 -1
- package/dist/http.mjs +1 -1
- package/dist/serialize.d.ts +1 -1
- package/dist/subscriber.d.ts +1 -1
- package/dist/utilities/freeze.d.ts +1 -1
- package/dist/utilities/is-function.d.ts +1 -1
- package/dist/utilities/object.d.ts +1 -1
- package/package.json +1 -1
package/dist/env.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var e=require("./utilities/object.js");function t(e,n,...i){for(const t of i)if(t&&e in t&&void 0!==t[e])return t[e];const r=t._getter();return e in r&&void 0!==r[e]?r[e]:n}t._getter=function(){if("undefined"!=typeof globalThis&&"process"in globalThis){const t=globalThis.process;if((null==t?void 0:t.env)&&e.isLiteralObject(t.env))return t.env}try{const t=new Function("return import.meta")();if((null==t?void 0:t.env)&&e.isLiteralObject(t.env))return t.env}catch(e){}return{}},t.getter=e=>{t._getter=e},exports.getEnv=t;
|
package/dist/env.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLiteralObject as t}from"./utilities/object.mjs";function e(t,n,...o){for(const e of o)if(e&&t in e&&void 0!==e[t])return e[t];const r=e._getter();return t in r&&void 0!==r[t]?r[t]:n}e._getter=function(){if("undefined"!=typeof globalThis&&"process"in globalThis){const e=globalThis.process;if((null==e?void 0:e.env)&&t(e.env))return e.env}try{const e=import.meta
|
|
1
|
+
import{isLiteralObject as t}from"./utilities/object.mjs";function e(t,n,...o){for(const e of o)if(e&&t in e&&void 0!==e[t])return e[t];const r=e._getter();return t in r&&void 0!==r[t]?r[t]:n}e._getter=function(){if("undefined"!=typeof globalThis&&"process"in globalThis){const e=globalThis.process;if((null==e?void 0:e.env)&&t(e.env))return e.env}try{const e=new Function("return import.meta")();if((null==e?void 0:e.env)&&t(e.env))return e.env}catch(t){}return{}},e.getter=t=>{e._getter=t};export{e as getEnv};
|
package/dist/http.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type FileListLike } from "./utilities/filelist";
|
|
2
|
+
import type { Promisable } from "./types/built-in";
|
|
2
3
|
/** Default base URL for HTTP requests, sourced from `API_URL` env variable. */
|
|
3
4
|
export declare const DEFAULT_BASE_URL: string | undefined;
|
|
4
5
|
/** Authentication token storage key, sourced from `API_AUTH_TOKEN_KEY` env variable. */
|
|
@@ -70,9 +71,9 @@ export interface HttpOptions {
|
|
|
70
71
|
}
|
|
71
72
|
/** Storage adapter interface for reading/writing auth tokens (e.g. `localStorage`). */
|
|
72
73
|
export interface HttpStorage {
|
|
73
|
-
getItem(key: string): string | null
|
|
74
|
-
setItem(key: string, value: string): void
|
|
75
|
-
removeItem(key: string, options?: any): void
|
|
74
|
+
getItem(key: string): Promisable<string | null>;
|
|
75
|
+
setItem(key: string, value: string): Promisable<void>;
|
|
76
|
+
removeItem(key: string, options?: any): Promisable<void>;
|
|
76
77
|
}
|
|
77
78
|
/** Interceptor that can modify a request before it is sent. */
|
|
78
79
|
export type HttpInterceptorRequest = (options: HttpRequest) => Promise<HttpRequest> | HttpRequest;
|
|
@@ -217,14 +218,14 @@ export declare class Http {
|
|
|
217
218
|
/** Remove an instance-level interceptor. */
|
|
218
219
|
off(...params: HttpInterceptorParameters): this;
|
|
219
220
|
/** Read the auth token from storage and format it with the configured header type. */
|
|
220
|
-
getToken(): {
|
|
221
|
+
getToken(): Promise<{
|
|
221
222
|
key: string;
|
|
222
223
|
value: string;
|
|
223
|
-
}
|
|
224
|
+
}>;
|
|
224
225
|
/** Build the final headers object, injecting auth token and Content-Type. */
|
|
225
|
-
getHeaders(headers?: Record<string, string>, isFormData?: boolean): {
|
|
226
|
+
getHeaders(headers?: Record<string, string>, isFormData?: boolean): Promise<{
|
|
226
227
|
[x: string]: string;
|
|
227
|
-
}
|
|
228
|
+
}>;
|
|
228
229
|
/**
|
|
229
230
|
* Build the full URL from base URL, path, query string, and path params.
|
|
230
231
|
*
|
package/dist/http.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var t=require("./utilities/filelist.js"),e=require("./utilities/flatten.js"),r=require("./utilities/formdata.js"),s=require("./utilities/get.js"),o=require("./utilities/sanitize-mime.js"),n=require("./serialize.js"),i=require("./env.js");function a(t){try{return new URL(t).origin}catch(t){return null}}const c=new Set(["__proto__","constructor","prototype"]),d=new Set(["credentials","cache","mode","redirect","referrer","referrerPolicy","integrity","keepalive","priority","duplex","window","next","cf","dispatcher"]);function l(t){const e=Object.create(null);for(const r of Object.keys(t))d.has(r)&&(e[r]=t[r]);return e}function p(t){const e=Object.create(null);for(const r of Object.keys(t))c.has(r)||(e[r]=t[r]);return e}const u=i.getEnv("API_URL","/"),h=i.getEnv("API_AUTH_TOKEN_KEY"),g=i.getEnv("API_AUTH_HEADER_KEY"),f=i.getEnv("API_AUTH_HEADER_TYPE");var y,T;exports.HttpMethod=void 0,(y=exports.HttpMethod||(exports.HttpMethod={})).GET="GET",y.POST="POST",y.PUT="PUT",y.DELETE="DELETE",y.PATCH="PATCH",y.HEAD="HEAD",y.OPTIONS="OPTIONS",exports.HttpUpload=void 0,(T=exports.HttpUpload||(exports.HttpUpload={})).UPLOAD="UPLOAD",T.RELATED="RELATED";class E{static register(t,e){return this.registered[t]=Object.assign({},e),this}static all(){return Object.assign({},this.registered)}}E.registered={};class H{constructor(t){var e,r,s;this.defaultHeaders={"Content-Type":"application/json"},this.method=H.method,this.storage=H.storage,this.interceptors={request:[],response:[],transform:[],error:[]};const o="string"==typeof t||void 0===t?{baseURL:null!=t?t:u}:t;this.baseURL=null!==(r=null!==(e=o.baseURL)&&void 0!==e?e:u)&&void 0!==r?r:"/";const n=new Set;for(const t of null!==(s=o.allowedOrigins)&&void 0!==s?s:[]){const e=a(t);if(!e)throw new Error(`Http: invalid allowedOrigins entry: ${t}`);n.add(e)}const i=a(this.baseURL);i&&n.add(i),this.allowedOrigins=n,this.defaultConfigs=o.configs?l(o.configs):{}}isAllowedOrigin(t){return 0===this.allowedOrigins.size||this.allowedOrigins.has(t)}assertSameOriginResponse(t,e,r){const s=Object.keys(r).some(t=>"authorization"===t.toLowerCase()&&!!r[t]),o=Object.keys(r).some(t=>"cookie"===t.toLowerCase()&&!!r[t]);if(!s&&!o)return;const n=a(t);if(!n)return;const i=e.url?a(e.url):null;if(i&&i!==n&&!this.isAllowedOrigin(i))throw new Error(`Http: credentialed request was redirected from ${n} to untrusted origin ${i}`)}static on(...t){const[e,r]=t,s=H.interceptors[e];s.includes(r)||s.push(r),H.interceptors[e]=s}static off(...t){const[e,r]=t,s=H.interceptors[e];H.interceptors[e]=s.filter(t=>t!==r)}setStorage(t){this.storage=t}isValidQuery(t){return"string"==typeof t||t instanceof URLSearchParams||(Array.isArray(t)?t.every(t=>Array.isArray(t)&&2===t.length&&"string"==typeof t[0]&&n.Serialize.Primitive.isPrimitive(t[1])):"object"==typeof t&&null!==t&&Object.values(t).every(t=>n.Serialize.Primitive.isPrimitive(t)))}getQuery(t){const{method:e,body:r,query:s}=t,o=e===exports.HttpMethod.GET&&this.isValidQuery(r)?r:s;if(!o||"object"!=typeof o)return"string"==typeof o?o:"";if(o instanceof URLSearchParams)return o.toString();const i=p(o);return n.Serialize.queryString.stringify(i,{skipNull:!0,skipEmptyString:!0})}addHeaders(t){this.defaultHeaders=Object.assign(Object.assign({},this.defaultHeaders),t)}on(...t){const[e,r]=t,s=this.interceptors[e];return s.includes(r)||s.push(r),this.interceptors[e]=s,this}off(...t){const[e,r]=t,s=this.interceptors[e];return this.interceptors[e]=s.filter(t=>t!==r),this}getToken(){const t=h||H.authTokenKey,e=g||H.authHeaderKey,r=f||H.authHeaderType;if(!t||!e)return{key:e,value:""};let s="";this.storage&&(s=this.storage.getItem(t)||"");const o={key:e,value:""};return s&&/^[\x21-\x7E]+$/.test(s)&&(o.value=r?`${r} ${s}`:s),o}getHeaders(t={},e){const r=this.getToken();r.key in t&&t[r.key]||(t[r.key]=r.value),e&&"Content-Type"in t?delete t["Content-Type"]:t["Content-Type"]=t["Content-Type"]||this.defaultHeaders["Content-Type"]||"application/json";const s=Object.assign(Object.assign(Object.assign({},this.defaultHeaders),t),H.extraHeaders||{});return H.extraHeaders=null,s}getURL(t){const{url:e="",params:r={}}=t,o=this.getQuery(t);let i;if(e){if(e.startsWith("//"))throw new Error(`Http: protocol-relative URLs are not allowed: ${e}`);if(/^[a-z][a-z0-9+.-]*:/i.test(e)){let t;try{t=new URL(e)}catch(t){throw new Error(`Http: invalid absolute URL: ${e}`)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new Error(`Http: unsupported URL scheme: ${t.protocol}`);if(!this.isAllowedOrigin(t.origin))throw new Error(`Http: URL origin '${t.origin}' is not in allowedOrigins`);i=t.toString()}else{const t=(this.baseURL||"/").replace(/\/+$/,""),r=e.replace(/^\/+/,"");i=t?`${t}/${r}`:`/${r}`}}else i=this.baseURL||"/";if(o){const t=i.includes("?")?"&":"?";i+=`${t}${o}`}if(!i.includes("{")||!i.includes("}"))return i;const a=Array.isArray(r)?r:p(r);return i.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(t,e)=>{const r=s.get(a,e);return null==r||"object"==typeof r?"":n.Serialize.URL.encode(String(r))})}getBody(t){const{method:e,body:s}=t;if(e!==exports.HttpMethod.GET&&e!==exports.HttpMethod.HEAD&&e!==exports.HttpMethod.OPTIONS&&e!==exports.HttpMethod.DELETE)return e!==exports.HttpMethod.POST&&e!==exports.HttpMethod.PUT&&e!==exports.HttpMethod.PATCH||!r.isFormData(s)?s instanceof Uint8Array||s instanceof ArrayBuffer?s:void 0!==s?JSON.stringify(s):void 0:s}async request(t){const{method:e=exports.HttpMethod.GET}=t;try{let s=Object.assign({},t);const o=[...H.interceptors.request,...this.interceptors.request];for(const t of o)s=await t(s);const n=this.getURL(s),i=this.getHeaders(s.headers||{});r.isFormData(s.body)&&"Content-Type"in i&&delete i["Content-Type"];const a=Object.assign(Object.assign({},this.defaultConfigs),s.configs?l(s.configs):{}),c=await fetch(n,Object.assign(Object.assign({},a),{method:s.method||e,headers:i,body:this.getBody(s),signal:s.signal}));this.assertSameOriginResponse(n,c,i);const d=c.headers.get("Content-Type")||"";let p=null;p=d.includes("application/json")?await c.json():await c.text();const u=[...H.interceptors.transform,...this.interceptors.transform];let h=p;for(const t of u)h=await t(h);const g=[...H.interceptors.response,...this.interceptors.response];let f=c;for(const t of g)f=await t(f);const y={};f.headers.forEach((t,e)=>{y[e]=t});const T=f.ok;let E=null;if(!T){E=p.error||p;const t=[...H.interceptors.error,...this.interceptors.error];for(const e of t)E=await e(E)}return{data:h,success:T,error:T?null:E,status:f.status,statusText:f.statusText,headers:y}}catch(t){let e=t instanceof Error?t:new Error(String(t));const r=[...H.interceptors.error,...this.interceptors.error];for(const t of r)e=await t(e);return{data:null,status:0,statusText:"Error",headers:{},error:e,success:!1}}}get(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:exports.HttpMethod.GET,url:t,query:e}))}post(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:exports.HttpMethod.POST,url:t,body:e}))}put(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:exports.HttpMethod.PUT,url:t,body:e}))}patch(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:exports.HttpMethod.PATCH,url:t,body:e}))}delete(t,e){return this.request(Object.assign(Object.assign({},e),{method:exports.HttpMethod.DELETE,url:t}))}head(t,e){return this.request(Object.assign(Object.assign({},e),{method:exports.HttpMethod.HEAD,url:t}))}options(t,e){return this.request(Object.assign(Object.assign({},e),{method:exports.HttpMethod.OPTIONS,url:t}))}upload(s,o,n){const i=(null==n?void 0:n.body)?r.objectToFormData(n.body):new FormData;let a=(null==n?void 0:n.name)||"file";if(Array.isArray(o)?(a.endsWith("[]")&&(a=a.slice(0,-2)),o.forEach((t,e)=>{i.append(`${a}[${e}]`,t,t.name)})):t.isFileList(o)?(a.endsWith("[]")&&(a=a.slice(0,-2)),Array.from(o).forEach((t,e)=>{i.append(`${a}[${e}]`,t,t.name)})):i.append(a,o,o.name),null==n?void 0:n.body){const t=e.flatten(n.body);Object.entries(t).forEach(([t,e])=>{null!=e&&i.append(t,String(e))})}return(null==n?void 0:n.onProgress)&&"undefined"!=typeof XMLHttpRequest?new Promise(async t=>{try{let e=Object.assign(Object.assign({},n),{method:exports.HttpMethod.POST,url:s,body:i});const r=[...H.interceptors.request,...this.interceptors.request];for(const t of r)e=await t(e);const o=this.getURL(e),a=this.getHeaders(e.headers||{},!0),c=new XMLHttpRequest;c.upload.addEventListener("progress",t=>{var e;if(t.lengthComputable){const r=Math.round(t.loaded/t.total*100);null===(e=n.onProgress)||void 0===e||e.call(n,{loaded:t.loaded,total:t.total,percentage:r})}}),c.addEventListener("load",async()=>{try{const e=c.getResponseHeader("Content-Type")||"";let r=null;r=e.includes("application/json")?JSON.parse(c.responseText):c.responseText;const s=[...H.interceptors.transform,...this.interceptors.transform];let o=r;for(const t of s)o=await t(o);const n=[...H.interceptors.response,...this.interceptors.response];let i=new Response(c.responseText,{status:c.status,statusText:c.statusText,headers:a});for(const t of n)i=await t(i);const d={};i.headers.forEach((t,e)=>{d[e]=t});const l=i.ok;t({data:o,success:l,error:l?null:o,status:i.status,statusText:i.statusText,headers:d})}catch(e){const r=[...H.interceptors.error,...this.interceptors.error];for(const t of r)t(e);t({data:null,status:0,statusText:"Error",headers:{},error:e,success:!1})}}),c.addEventListener("error",e=>{const r=[...H.interceptors.error,...this.interceptors.error];for(const t of r)t(e);t({data:null,status:0,statusText:"Error",headers:{},error:e,success:!1})}),c.addEventListener("abort",()=>{t({data:null,status:0,statusText:"Aborted",headers:{},error:null,success:!1})}),c.open(e.method||exports.HttpMethod.POST,o,!0),Object.entries(a).forEach(([t,e])=>{"content-type"!==(null==t?void 0:t.toLowerCase())&&e&&c.setRequestHeader(t,e)}),c.send(e.body)}catch(e){const r=[...H.interceptors.error,...this.interceptors.error];for(const t of r)t(e);t({data:null,status:0,statusText:"Error",headers:{},error:e,success:!1})}}):this.request({method:exports.HttpMethod.POST,url:s,body:i,headers:null==n?void 0:n.headers,params:null==n?void 0:n.params,signal:null==n?void 0:n.signal,query:null==n?void 0:n.query})}related(t,e,r){const s=o.sanitizeMime(r.contentType),n=o.sanitizeMime(r.metadataMimeType||"application/json"),i=`----related-boundary-${Date.now()}-${Math.random().toString(36).slice(2)}`,a=JSON.stringify(r.metadata),c=new TextEncoder,d=c.encode(`--${i}\r\nContent-Type: ${n}; charset=UTF-8\r\n\r\n`+a+"\r\n"),l=c.encode(`--${i}\r\nContent-Type: ${s}\r\nContent-Transfer-Encoding: binary\r\n\r\n`),p=c.encode(`\r\n--${i}--`),u=e instanceof Uint8Array?e:new Uint8Array(e),h=new Uint8Array(d.length+l.length+u.length+p.length);return[d,l,u,p].reduce((t,e)=>(h.set(e,t),t+e.length),0),this.request({method:exports.HttpMethod.POST,url:t,body:h,headers:Object.assign(Object.assign({},r.headers||{}),{"Content-Type":`multipart/related; boundary=${i}`}),params:r.params,signal:r.signal,query:r.query})}static createFactory(t={}){const r=t.http||new H(t.baseURL);return function(s,o){const n=e.flatten("function"==typeof t.endpoint?t.endpoint():t.endpoint||{})[s];return{key:s,fn:async(...e)=>{const s="function"==typeof t.storage?await t.storage():t.storage;switch(s&&r.setStorage(s),o){case exports.HttpMethod.POST:return await r.post(n,...e);case exports.HttpMethod.PUT:return await r.put(n,...e);case exports.HttpMethod.PATCH:return await r.patch(n,...e);case exports.HttpMethod.DELETE:return await r.delete(n,...e);case exports.HttpMethod.HEAD:return await r.head(n,...e);case exports.HttpMethod.OPTIONS:return await r.options(n,...e);case exports.HttpUpload.UPLOAD:return await r.upload(n,...e);case exports.HttpUpload.RELATED:return await r.related(n,...e);default:return await r.get(n,...e)}}}}}}H.method=exports.HttpMethod,H.Endpoint=E,H.authTokenKey="access_token",H.authHeaderKey="Authorization",H.authHeaderType="Bearer",H.authDetectToken=["localStorage","sessionStorage","cookie"],H.extraHeaders=null,H.storage=null,H.interceptors={request:[],response:[],transform:[],error:[]},exports.API_AUTH_HEADER_KEY=g,exports.API_AUTH_HEADER_TYPE=f,exports.API_AUTH_TOKEN_KEY=h,exports.DEFAULT_BASE_URL=u,exports.Endpoint=E,exports.Http=H;
|
|
1
|
+
"use strict";var t=require("./utilities/get.js"),e=require("./env.js"),r=require("./utilities/flatten.js"),s=require("./serialize.js"),o=require("./utilities/sanitize-mime.js"),n=require("./utilities/formdata.js"),i=require("./utilities/filelist.js");function a(t){try{return new URL(t).origin}catch(t){return null}}const c=new Set(["__proto__","constructor","prototype"]),d=new Set(["credentials","cache","mode","redirect","referrer","referrerPolicy","integrity","keepalive","priority","duplex","window","next","cf","dispatcher"]);function l(t){const e=Object.create(null);for(const r of Object.keys(t))d.has(r)&&(e[r]=t[r]);return e}function p(t){const e=Object.create(null);for(const r of Object.keys(t))c.has(r)||(e[r]=t[r]);return e}const u=e.getEnv("API_URL","/"),h=e.getEnv("API_AUTH_TOKEN_KEY"),g=e.getEnv("API_AUTH_HEADER_KEY"),f=e.getEnv("API_AUTH_HEADER_TYPE");var y,T;exports.HttpMethod=void 0,(y=exports.HttpMethod||(exports.HttpMethod={})).GET="GET",y.POST="POST",y.PUT="PUT",y.DELETE="DELETE",y.PATCH="PATCH",y.HEAD="HEAD",y.OPTIONS="OPTIONS",exports.HttpUpload=void 0,(T=exports.HttpUpload||(exports.HttpUpload={})).UPLOAD="UPLOAD",T.RELATED="RELATED";class E{static register(t,e){return this.registered[t]=Object.assign({},e),this}static all(){return Object.assign({},this.registered)}}E.registered={};class H{constructor(t){var e,r,s;this.defaultHeaders={"Content-Type":"application/json"},this.method=H.method,this.storage=H.storage,this.interceptors={request:[],response:[],transform:[],error:[]};const o="string"==typeof t||void 0===t?{baseURL:null!=t?t:u}:t;this.baseURL=null!==(r=null!==(e=o.baseURL)&&void 0!==e?e:u)&&void 0!==r?r:"/";const n=new Set;for(const t of null!==(s=o.allowedOrigins)&&void 0!==s?s:[]){const e=a(t);if(!e)throw new Error(`Http: invalid allowedOrigins entry: ${t}`);n.add(e)}const i=a(this.baseURL);i&&n.add(i),this.allowedOrigins=n,this.defaultConfigs=o.configs?l(o.configs):{}}isAllowedOrigin(t){return 0===this.allowedOrigins.size||this.allowedOrigins.has(t)}assertSameOriginResponse(t,e,r){const s=Object.keys(r).some(t=>"authorization"===t.toLowerCase()&&!!r[t]),o=Object.keys(r).some(t=>"cookie"===t.toLowerCase()&&!!r[t]);if(!s&&!o)return;const n=a(t);if(!n)return;const i=e.url?a(e.url):null;if(i&&i!==n&&!this.isAllowedOrigin(i))throw new Error(`Http: credentialed request was redirected from ${n} to untrusted origin ${i}`)}static on(...t){const[e,r]=t,s=H.interceptors[e];s.includes(r)||s.push(r),H.interceptors[e]=s}static off(...t){const[e,r]=t,s=H.interceptors[e];H.interceptors[e]=s.filter(t=>t!==r)}setStorage(t){this.storage=t}isValidQuery(t){return"string"==typeof t||t instanceof URLSearchParams||(Array.isArray(t)?t.every(t=>Array.isArray(t)&&2===t.length&&"string"==typeof t[0]&&s.Serialize.Primitive.isPrimitive(t[1])):"object"==typeof t&&null!==t&&Object.values(t).every(t=>s.Serialize.Primitive.isPrimitive(t)))}getQuery(t){const{method:e,body:r,query:o}=t,n=e===exports.HttpMethod.GET&&this.isValidQuery(r)?r:o;if(!n||"object"!=typeof n)return"string"==typeof n?n:"";if(n instanceof URLSearchParams)return n.toString();const i=p(n);return s.Serialize.queryString.stringify(i,{skipNull:!0,skipEmptyString:!0})}addHeaders(t){this.defaultHeaders=Object.assign(Object.assign({},this.defaultHeaders),t)}on(...t){const[e,r]=t,s=this.interceptors[e];return s.includes(r)||s.push(r),this.interceptors[e]=s,this}off(...t){const[e,r]=t,s=this.interceptors[e];return this.interceptors[e]=s.filter(t=>t!==r),this}async getToken(){const t=h||H.authTokenKey,e=g||H.authHeaderKey,r=f||H.authHeaderType;if(!t||!e)return{key:e,value:""};let s="";this.storage&&(s=await this.storage.getItem(t)||"");const o={key:e,value:""};return s&&/^[\x21-\x7E]+$/.test(s)&&(o.value=r?`${r} ${s}`:s),o}async getHeaders(t={},e){const r=await this.getToken();r.key in t&&t[r.key]||(t[r.key]=r.value),e&&"Content-Type"in t?delete t["Content-Type"]:t["Content-Type"]=t["Content-Type"]||this.defaultHeaders["Content-Type"]||"application/json";const s=Object.assign(Object.assign(Object.assign({},this.defaultHeaders),t),H.extraHeaders||{});return H.extraHeaders=null,s}getURL(e){const{url:r="",params:o={}}=e,n=this.getQuery(e);let i;if(r){if(r.startsWith("//"))throw new Error(`Http: protocol-relative URLs are not allowed: ${r}`);if(/^[a-z][a-z0-9+.-]*:/i.test(r)){let t;try{t=new URL(r)}catch(t){throw new Error(`Http: invalid absolute URL: ${r}`)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new Error(`Http: unsupported URL scheme: ${t.protocol}`);if(!this.isAllowedOrigin(t.origin))throw new Error(`Http: URL origin '${t.origin}' is not in allowedOrigins`);i=t.toString()}else{const t=(this.baseURL||"/").replace(/\/+$/,""),e=r.replace(/^\/+/,"");i=t?`${t}/${e}`:`/${e}`}}else i=this.baseURL||"/";if(n){const t=i.includes("?")?"&":"?";i+=`${t}${n}`}if(!i.includes("{")||!i.includes("}"))return i;const a=Array.isArray(o)?o:p(o);return i.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(e,r)=>{const o=t.get(a,r);return null==o||"object"==typeof o?"":s.Serialize.URL.encode(String(o))})}getBody(t){const{method:e,body:r}=t;if(e!==exports.HttpMethod.GET&&e!==exports.HttpMethod.HEAD&&e!==exports.HttpMethod.OPTIONS&&e!==exports.HttpMethod.DELETE)return e!==exports.HttpMethod.POST&&e!==exports.HttpMethod.PUT&&e!==exports.HttpMethod.PATCH||!n.isFormData(r)?r instanceof Uint8Array||r instanceof ArrayBuffer?r:void 0!==r?JSON.stringify(r):void 0:r}async request(t){const{method:e=exports.HttpMethod.GET}=t;try{let r=Object.assign({},t);const s=[...H.interceptors.request,...this.interceptors.request];for(const t of s)r=await t(r);const o=this.getURL(r),i=await this.getHeaders(r.headers||{});n.isFormData(r.body)&&"Content-Type"in i&&delete i["Content-Type"];const a=Object.assign(Object.assign({},this.defaultConfigs),r.configs?l(r.configs):{}),c=await fetch(o,Object.assign(Object.assign({},a),{method:r.method||e,headers:i,body:this.getBody(r),signal:r.signal}));this.assertSameOriginResponse(o,c,i);const d=c.headers.get("Content-Type")||"";let p=null;p=d.includes("application/json")?await c.json():await c.text();const u=[...H.interceptors.transform,...this.interceptors.transform];let h=p;for(const t of u)h=await t(h);const g=[...H.interceptors.response,...this.interceptors.response];let f=c;for(const t of g)f=await t(f);const y={};f.headers.forEach((t,e)=>{y[e]=t});const T=f.ok;let E=null;if(!T){E=p.error||p;const t=[...H.interceptors.error,...this.interceptors.error];for(const e of t)E=await e(E)}return{data:h,success:T,error:T?null:E,status:f.status,statusText:f.statusText,headers:y}}catch(t){let e=t instanceof Error?t:new Error(String(t));const r=[...H.interceptors.error,...this.interceptors.error];for(const t of r)e=await t(e);return{data:null,status:0,statusText:"Error",headers:{},error:e,success:!1}}}get(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:exports.HttpMethod.GET,url:t,query:e}))}post(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:exports.HttpMethod.POST,url:t,body:e}))}put(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:exports.HttpMethod.PUT,url:t,body:e}))}patch(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:exports.HttpMethod.PATCH,url:t,body:e}))}delete(t,e){return this.request(Object.assign(Object.assign({},e),{method:exports.HttpMethod.DELETE,url:t}))}head(t,e){return this.request(Object.assign(Object.assign({},e),{method:exports.HttpMethod.HEAD,url:t}))}options(t,e){return this.request(Object.assign(Object.assign({},e),{method:exports.HttpMethod.OPTIONS,url:t}))}upload(t,e,s){const o=(null==s?void 0:s.body)?n.objectToFormData(s.body):new FormData;let a=(null==s?void 0:s.name)||"file";if(Array.isArray(e)?(a.endsWith("[]")&&(a=a.slice(0,-2)),e.forEach((t,e)=>{o.append(`${a}[${e}]`,t,t.name)})):i.isFileList(e)?(a.endsWith("[]")&&(a=a.slice(0,-2)),Array.from(e).forEach((t,e)=>{o.append(`${a}[${e}]`,t,t.name)})):o.append(a,e,e.name),null==s?void 0:s.body){const t=r.flatten(s.body);Object.entries(t).forEach(([t,e])=>{null!=e&&o.append(t,String(e))})}return(null==s?void 0:s.onProgress)&&"undefined"!=typeof XMLHttpRequest?new Promise(async e=>{try{let r=Object.assign(Object.assign({},s),{method:exports.HttpMethod.POST,url:t,body:o});const n=[...H.interceptors.request,...this.interceptors.request];for(const t of n)r=await t(r);const i=this.getURL(r),a=await this.getHeaders(r.headers||{},!0),c=new XMLHttpRequest;c.upload.addEventListener("progress",t=>{var e;if(t.lengthComputable){const r=Math.round(t.loaded/t.total*100);null===(e=s.onProgress)||void 0===e||e.call(s,{loaded:t.loaded,total:t.total,percentage:r})}}),c.addEventListener("load",async()=>{try{const t=c.getResponseHeader("Content-Type")||"";let r=null;r=t.includes("application/json")?JSON.parse(c.responseText):c.responseText;const s=[...H.interceptors.transform,...this.interceptors.transform];let o=r;for(const t of s)o=await t(o);const n=[...H.interceptors.response,...this.interceptors.response];let i=new Response(c.responseText,{status:c.status,statusText:c.statusText,headers:a});for(const t of n)i=await t(i);const d={};i.headers.forEach((t,e)=>{d[e]=t});const l=i.ok;e({data:o,success:l,error:l?null:o,status:i.status,statusText:i.statusText,headers:d})}catch(t){const r=[...H.interceptors.error,...this.interceptors.error];for(const e of r)e(t);e({data:null,status:0,statusText:"Error",headers:{},error:t,success:!1})}}),c.addEventListener("error",t=>{const r=[...H.interceptors.error,...this.interceptors.error];for(const e of r)e(t);e({data:null,status:0,statusText:"Error",headers:{},error:t,success:!1})}),c.addEventListener("abort",()=>{e({data:null,status:0,statusText:"Aborted",headers:{},error:null,success:!1})}),c.open(r.method||exports.HttpMethod.POST,i,!0),Object.entries(a).forEach(([t,e])=>{"content-type"!==(null==t?void 0:t.toLowerCase())&&e&&c.setRequestHeader(t,e)}),c.send(r.body)}catch(t){const r=[...H.interceptors.error,...this.interceptors.error];for(const e of r)e(t);e({data:null,status:0,statusText:"Error",headers:{},error:t,success:!1})}}):this.request({method:exports.HttpMethod.POST,url:t,body:o,headers:null==s?void 0:s.headers,params:null==s?void 0:s.params,signal:null==s?void 0:s.signal,query:null==s?void 0:s.query})}related(t,e,r){const s=o.sanitizeMime(r.contentType),n=o.sanitizeMime(r.metadataMimeType||"application/json"),i=`----related-boundary-${Date.now()}-${Math.random().toString(36).slice(2)}`,a=JSON.stringify(r.metadata),c=new TextEncoder,d=c.encode(`--${i}\r\nContent-Type: ${n}; charset=UTF-8\r\n\r\n`+a+"\r\n"),l=c.encode(`--${i}\r\nContent-Type: ${s}\r\nContent-Transfer-Encoding: binary\r\n\r\n`),p=c.encode(`\r\n--${i}--`),u=e instanceof Uint8Array?e:new Uint8Array(e),h=new Uint8Array(d.length+l.length+u.length+p.length);return[d,l,u,p].reduce((t,e)=>(h.set(e,t),t+e.length),0),this.request({method:exports.HttpMethod.POST,url:t,body:h,headers:Object.assign(Object.assign({},r.headers||{}),{"Content-Type":`multipart/related; boundary=${i}`}),params:r.params,signal:r.signal,query:r.query})}static createFactory(t={}){const e=t.http||new H(t.baseURL);return function(s,o){const n=r.flatten("function"==typeof t.endpoint?t.endpoint():t.endpoint||{})[s];return{key:s,fn:async(...r)=>{const s="function"==typeof t.storage?await t.storage():t.storage;switch(s&&e.setStorage(s),o){case exports.HttpMethod.POST:return await e.post(n,...r);case exports.HttpMethod.PUT:return await e.put(n,...r);case exports.HttpMethod.PATCH:return await e.patch(n,...r);case exports.HttpMethod.DELETE:return await e.delete(n,...r);case exports.HttpMethod.HEAD:return await e.head(n,...r);case exports.HttpMethod.OPTIONS:return await e.options(n,...r);case exports.HttpUpload.UPLOAD:return await e.upload(n,...r);case exports.HttpUpload.RELATED:return await e.related(n,...r);default:return await e.get(n,...r)}}}}}}H.method=exports.HttpMethod,H.Endpoint=E,H.authTokenKey="access_token",H.authHeaderKey="Authorization",H.authHeaderType="Bearer",H.authDetectToken=["localStorage","sessionStorage","cookie"],H.extraHeaders=null,H.storage=null,H.interceptors={request:[],response:[],transform:[],error:[]},exports.API_AUTH_HEADER_KEY=g,exports.API_AUTH_HEADER_TYPE=f,exports.API_AUTH_TOKEN_KEY=h,exports.DEFAULT_BASE_URL=u,exports.Endpoint=E,exports.Http=H;
|
package/dist/http.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isFileList as t}from"./utilities/filelist.mjs";import{flatten as e}from"./utilities/flatten.mjs";import{isFormData as r,objectToFormData as s}from"./utilities/formdata.mjs";import{get as n}from"./utilities/get.mjs";import{sanitizeMime as o}from"./utilities/sanitize-mime.mjs";import{Serialize as i}from"./serialize.mjs";import{getEnv as a}from"./env.mjs";function c(t){try{return new URL(t).origin}catch(t){return null}}const l=new Set(["__proto__","constructor","prototype"]),u=new Set(["credentials","cache","mode","redirect","referrer","referrerPolicy","integrity","keepalive","priority","duplex","window","next","cf","dispatcher"]);function d(t){const e=Object.create(null);for(const r of Object.keys(t))u.has(r)&&(e[r]=t[r]);return e}function p(t){const e=Object.create(null);for(const r of Object.keys(t))l.has(r)||(e[r]=t[r]);return e}const h=a("API_URL","/"),f=a("API_AUTH_TOKEN_KEY"),g=a("API_AUTH_HEADER_KEY"),y=a("API_AUTH_HEADER_TYPE");var m,T;!function(t){t.GET="GET",t.POST="POST",t.PUT="PUT",t.DELETE="DELETE",t.PATCH="PATCH",t.HEAD="HEAD",t.OPTIONS="OPTIONS"}(m||(m={})),function(t){t.UPLOAD="UPLOAD",t.RELATED="RELATED"}(T||(T={}));class O{static register(t,e){return this.registered[t]=Object.assign({},e),this}static all(){return Object.assign({},this.registered)}}O.registered={};class b{constructor(t){var e,r,s;this.defaultHeaders={"Content-Type":"application/json"},this.method=b.method,this.storage=b.storage,this.interceptors={request:[],response:[],transform:[],error:[]};const n="string"==typeof t||void 0===t?{baseURL:null!=t?t:h}:t;this.baseURL=null!==(r=null!==(e=n.baseURL)&&void 0!==e?e:h)&&void 0!==r?r:"/";const o=new Set;for(const t of null!==(s=n.allowedOrigins)&&void 0!==s?s:[]){const e=c(t);if(!e)throw new Error(`Http: invalid allowedOrigins entry: ${t}`);o.add(e)}const i=c(this.baseURL);i&&o.add(i),this.allowedOrigins=o,this.defaultConfigs=n.configs?d(n.configs):{}}isAllowedOrigin(t){return 0===this.allowedOrigins.size||this.allowedOrigins.has(t)}assertSameOriginResponse(t,e,r){const s=Object.keys(r).some(t=>"authorization"===t.toLowerCase()&&!!r[t]),n=Object.keys(r).some(t=>"cookie"===t.toLowerCase()&&!!r[t]);if(!s&&!n)return;const o=c(t);if(!o)return;const i=e.url?c(e.url):null;if(i&&i!==o&&!this.isAllowedOrigin(i))throw new Error(`Http: credentialed request was redirected from ${o} to untrusted origin ${i}`)}static on(...t){const[e,r]=t,s=b.interceptors[e];s.includes(r)||s.push(r),b.interceptors[e]=s}static off(...t){const[e,r]=t,s=b.interceptors[e];b.interceptors[e]=s.filter(t=>t!==r)}setStorage(t){this.storage=t}isValidQuery(t){return"string"==typeof t||t instanceof URLSearchParams||(Array.isArray(t)?t.every(t=>Array.isArray(t)&&2===t.length&&"string"==typeof t[0]&&i.Primitive.isPrimitive(t[1])):"object"==typeof t&&null!==t&&Object.values(t).every(t=>i.Primitive.isPrimitive(t)))}getQuery(t){const{method:e,body:r,query:s}=t,n=e===m.GET&&this.isValidQuery(r)?r:s;if(!n||"object"!=typeof n)return"string"==typeof n?n:"";if(n instanceof URLSearchParams)return n.toString();const o=p(n);return i.queryString.stringify(o,{skipNull:!0,skipEmptyString:!0})}addHeaders(t){this.defaultHeaders=Object.assign(Object.assign({},this.defaultHeaders),t)}on(...t){const[e,r]=t,s=this.interceptors[e];return s.includes(r)||s.push(r),this.interceptors[e]=s,this}off(...t){const[e,r]=t,s=this.interceptors[e];return this.interceptors[e]=s.filter(t=>t!==r),this}getToken(){const t=f||b.authTokenKey,e=g||b.authHeaderKey,r=y||b.authHeaderType;if(!t||!e)return{key:e,value:""};let s="";this.storage&&(s=this.storage.getItem(t)||"");const n={key:e,value:""};return s&&/^[\x21-\x7E]+$/.test(s)&&(n.value=r?`${r} ${s}`:s),n}getHeaders(t={},e){const r=this.getToken();r.key in t&&t[r.key]||(t[r.key]=r.value),e&&"Content-Type"in t?delete t["Content-Type"]:t["Content-Type"]=t["Content-Type"]||this.defaultHeaders["Content-Type"]||"application/json";const s=Object.assign(Object.assign(Object.assign({},this.defaultHeaders),t),b.extraHeaders||{});return b.extraHeaders=null,s}getURL(t){const{url:e="",params:r={}}=t,s=this.getQuery(t);let o;if(e){if(e.startsWith("//"))throw new Error(`Http: protocol-relative URLs are not allowed: ${e}`);if(/^[a-z][a-z0-9+.-]*:/i.test(e)){let t;try{t=new URL(e)}catch(t){throw new Error(`Http: invalid absolute URL: ${e}`)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new Error(`Http: unsupported URL scheme: ${t.protocol}`);if(!this.isAllowedOrigin(t.origin))throw new Error(`Http: URL origin '${t.origin}' is not in allowedOrigins`);o=t.toString()}else{const t=(this.baseURL||"/").replace(/\/+$/,""),r=e.replace(/^\/+/,"");o=t?`${t}/${r}`:`/${r}`}}else o=this.baseURL||"/";if(s){const t=o.includes("?")?"&":"?";o+=`${t}${s}`}if(!o.includes("{")||!o.includes("}"))return o;const a=Array.isArray(r)?r:p(r);return o.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(t,e)=>{const r=n(a,e);return null==r||"object"==typeof r?"":i.URL.encode(String(r))})}getBody(t){const{method:e,body:s}=t;if(e!==m.GET&&e!==m.HEAD&&e!==m.OPTIONS&&e!==m.DELETE)return e!==m.POST&&e!==m.PUT&&e!==m.PATCH||!r(s)?s instanceof Uint8Array||s instanceof ArrayBuffer?s:void 0!==s?JSON.stringify(s):void 0:s}async request(t){const{method:e=m.GET}=t;try{let s=Object.assign({},t);const n=[...b.interceptors.request,...this.interceptors.request];for(const t of n)s=await t(s);const o=this.getURL(s),i=this.getHeaders(s.headers||{});r(s.body)&&"Content-Type"in i&&delete i["Content-Type"];const a=Object.assign(Object.assign({},this.defaultConfigs),s.configs?d(s.configs):{}),c=await fetch(o,Object.assign(Object.assign({},a),{method:s.method||e,headers:i,body:this.getBody(s),signal:s.signal}));this.assertSameOriginResponse(o,c,i);const l=c.headers.get("Content-Type")||"";let u=null;u=l.includes("application/json")?await c.json():await c.text();const p=[...b.interceptors.transform,...this.interceptors.transform];let h=u;for(const t of p)h=await t(h);const f=[...b.interceptors.response,...this.interceptors.response];let g=c;for(const t of f)g=await t(g);const y={};g.headers.forEach((t,e)=>{y[e]=t});const m=g.ok;let T=null;if(!m){T=u.error||u;const t=[...b.interceptors.error,...this.interceptors.error];for(const e of t)T=await e(T)}return{data:h,success:m,error:m?null:T,status:g.status,statusText:g.statusText,headers:y}}catch(t){let e=t instanceof Error?t:new Error(String(t));const r=[...b.interceptors.error,...this.interceptors.error];for(const t of r)e=await t(e);return{data:null,status:0,statusText:"Error",headers:{},error:e,success:!1}}}get(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:m.GET,url:t,query:e}))}post(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:m.POST,url:t,body:e}))}put(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:m.PUT,url:t,body:e}))}patch(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:m.PATCH,url:t,body:e}))}delete(t,e){return this.request(Object.assign(Object.assign({},e),{method:m.DELETE,url:t}))}head(t,e){return this.request(Object.assign(Object.assign({},e),{method:m.HEAD,url:t}))}options(t,e){return this.request(Object.assign(Object.assign({},e),{method:m.OPTIONS,url:t}))}upload(r,n,o){const i=(null==o?void 0:o.body)?s(o.body):new FormData;let a=(null==o?void 0:o.name)||"file";if(Array.isArray(n)?(a.endsWith("[]")&&(a=a.slice(0,-2)),n.forEach((t,e)=>{i.append(`${a}[${e}]`,t,t.name)})):t(n)?(a.endsWith("[]")&&(a=a.slice(0,-2)),Array.from(n).forEach((t,e)=>{i.append(`${a}[${e}]`,t,t.name)})):i.append(a,n,n.name),null==o?void 0:o.body){const t=e(o.body);Object.entries(t).forEach(([t,e])=>{null!=e&&i.append(t,String(e))})}return(null==o?void 0:o.onProgress)&&"undefined"!=typeof XMLHttpRequest?new Promise(async t=>{try{let e=Object.assign(Object.assign({},o),{method:m.POST,url:r,body:i});const s=[...b.interceptors.request,...this.interceptors.request];for(const t of s)e=await t(e);const n=this.getURL(e),a=this.getHeaders(e.headers||{},!0),c=new XMLHttpRequest;c.upload.addEventListener("progress",t=>{var e;if(t.lengthComputable){const r=Math.round(t.loaded/t.total*100);null===(e=o.onProgress)||void 0===e||e.call(o,{loaded:t.loaded,total:t.total,percentage:r})}}),c.addEventListener("load",async()=>{try{const e=c.getResponseHeader("Content-Type")||"";let r=null;r=e.includes("application/json")?JSON.parse(c.responseText):c.responseText;const s=[...b.interceptors.transform,...this.interceptors.transform];let n=r;for(const t of s)n=await t(n);const o=[...b.interceptors.response,...this.interceptors.response];let i=new Response(c.responseText,{status:c.status,statusText:c.statusText,headers:a});for(const t of o)i=await t(i);const l={};i.headers.forEach((t,e)=>{l[e]=t});const u=i.ok;t({data:n,success:u,error:u?null:n,status:i.status,statusText:i.statusText,headers:l})}catch(e){const r=[...b.interceptors.error,...this.interceptors.error];for(const t of r)t(e);t({data:null,status:0,statusText:"Error",headers:{},error:e,success:!1})}}),c.addEventListener("error",e=>{const r=[...b.interceptors.error,...this.interceptors.error];for(const t of r)t(e);t({data:null,status:0,statusText:"Error",headers:{},error:e,success:!1})}),c.addEventListener("abort",()=>{t({data:null,status:0,statusText:"Aborted",headers:{},error:null,success:!1})}),c.open(e.method||m.POST,n,!0),Object.entries(a).forEach(([t,e])=>{"content-type"!==(null==t?void 0:t.toLowerCase())&&e&&c.setRequestHeader(t,e)}),c.send(e.body)}catch(e){const r=[...b.interceptors.error,...this.interceptors.error];for(const t of r)t(e);t({data:null,status:0,statusText:"Error",headers:{},error:e,success:!1})}}):this.request({method:m.POST,url:r,body:i,headers:null==o?void 0:o.headers,params:null==o?void 0:o.params,signal:null==o?void 0:o.signal,query:null==o?void 0:o.query})}related(t,e,r){const s=o(r.contentType),n=o(r.metadataMimeType||"application/json"),i=`----related-boundary-${Date.now()}-${Math.random().toString(36).slice(2)}`,a=JSON.stringify(r.metadata),c=new TextEncoder,l=c.encode(`--${i}\r\nContent-Type: ${n}; charset=UTF-8\r\n\r\n`+a+"\r\n"),u=c.encode(`--${i}\r\nContent-Type: ${s}\r\nContent-Transfer-Encoding: binary\r\n\r\n`),d=c.encode(`\r\n--${i}--`),p=e instanceof Uint8Array?e:new Uint8Array(e),h=new Uint8Array(l.length+u.length+p.length+d.length);return[l,u,p,d].reduce((t,e)=>(h.set(e,t),t+e.length),0),this.request({method:m.POST,url:t,body:h,headers:Object.assign(Object.assign({},r.headers||{}),{"Content-Type":`multipart/related; boundary=${i}`}),params:r.params,signal:r.signal,query:r.query})}static createFactory(t={}){const r=t.http||new b(t.baseURL);return function(s,n){const o=e("function"==typeof t.endpoint?t.endpoint():t.endpoint||{})[s];return{key:s,fn:async(...e)=>{const s="function"==typeof t.storage?await t.storage():t.storage;switch(s&&r.setStorage(s),n){case m.POST:return await r.post(o,...e);case m.PUT:return await r.put(o,...e);case m.PATCH:return await r.patch(o,...e);case m.DELETE:return await r.delete(o,...e);case m.HEAD:return await r.head(o,...e);case m.OPTIONS:return await r.options(o,...e);case T.UPLOAD:return await r.upload(o,...e);case T.RELATED:return await r.related(o,...e);default:return await r.get(o,...e)}}}}}}b.method=m,b.Endpoint=O,b.authTokenKey="access_token",b.authHeaderKey="Authorization",b.authHeaderType="Bearer",b.authDetectToken=["localStorage","sessionStorage","cookie"],b.extraHeaders=null,b.storage=null,b.interceptors={request:[],response:[],transform:[],error:[]};export{g as API_AUTH_HEADER_KEY,y as API_AUTH_HEADER_TYPE,f as API_AUTH_TOKEN_KEY,h as DEFAULT_BASE_URL,O as Endpoint,b as Http,m as HttpMethod,T as HttpUpload};
|
|
1
|
+
import{get as t}from"./utilities/get.mjs";import{getEnv as e}from"./env.mjs";import{flatten as r}from"./utilities/flatten.mjs";import{Serialize as s}from"./serialize.mjs";import{sanitizeMime as n}from"./utilities/sanitize-mime.mjs";import{isFormData as o,objectToFormData as i}from"./utilities/formdata.mjs";import{isFileList as a}from"./utilities/filelist.mjs";function c(t){try{return new URL(t).origin}catch(t){return null}}const l=new Set(["__proto__","constructor","prototype"]),u=new Set(["credentials","cache","mode","redirect","referrer","referrerPolicy","integrity","keepalive","priority","duplex","window","next","cf","dispatcher"]);function d(t){const e=Object.create(null);for(const r of Object.keys(t))u.has(r)&&(e[r]=t[r]);return e}function p(t){const e=Object.create(null);for(const r of Object.keys(t))l.has(r)||(e[r]=t[r]);return e}const h=e("API_URL","/"),f=e("API_AUTH_TOKEN_KEY"),g=e("API_AUTH_HEADER_KEY"),y=e("API_AUTH_HEADER_TYPE");var m,T;!function(t){t.GET="GET",t.POST="POST",t.PUT="PUT",t.DELETE="DELETE",t.PATCH="PATCH",t.HEAD="HEAD",t.OPTIONS="OPTIONS"}(m||(m={})),function(t){t.UPLOAD="UPLOAD",t.RELATED="RELATED"}(T||(T={}));class O{static register(t,e){return this.registered[t]=Object.assign({},e),this}static all(){return Object.assign({},this.registered)}}O.registered={};class b{constructor(t){var e,r,s;this.defaultHeaders={"Content-Type":"application/json"},this.method=b.method,this.storage=b.storage,this.interceptors={request:[],response:[],transform:[],error:[]};const n="string"==typeof t||void 0===t?{baseURL:null!=t?t:h}:t;this.baseURL=null!==(r=null!==(e=n.baseURL)&&void 0!==e?e:h)&&void 0!==r?r:"/";const o=new Set;for(const t of null!==(s=n.allowedOrigins)&&void 0!==s?s:[]){const e=c(t);if(!e)throw new Error(`Http: invalid allowedOrigins entry: ${t}`);o.add(e)}const i=c(this.baseURL);i&&o.add(i),this.allowedOrigins=o,this.defaultConfigs=n.configs?d(n.configs):{}}isAllowedOrigin(t){return 0===this.allowedOrigins.size||this.allowedOrigins.has(t)}assertSameOriginResponse(t,e,r){const s=Object.keys(r).some(t=>"authorization"===t.toLowerCase()&&!!r[t]),n=Object.keys(r).some(t=>"cookie"===t.toLowerCase()&&!!r[t]);if(!s&&!n)return;const o=c(t);if(!o)return;const i=e.url?c(e.url):null;if(i&&i!==o&&!this.isAllowedOrigin(i))throw new Error(`Http: credentialed request was redirected from ${o} to untrusted origin ${i}`)}static on(...t){const[e,r]=t,s=b.interceptors[e];s.includes(r)||s.push(r),b.interceptors[e]=s}static off(...t){const[e,r]=t,s=b.interceptors[e];b.interceptors[e]=s.filter(t=>t!==r)}setStorage(t){this.storage=t}isValidQuery(t){return"string"==typeof t||t instanceof URLSearchParams||(Array.isArray(t)?t.every(t=>Array.isArray(t)&&2===t.length&&"string"==typeof t[0]&&s.Primitive.isPrimitive(t[1])):"object"==typeof t&&null!==t&&Object.values(t).every(t=>s.Primitive.isPrimitive(t)))}getQuery(t){const{method:e,body:r,query:n}=t,o=e===m.GET&&this.isValidQuery(r)?r:n;if(!o||"object"!=typeof o)return"string"==typeof o?o:"";if(o instanceof URLSearchParams)return o.toString();const i=p(o);return s.queryString.stringify(i,{skipNull:!0,skipEmptyString:!0})}addHeaders(t){this.defaultHeaders=Object.assign(Object.assign({},this.defaultHeaders),t)}on(...t){const[e,r]=t,s=this.interceptors[e];return s.includes(r)||s.push(r),this.interceptors[e]=s,this}off(...t){const[e,r]=t,s=this.interceptors[e];return this.interceptors[e]=s.filter(t=>t!==r),this}async getToken(){const t=f||b.authTokenKey,e=g||b.authHeaderKey,r=y||b.authHeaderType;if(!t||!e)return{key:e,value:""};let s="";this.storage&&(s=await this.storage.getItem(t)||"");const n={key:e,value:""};return s&&/^[\x21-\x7E]+$/.test(s)&&(n.value=r?`${r} ${s}`:s),n}async getHeaders(t={},e){const r=await this.getToken();r.key in t&&t[r.key]||(t[r.key]=r.value),e&&"Content-Type"in t?delete t["Content-Type"]:t["Content-Type"]=t["Content-Type"]||this.defaultHeaders["Content-Type"]||"application/json";const s=Object.assign(Object.assign(Object.assign({},this.defaultHeaders),t),b.extraHeaders||{});return b.extraHeaders=null,s}getURL(e){const{url:r="",params:n={}}=e,o=this.getQuery(e);let i;if(r){if(r.startsWith("//"))throw new Error(`Http: protocol-relative URLs are not allowed: ${r}`);if(/^[a-z][a-z0-9+.-]*:/i.test(r)){let t;try{t=new URL(r)}catch(t){throw new Error(`Http: invalid absolute URL: ${r}`)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new Error(`Http: unsupported URL scheme: ${t.protocol}`);if(!this.isAllowedOrigin(t.origin))throw new Error(`Http: URL origin '${t.origin}' is not in allowedOrigins`);i=t.toString()}else{const t=(this.baseURL||"/").replace(/\/+$/,""),e=r.replace(/^\/+/,"");i=t?`${t}/${e}`:`/${e}`}}else i=this.baseURL||"/";if(o){const t=i.includes("?")?"&":"?";i+=`${t}${o}`}if(!i.includes("{")||!i.includes("}"))return i;const a=Array.isArray(n)?n:p(n);return i.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(e,r)=>{const n=t(a,r);return null==n||"object"==typeof n?"":s.URL.encode(String(n))})}getBody(t){const{method:e,body:r}=t;if(e!==m.GET&&e!==m.HEAD&&e!==m.OPTIONS&&e!==m.DELETE)return e!==m.POST&&e!==m.PUT&&e!==m.PATCH||!o(r)?r instanceof Uint8Array||r instanceof ArrayBuffer?r:void 0!==r?JSON.stringify(r):void 0:r}async request(t){const{method:e=m.GET}=t;try{let r=Object.assign({},t);const s=[...b.interceptors.request,...this.interceptors.request];for(const t of s)r=await t(r);const n=this.getURL(r),i=await this.getHeaders(r.headers||{});o(r.body)&&"Content-Type"in i&&delete i["Content-Type"];const a=Object.assign(Object.assign({},this.defaultConfigs),r.configs?d(r.configs):{}),c=await fetch(n,Object.assign(Object.assign({},a),{method:r.method||e,headers:i,body:this.getBody(r),signal:r.signal}));this.assertSameOriginResponse(n,c,i);const l=c.headers.get("Content-Type")||"";let u=null;u=l.includes("application/json")?await c.json():await c.text();const p=[...b.interceptors.transform,...this.interceptors.transform];let h=u;for(const t of p)h=await t(h);const f=[...b.interceptors.response,...this.interceptors.response];let g=c;for(const t of f)g=await t(g);const y={};g.headers.forEach((t,e)=>{y[e]=t});const m=g.ok;let T=null;if(!m){T=u.error||u;const t=[...b.interceptors.error,...this.interceptors.error];for(const e of t)T=await e(T)}return{data:h,success:m,error:m?null:T,status:g.status,statusText:g.statusText,headers:y}}catch(t){let e=t instanceof Error?t:new Error(String(t));const r=[...b.interceptors.error,...this.interceptors.error];for(const t of r)e=await t(e);return{data:null,status:0,statusText:"Error",headers:{},error:e,success:!1}}}get(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:m.GET,url:t,query:e}))}post(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:m.POST,url:t,body:e}))}put(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:m.PUT,url:t,body:e}))}patch(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:m.PATCH,url:t,body:e}))}delete(t,e){return this.request(Object.assign(Object.assign({},e),{method:m.DELETE,url:t}))}head(t,e){return this.request(Object.assign(Object.assign({},e),{method:m.HEAD,url:t}))}options(t,e){return this.request(Object.assign(Object.assign({},e),{method:m.OPTIONS,url:t}))}upload(t,e,s){const n=(null==s?void 0:s.body)?i(s.body):new FormData;let o=(null==s?void 0:s.name)||"file";if(Array.isArray(e)?(o.endsWith("[]")&&(o=o.slice(0,-2)),e.forEach((t,e)=>{n.append(`${o}[${e}]`,t,t.name)})):a(e)?(o.endsWith("[]")&&(o=o.slice(0,-2)),Array.from(e).forEach((t,e)=>{n.append(`${o}[${e}]`,t,t.name)})):n.append(o,e,e.name),null==s?void 0:s.body){const t=r(s.body);Object.entries(t).forEach(([t,e])=>{null!=e&&n.append(t,String(e))})}return(null==s?void 0:s.onProgress)&&"undefined"!=typeof XMLHttpRequest?new Promise(async e=>{try{let r=Object.assign(Object.assign({},s),{method:m.POST,url:t,body:n});const o=[...b.interceptors.request,...this.interceptors.request];for(const t of o)r=await t(r);const i=this.getURL(r),a=await this.getHeaders(r.headers||{},!0),c=new XMLHttpRequest;c.upload.addEventListener("progress",t=>{var e;if(t.lengthComputable){const r=Math.round(t.loaded/t.total*100);null===(e=s.onProgress)||void 0===e||e.call(s,{loaded:t.loaded,total:t.total,percentage:r})}}),c.addEventListener("load",async()=>{try{const t=c.getResponseHeader("Content-Type")||"";let r=null;r=t.includes("application/json")?JSON.parse(c.responseText):c.responseText;const s=[...b.interceptors.transform,...this.interceptors.transform];let n=r;for(const t of s)n=await t(n);const o=[...b.interceptors.response,...this.interceptors.response];let i=new Response(c.responseText,{status:c.status,statusText:c.statusText,headers:a});for(const t of o)i=await t(i);const l={};i.headers.forEach((t,e)=>{l[e]=t});const u=i.ok;e({data:n,success:u,error:u?null:n,status:i.status,statusText:i.statusText,headers:l})}catch(t){const r=[...b.interceptors.error,...this.interceptors.error];for(const e of r)e(t);e({data:null,status:0,statusText:"Error",headers:{},error:t,success:!1})}}),c.addEventListener("error",t=>{const r=[...b.interceptors.error,...this.interceptors.error];for(const e of r)e(t);e({data:null,status:0,statusText:"Error",headers:{},error:t,success:!1})}),c.addEventListener("abort",()=>{e({data:null,status:0,statusText:"Aborted",headers:{},error:null,success:!1})}),c.open(r.method||m.POST,i,!0),Object.entries(a).forEach(([t,e])=>{"content-type"!==(null==t?void 0:t.toLowerCase())&&e&&c.setRequestHeader(t,e)}),c.send(r.body)}catch(t){const r=[...b.interceptors.error,...this.interceptors.error];for(const e of r)e(t);e({data:null,status:0,statusText:"Error",headers:{},error:t,success:!1})}}):this.request({method:m.POST,url:t,body:n,headers:null==s?void 0:s.headers,params:null==s?void 0:s.params,signal:null==s?void 0:s.signal,query:null==s?void 0:s.query})}related(t,e,r){const s=n(r.contentType),o=n(r.metadataMimeType||"application/json"),i=`----related-boundary-${Date.now()}-${Math.random().toString(36).slice(2)}`,a=JSON.stringify(r.metadata),c=new TextEncoder,l=c.encode(`--${i}\r\nContent-Type: ${o}; charset=UTF-8\r\n\r\n`+a+"\r\n"),u=c.encode(`--${i}\r\nContent-Type: ${s}\r\nContent-Transfer-Encoding: binary\r\n\r\n`),d=c.encode(`\r\n--${i}--`),p=e instanceof Uint8Array?e:new Uint8Array(e),h=new Uint8Array(l.length+u.length+p.length+d.length);return[l,u,p,d].reduce((t,e)=>(h.set(e,t),t+e.length),0),this.request({method:m.POST,url:t,body:h,headers:Object.assign(Object.assign({},r.headers||{}),{"Content-Type":`multipart/related; boundary=${i}`}),params:r.params,signal:r.signal,query:r.query})}static createFactory(t={}){const e=t.http||new b(t.baseURL);return function(s,n){const o=r("function"==typeof t.endpoint?t.endpoint():t.endpoint||{})[s];return{key:s,fn:async(...r)=>{const s="function"==typeof t.storage?await t.storage():t.storage;switch(s&&e.setStorage(s),n){case m.POST:return await e.post(o,...r);case m.PUT:return await e.put(o,...r);case m.PATCH:return await e.patch(o,...r);case m.DELETE:return await e.delete(o,...r);case m.HEAD:return await e.head(o,...r);case m.OPTIONS:return await e.options(o,...r);case T.UPLOAD:return await e.upload(o,...r);case T.RELATED:return await e.related(o,...r);default:return await e.get(o,...r)}}}}}}b.method=m,b.Endpoint=O,b.authTokenKey="access_token",b.authHeaderKey="Authorization",b.authHeaderType="Bearer",b.authDetectToken=["localStorage","sessionStorage","cookie"],b.extraHeaders=null,b.storage=null,b.interceptors={request:[],response:[],transform:[],error:[]};export{g as API_AUTH_HEADER_KEY,y as API_AUTH_HEADER_TYPE,f as API_AUTH_TOKEN_KEY,h as DEFAULT_BASE_URL,O as Endpoint,b as Http,m as HttpMethod,T as HttpUpload};
|
package/dist/serialize.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { LiteralObject } from "./types";
|
|
1
|
+
import type { LiteralObject } from "./types/built-in";
|
|
2
2
|
type Primitive = string | number | boolean | null | undefined | symbol | bigint;
|
|
3
3
|
/** Options for {@link Serialize.queryString.stringify}. */
|
|
4
4
|
export interface SerializeQueryOptions {
|
package/dist/subscriber.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Freezable, LiteralObject, PartialLiteral, ToString } from "./types";
|
|
1
|
+
import type { Freezable, LiteralObject, PartialLiteral, ToString } from "./types/built-in";
|
|
2
2
|
export type SubscribeChannel = string;
|
|
3
3
|
export type SubcribeHandler<Payload = never> = [Payload] extends [never] ? () => void : (payload: Payload) => void;
|
|
4
4
|
export interface Shallow {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ecosy/core",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.4",
|
|
4
4
|
"description": "A modular, tree-shakable collection of essential utilities, serialization primitives, and event-driven patterns for modern TypeScript applications",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": {
|