@shipstatic/ship 0.4.7 → 0.4.8
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/browser.d.ts +3 -1
- package/dist/browser.js +13 -13
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +18 -18
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.cts
CHANGED
|
@@ -104,7 +104,7 @@ interface ShipClientOptions {
|
|
|
104
104
|
* Event map for Ship SDK events
|
|
105
105
|
* Core events for observability: request, response, error
|
|
106
106
|
*/
|
|
107
|
-
interface ShipEvents
|
|
107
|
+
interface ShipEvents {
|
|
108
108
|
/** Emitted before each API request */
|
|
109
109
|
request: [url: string, init: RequestInit];
|
|
110
110
|
/** Emitted after successful API response */
|
package/dist/index.d.ts
CHANGED
|
@@ -104,7 +104,7 @@ interface ShipClientOptions {
|
|
|
104
104
|
* Event map for Ship SDK events
|
|
105
105
|
* Core events for observability: request, response, error
|
|
106
106
|
*/
|
|
107
|
-
interface ShipEvents
|
|
107
|
+
interface ShipEvents {
|
|
108
108
|
/** Emitted before each API request */
|
|
109
109
|
request: [url: string, init: RequestInit];
|
|
110
110
|
/** Emitted after successful API response */
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Pe=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var He=Object.prototype.hasOwnProperty;var A=(n,e)=>()=>(n&&(e=n(n=0)),e);var B=(n,e)=>{for(var t in e)Pe(n,t,{get:e[t],enumerable:!0})},Ae=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qe(e))!He.call(n,r)&&r!==t&&Pe(n,r,{get:()=>e[r],enumerable:!(o=Ke(e,r))||o.enumerable});return n},p=(n,e,t)=>(Ae(n,e,"default"),t&&Ae(t,e,"default"));import{ShipError as Ge}from"@shipstatic/types";function L(n){re=n}function F(){if(re===null)throw Ge.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return re}var re,_=A(()=>{"use strict";re=null});function Q(n){se=n}function Ye(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function C(){return se||Ye()}var se,I=A(()=>{"use strict";se=null});var we={};B(we,{loadConfig:()=>O});import{z}from"zod";import{ShipError as pe}from"@shipstatic/types";function Ie(n){try{return We.parse(n)}catch(e){if(e instanceof z.ZodError){let t=e.issues[0],o=t.path.length>0?` at ${t.path.join(".")}`:"";throw pe.config(`Configuration validation failed${o}: ${t.message}`)}throw pe.config("Configuration validation failed")}}async function Je(n){try{if(C()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),o=e(ae,{searchPlaces:[`.${ae}rc`,"package.json",`${t.homedir()}/.${ae}rc`],stopDir:t.homedir()}),r;if(n?r=o.load(n):r=o.search(),r&&r.config)return Ie(r.config)}catch(e){if(e instanceof pe)throw e}return{}}async function O(n){if(C()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await Je(n),o={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Ie(o)}var ae,We,Z=A(()=>{"use strict";I();ae="ship",We=z.object({apiUrl:z.string().url().optional(),apiKey:z.string().optional(),deployToken:z.string().optional()}).strict()});import{ShipError as k}from"@shipstatic/types";async function Ze(n){let e=(await import("spark-md5")).default;return new Promise((t,o)=>{let i=Math.ceil(n.size/2097152),s=0,a=new e.ArrayBuffer,u=new FileReader,S=()=>{let D=s*2097152,c=Math.min(D+2097152,n.size);u.readAsArrayBuffer(n.slice(D,c))};u.onload=D=>{let c=D.target?.result;if(!c){o(k.business("Failed to read file chunk"));return}a.append(c),s++,s<i?S():t({md5:a.end()})},u.onerror=()=>{o(k.business("Failed to calculate MD5: FileReader error"))},S()})}async function et(n){let e=await import("crypto");if(Buffer.isBuffer(n)){let o=e.createHash("md5");return o.update(n),{md5:o.digest("hex")}}let t=await import("fs");return new Promise((o,r)=>{let i=e.createHash("md5"),s=t.createReadStream(n);s.on("error",a=>r(k.business(`Failed to read file for MD5: ${a.message}`))),s.on("data",a=>i.update(a)),s.on("end",()=>o({md5:i.digest("hex")}))})}async function b(n){let e=C();if(e==="browser"){if(!(n instanceof Blob))throw k.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Ze(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw k.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return et(n)}throw k.business("Unknown or unsupported execution environment for MD5 calculation.")}var ee=A(()=>{"use strict";I()});import{isJunk as nt}from"junk";function G(n){return!n||n.length===0?[]:n.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let o=t[t.length-1];if(nt(o))return!1;let r=t.slice(0,-1);for(let i of r)if(te.some(s=>i.toLowerCase()===s.toLowerCase()))return!1;return!0})}var te,me=A(()=>{"use strict";te=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ue(n){if(!n||n.length===0)return"";let e=n.filter(i=>i&&typeof i=="string").map(i=>i.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(i=>i.split("/").filter(Boolean)),o=[],r=Math.min(...t.map(i=>i.length));for(let i=0;i<r;i++){let s=t[0][i];if(t.every(a=>a[i]===s))o.push(s);else break}return o.join("/")}function ne(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var de=A(()=>{"use strict"});function Y(n,e={}){if(e.flatten===!1)return n.map(o=>({path:ne(o),name:he(o)}));let t=ot(n);return n.map(o=>{let r=ne(o);if(t){let i=t.endsWith("/")?t:`${t}/`;r.startsWith(i)&&(r=r.substring(i.length))}return r||(r=he(o)),{path:r,name:he(o)}})}function ot(n){if(!n.length)return"";let t=n.map(i=>ne(i)).map(i=>i.split("/")),o=[],r=Math.min(...t.map(i=>i.length));for(let i=0;i<r-1;i++){let s=t[0][i];if(t.every(a=>a[i]===s))o.push(s);else break}return o.join("/")}function he(n){return n.split(/[/\\]/).pop()||n}var ye=A(()=>{"use strict";de()});var _e={};B(_e,{processFilesForNode:()=>ie});import{ShipError as w}from"@shipstatic/types";import*as v from"fs";import*as E from"path";function Le(n,e=new Set){let t=[],o=v.realpathSync(n);if(e.has(o))return t;e.add(o);let r=v.readdirSync(n);for(let i of r){let s=E.join(n,i),a=v.statSync(s);if(a.isDirectory()){let u=Le(s,e);t.push(...u)}else a.isFile()&&t.push(s)}return t}async function ie(n,e={}){if(C()!=="node")throw w.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(h=>{let y=E.resolve(h);try{return v.statSync(y).isDirectory()?Le(y):[y]}catch{throw w.file(`Path does not exist: ${h}`,h)}}),o=[...new Set(t)],r=G(o);if(r.length===0)return[];let i=n.map(h=>E.resolve(h)),s=Ue(i.map(h=>{try{return v.statSync(h).isDirectory()?h:E.dirname(h)}catch{return E.dirname(h)}})),a=r.map(h=>{if(s&&s.length>0){let y=E.relative(s,h);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return E.basename(h)}),u=Y(a,{flatten:e.pathDetect!==!1}),S=[],D=0,c=F();for(let h=0;h<r.length;h++){let y=r[h],T=u[h].path;try{let R=v.statSync(y);if(R.size===0)continue;if(R.size>c.maxFileSize)throw w.business(`File ${y} is too large. Maximum allowed size is ${c.maxFileSize/(1024*1024)}MB.`);if(D+=R.size,D>c.maxTotalSize)throw w.business(`Total deploy size is too large. Maximum allowed is ${c.maxTotalSize/(1024*1024)}MB.`);let U=v.readFileSync(y),{md5:ze}=await b(U);if(T.includes("\0")||T.includes("/../")||T.startsWith("../")||T.endsWith("/.."))throw w.business(`Security error: Unsafe file path "${T}" for file: ${y}`);S.push({path:T,content:U,size:U.length,md5:ze})}catch(R){if(R instanceof w)throw R;let U=R instanceof Error?R.message:String(R);throw w.file(`Failed to read file "${y}": ${U}`,y)}}if(S.length>c.maxFilesCount)throw w.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return S}var Te=A(()=>{"use strict";I();ee();me();_();ye();de()});var J={};B(J,{ApiHttp:()=>x,DEFAULT_API:()=>ue,ErrorType:()=>ve,FILE_VALIDATION_STATUS:()=>f,JUNK_DIRECTORIES:()=>te,Ship:()=>W,ShipError:()=>Ee,__setTestEnvironment:()=>Q,allValidFilesReady:()=>De,calculateMD5:()=>b,createAccountResource:()=>j,createDeploymentResource:()=>q,createDomainResource:()=>H,createTokenResource:()=>V,default:()=>xe,ensureShipError:()=>Ce,filterJunk:()=>G,formatFileSize:()=>N,getCurrentConfig:()=>F,getENV:()=>C,getValidFiles:()=>oe,loadConfig:()=>O,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>Y,pluralize:()=>fe,processFilesForNode:()=>ie,resolveConfig:()=>$,setPlatformConfig:()=>L,validateFiles:()=>ge});var m={};B(m,{ApiHttp:()=>x,DEFAULT_API:()=>ue,ErrorType:()=>ve,FILE_VALIDATION_STATUS:()=>f,JUNK_DIRECTORIES:()=>te,Ship:()=>W,ShipError:()=>Ee,__setTestEnvironment:()=>Q,allValidFilesReady:()=>De,calculateMD5:()=>b,createAccountResource:()=>j,createDeploymentResource:()=>q,createDomainResource:()=>H,createTokenResource:()=>V,default:()=>xe,ensureShipError:()=>Ce,filterJunk:()=>G,formatFileSize:()=>N,getCurrentConfig:()=>F,getENV:()=>C,getValidFiles:()=>oe,loadConfig:()=>O,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>Y,pluralize:()=>fe,processFilesForNode:()=>ie,resolveConfig:()=>$,setPlatformConfig:()=>L,validateFiles:()=>ge});import{ShipError as P,DEFAULT_API as je}from"@shipstatic/types";var X=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let o=this.handlers.get(e);o&&(o.delete(t),o.size===0&&this.handlers.delete(e))}emit(e,...t){let o=this.handlers.get(e);if(!o)return;let r=Array.from(o);for(let i of r)try{i(...t)}catch(s){o.delete(i),e!=="error"&&setTimeout(()=>{s instanceof Error?this.emit("error",s,String(e)):this.emit("error",new Error(String(s)),String(e))},0)}}transfer(e){this.handlers.forEach((t,o)=>{t.forEach(r=>{e.on(o,r)})})}clear(){this.handlers.clear()}};var d={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Ve=3e4,x=class extends X{constructor(e){super(),this.apiUrl=e.apiUrl||je,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Ve,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,t,o){let r=this.mergeHeaders(t.headers),{signal:i,cleanup:s}=this.createTimeoutSignal(t.signal),a={...t,headers:r,credentials:r.Authorization?void 0:"include",signal:i};this.emit("request",e,a);try{let u=await fetch(e,a);return s(),u.ok||await this.handleResponseError(u,o),this.emit("response",this.safeClone(u),e),{data:await this.parseResponse(this.safeClone(u)),status:u.status}}catch(u){throw s(),this.emit("error",u,e),this.handleFetchError(u,o),u}}async request(e,t,o){let{data:r}=await this.executeRequest(e,t,o);return r}async requestWithStatus(e,t,o){return this.executeRequest(e,t,o)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let t=new AbortController,o=setTimeout(()=>t.abort(),this.timeout);if(e){let r=()=>t.abort();e.addEventListener("abort",r),e.aborted&&t.abort()}return{signal:t.signal,cleanup:()=>clearTimeout(o)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,t){let o={};try{o=e.headers.get("content-type")?.includes("application/json")?await e.json():{message:await e.text()}}catch{o={message:"Failed to parse error response"}}let r=o.message||o.error||`${t} failed`;throw e.status===401?P.authentication(r):P.api(r,e.status,o.code,o)}handleFetchError(e,t){throw e.name==="AbortError"?P.cancelled(`${t} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?P.network(`${t} failed: ${e.message}`,e):e instanceof P?e:P.business(`${t} failed: ${e.message||"Unknown error"}`)}async deploy(e,t={}){if(!e.length)throw P.business("No files to deploy");for(let s of e)if(!s.md5)throw P.file(`MD5 checksum missing for file: ${s.path}`,s.path);let{body:o,headers:r}=await this.createDeployBody(e,t.tags,t.via),i={};return t.deployToken?i.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(i.Authorization=`Bearer ${t.apiKey}`),t.caller&&(i["X-Caller"]=t.caller),this.request(`${t.apiUrl||this.apiUrl}${d.DEPLOYMENTS}`,{method:"POST",body:o,headers:{...r,...i},signal:t.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${d.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${d.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentTags(e,t){return this.request(`${this.apiUrl}${d.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:t})},"Update deployment tags")}async removeDeployment(e){await this.request(`${this.apiUrl}${d.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,t,o){let r={};t&&(r.deployment=t),o!==void 0&&(r.tags=o);let{data:i,status:s}=await this.requestWithStatus(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"Set domain");return{...i,isCreate:s===201}}async listDomains(){return this.request(`${this.apiUrl}${d.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async updateDomainTags(e,t){return this.request(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:t})},"Update domain tags")}async removeDomain(e){await this.request(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async createToken(e,t){let o={};return e!==void 0&&(o.ttl=e),t!==void 0&&(o.tags=t),this.request(`${this.apiUrl}${d.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${d.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${d.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${d.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${d.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${d.PING}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return this.request(`${this.apiUrl}${d.PING}`,{method:"GET"},"Ping")}async checkSPA(e){let t=e.find(s=>s.path==="index.html"||s.path==="/index.html");if(!t||t.size>100*1024)return!1;let o;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))o=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)o=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)o=await t.content.text();else return!1;let r={files:e.map(s=>s.path),index:o};return(await this.request(`${this.apiUrl}${d.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"SPA check")).isSPA}};_();import{ShipError as Oe}from"@shipstatic/types";import{ShipError as le}from"@shipstatic/types";I();import{DEFAULT_API as Xe}from"@shipstatic/types";async function Qe(n){let e=C();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(Z(),we));return t(n)}else return{}}function $(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||Xe,apiKey:n.apiKey!==void 0?n.apiKey:e.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:e.deployToken},o={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(o.apiKey=t.apiKey),t.deployToken!==void 0&&(o.deployToken=t.deployToken),o}function K(n,e){let t={...n};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.caller===void 0&&e.caller!==void 0&&(t.caller=e.caller),t}ee();import{DEPLOYMENT_CONFIG_FILENAME as Fe}from"@shipstatic/types";async function tt(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:o}=await b(t);return{path:Fe,content:t,size:e.length,md5:o}}async function be(n,e,t){if(t.spaDetect===!1||n.some(o=>o.path===Fe))return n;try{if(await e.checkSPA(n)){let r=await tt();return[...n,r]}}catch{}return n}function q(n){let{getApi:e,ensureInit:t,processInput:o,clientDefaults:r,hasAuth:i}=n;return{create:async(s,a={})=>{await t();let u=r?K(a,r):a;if(i&&!i()&&!u.deployToken&&!u.apiKey)throw le.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!o)throw le.config("processInput function is not provided.");let S=e(),D=await o(s,u);return D=await be(D,S,u),S.deploy(D,u)},list:async()=>(await t(),e().listDeployments()),get:async s=>(await t(),e().getDeployment(s)),set:async(s,a)=>(await t(),e().updateDeploymentTags(s,a.tags)),remove:async s=>{await t(),await e().removeDeployment(s)}}}function H(n){let{getApi:e,ensureInit:t}=n;return{set:async(o,r={})=>{await t();let{deployment:i,tags:s}=r;if(i===void 0&&(!s||s.length===0))throw le.validation("Must provide deployment or tags");return i===void 0&&s!==void 0?e().updateDomainTags(o,s):e().setDomain(o,i,s)},list:async()=>(await t(),e().listDomains()),get:async o=>(await t(),e().getDomain(o)),remove:async o=>{await t(),await e().removeDomain(o)},verify:async o=>(await t(),e().verifyDomain(o)),dns:async o=>(await t(),e().getDomainDns(o)),records:async o=>(await t(),e().getDomainRecords(o)),share:async o=>(await t(),e().getDomainShare(o))}}function j(n){let{getApi:e,ensureInit:t}=n;return{get:async()=>(await t(),e().getAccount())}}function V(n){let{getApi:e,ensureInit:t}=n;return{create:async(o={})=>(await t(),e().createToken(o.ttl,o.tags)),list:async()=>(await t(),e().listTokens()),remove:async o=>{await t(),await e().removeToken(o)}}}var M=class{constructor(e={}){this.initPromise=null;this._config=null;this.auth=null;this.clientOptions=e,e.deployToken?this.auth={type:"token",value:e.deployToken}:e.apiKey&&(this.auth={type:"apiKey",value:e.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(e);this.http=new x({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let o={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=q({...o,processInput:(r,i)=>this.processInput(r,i),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=H(o),this._account=j(o),this._tokens=V(o)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=F(),this._config)}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}setDeployToken(e){if(!e||typeof e!="string")throw Oe.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw Oe.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};I();Z();import{ShipError as Re}from"@shipstatic/types";_();import{ShipError as Me}from"@shipstatic/types";import $e from"mime-db";var ce={};for(let n in $e){let e=$e[n];e&&e.extensions&&e.extensions.forEach(t=>{ce[t]||(ce[t]=n)})}function ke(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return ce[e]||"application/octet-stream"}async function Ne(n,e,t){let{FormData:o,File:r}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),s=new o,a=[];for(let c of n){let h=ke(c.path),y;if(Buffer.isBuffer(c.content))y=new r([c.content],c.path,{type:h});else if(typeof Blob<"u"&&c.content instanceof Blob)y=new r([c.content],c.path,{type:h});else throw Me.file(`Unsupported file.content type for Node.js: ${c.path}`,c.path);if(!c.md5)throw Me.file(`File missing md5 checksum: ${c.path}`,c.path);let T=c.path.startsWith("/")?c.path:"/"+c.path;s.append("files[]",y,T),a.push(c.md5)}s.append("checksums",JSON.stringify(a)),e&&e.length>0&&s.append("tags",JSON.stringify(e)),t&&s.append("via",t);let u=new i(s),S=[];for await(let c of u.encode())S.push(Buffer.from(c));let D=Buffer.concat(S);return{body:D.buffer.slice(D.byteOffset,D.byteOffset+D.byteLength),headers:{"Content-Type":u.contentType,"Content-Length":Buffer.byteLength(D).toString()}}}var l={};B(l,{ApiHttp:()=>x,DEFAULT_API:()=>ue,ErrorType:()=>ve,FILE_VALIDATION_STATUS:()=>f,JUNK_DIRECTORIES:()=>te,Ship:()=>M,ShipError:()=>Ee,__setTestEnvironment:()=>Q,allValidFilesReady:()=>De,calculateMD5:()=>b,createAccountResource:()=>j,createDeploymentResource:()=>q,createDomainResource:()=>H,createTokenResource:()=>V,ensureShipError:()=>Ce,filterJunk:()=>G,formatFileSize:()=>N,getENV:()=>C,getValidFiles:()=>oe,loadConfig:()=>Qe,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>Y,pluralize:()=>fe,resolveConfig:()=>$,validateFiles:()=>ge});var g={};p(g,Ht);import*as Ht from"@shipstatic/types";p(l,g);import{DEFAULT_API as ue}from"@shipstatic/types";ee();function fe(n,e,t,o=!0){let r=n===1?e:t;return o?`${n} ${r}`:r}me();ye();I();import{FileValidationStatus as f}from"@shipstatic/types";import Be from"mime-db";var it=new Set(Object.keys(Be)),rt=new Map(Object.entries(Be).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)]));var st=[[/File name cannot|Invalid file name|File name contains|File name uses|traversal/i,"Invalid File Name"],[/File size must be positive/i,"Invalid File Size"],[/MIME type is required/i,"Missing MIME Type"],[/Invalid MIME type/i,"Invalid MIME Type"],[/not allowed/i,"Invalid File Type"],[/extension does not match/i,"Extension Mismatch"],[/Total size/i,"Total Size Exceeded"],[/exceeds limit/i,"File Too Large"]];function at(n,e){if(n===f.PROCESSING_ERROR)return"Processing Error";if(n===f.EMPTY_FILE)return"Empty File";if(!e)return"Validation Failed";for(let[t,o]of st)if(t.test(e))return o;return"Validation Failed"}function N(n,e=1){if(n===0)return"0 Bytes";let t=1024,o=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,r)).toFixed(e))+" "+o[r]}function pt(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,o=n.split("/").pop()||n;return t.test(o)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function lt(n,e){if(n.startsWith("."))return!0;let t=n.toLowerCase().split(".");if(t.length>1&&t[t.length-1]){let o=t[t.length-1],r=rt.get(e);if(r&&!r.has(o))return!1}return!0}function ge(n,e){let t=[],o=[];if(n.length===0){let i="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:i,errors:[i],isClientError:!0}}}if(n.length>e.maxFilesCount){let i=`Number of files (${n.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:n.map(s=>({...s,status:f.VALIDATION_FAILED,statusMessage:i})),validFiles:[],error:{error:"File Count Exceeded",details:i,errors:[i],isClientError:!0}}}let r=0;for(let i of n){let s=f.READY,a="Ready for upload",u=i.name?pt(i.name):{valid:!1,reason:"File name cannot be empty"};i.status===f.PROCESSING_ERROR?(s=f.PROCESSING_ERROR,a=i.statusMessage||"A file failed during processing.",t.push(`${i.name}: ${a}`)):!i.name||i.name.trim().length===0?(s=f.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${i.name||"(empty)"}: ${a}`)):i.name.includes("\0")?(s=f.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push(`${i.name}: ${a}`)):u.valid?i.size<=0?(s=f.EMPTY_FILE,a=i.size===0?"File is empty (0 bytes)":"File size must be positive",t.push(`${i.name}: ${a}`)):!i.type||i.type.trim().length===0?(s=f.VALIDATION_FAILED,a="File MIME type is required",t.push(`${i.name}: ${a}`)):e.allowedMimeTypes.some(S=>i.type.startsWith(S))?it.has(i.type)?lt(i.name,i.type)?i.size>e.maxFileSize?(s=f.VALIDATION_FAILED,a=`File size (${N(i.size)}) exceeds limit of ${N(e.maxFileSize)}`,t.push(`${i.name}: ${a}`)):(r+=i.size,r>e.maxTotalSize&&(s=f.VALIDATION_FAILED,a=`Total size would exceed limit of ${N(e.maxTotalSize)}`,t.push(`${i.name}: ${a}`))):(s=f.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${i.name}: ${a}`)):(s=f.VALIDATION_FAILED,a=`Invalid MIME type "${i.type}"`,t.push(`${i.name}: ${a}`)):(s=f.VALIDATION_FAILED,a=`File type "${i.type}" is not allowed`,t.push(`${i.name}: ${a}`)):(s=f.VALIDATION_FAILED,a=u.reason||"Invalid file name",t.push(`${i.name}: ${a}`)),o.push({...i,status:s,statusMessage:a})}if(t.length>0){let i=o.find(a=>a.status!==f.READY&&a.status!==f.PENDING),s=at(i?.status,i?.statusMessage);return{files:o.map(a=>({...a,status:f.VALIDATION_FAILED})),validFiles:[],error:{error:s,details:t.length===1?t[0]:`${t.length} file(s) failed validation`,errors:t,isClientError:!0}}}return{files:o,validFiles:o,error:null}}function oe(n){return n.filter(e=>e.status===f.READY)}function De(n){return oe(n).length>0}import{ShipError as Se}from"@shipstatic/types";function Ce(n){return n instanceof Se?n:n instanceof Error?Se.business(n.message):Se.business(String(n??"Unknown error"))}import{ShipError as Ee,ErrorType as ve}from"@shipstatic/types";p(m,l);Z();_();Te();I();var W=class extends M{constructor(e={}){if(C()!=="node")throw Re.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return $(e,{})}async loadFullConfig(){try{let e=await O(this.clientOptions.configFile),t=$(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let o=new x({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(o);let r=await this.http.getConfig();L(r)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){let o=typeof e=="string"?[e]:e;if(!Array.isArray(o)||!o.every(i=>typeof i=="string"))throw Re.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw Re.business("No files to deploy.");let{processFilesForNode:r}=await Promise.resolve().then(()=>(Te(),_e));return r(o,t)}getDeployBodyCreator(){return Ne}},xe=W;p(J,m);export{x as ApiHttp,ue as DEFAULT_API,ve as ErrorType,f as FILE_VALIDATION_STATUS,te as JUNK_DIRECTORIES,W as Ship,Ee as ShipError,Q as __setTestEnvironment,De as allValidFilesReady,b as calculateMD5,j as createAccountResource,q as createDeploymentResource,H as createDomainResource,V as createTokenResource,xe as default,Ce as ensureShipError,G as filterJunk,N as formatFileSize,F as getCurrentConfig,C as getENV,oe as getValidFiles,O as loadConfig,K as mergeDeployOptions,Y as optimizeDeployPaths,fe as pluralize,ie as processFilesForNode,$ as resolveConfig,L as setPlatformConfig,ge as validateFiles};
|
|
1
|
+
var Pe=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var He=Object.prototype.hasOwnProperty;var P=(o,e)=>()=>(o&&(e=o(o=0)),e);var B=(o,e)=>{for(var t in e)Pe(o,t,{get:e[t],enumerable:!0})},xe=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qe(e))!He.call(o,r)&&r!==t&&Pe(o,r,{get:()=>e[r],enumerable:!(n=Ke(e,r))||n.enumerable});return o},p=(o,e,t)=>(xe(o,e,"default"),t&&xe(t,e,"default"));import{ShipError as Ge}from"@shipstatic/types";function L(o){re=o}function F(){if(re===null)throw Ge.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return re}var re,_=P(()=>{"use strict";re=null});function Q(o){se=o}function Ye(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function E(){return se||Ye()}var se,I=P(()=>{"use strict";se=null});var we={};B(we,{loadConfig:()=>O});import{z}from"zod";import{ShipError as pe}from"@shipstatic/types";function Ie(o){try{return We.parse(o)}catch(e){if(e instanceof z.ZodError){let t=e.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw pe.config(`Configuration validation failed${n}: ${t.message}`)}throw pe.config("Configuration validation failed")}}async function Je(o){try{if(E()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),n=e(ae,{searchPlaces:[`.${ae}rc`,"package.json",`${t.homedir()}/.${ae}rc`],stopDir:t.homedir()}),r;if(o?r=n.load(o):r=n.search(),r&&r.config)return Ie(r.config)}catch(e){if(e instanceof pe)throw e}return{}}async function O(o){if(E()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await Je(o),n={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Ie(n)}var ae,We,Z=P(()=>{"use strict";I();ae="ship",We=z.object({apiUrl:z.string().url().optional(),apiKey:z.string().optional(),deployToken:z.string().optional()}).strict()});import{ShipError as k}from"@shipstatic/types";async function Ze(o){let e=(await import("spark-md5")).default;return new Promise((t,n)=>{let i=Math.ceil(o.size/2097152),s=0,a=new e.ArrayBuffer,c=new FileReader,D=()=>{let S=s*2097152,u=Math.min(S+2097152,o.size);c.readAsArrayBuffer(o.slice(S,u))};c.onload=S=>{let u=S.target?.result;if(!u){n(k.business("Failed to read file chunk"));return}a.append(u),s++,s<i?D():t({md5:a.end()})},c.onerror=()=>{n(k.business("Failed to calculate MD5: FileReader error"))},D()})}async function et(o){let e=await import("crypto");if(Buffer.isBuffer(o)){let n=e.createHash("md5");return n.update(o),{md5:n.digest("hex")}}let t=await import("fs");return new Promise((n,r)=>{let i=e.createHash("md5"),s=t.createReadStream(o);s.on("error",a=>r(k.business(`Failed to read file for MD5: ${a.message}`))),s.on("data",a=>i.update(a)),s.on("end",()=>n({md5:i.digest("hex")}))})}async function b(o){let e=E();if(e==="browser"){if(!(o instanceof Blob))throw k.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Ze(o)}if(e==="node"){if(!(Buffer.isBuffer(o)||typeof o=="string"))throw k.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return et(o)}throw k.business("Unknown or unsupported execution environment for MD5 calculation.")}var ee=P(()=>{"use strict";I()});import{isJunk as nt}from"junk";function G(o){return!o||o.length===0?[]:o.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let n=t[t.length-1];if(nt(n))return!1;let r=t.slice(0,-1);for(let i of r)if(te.some(s=>i.toLowerCase()===s.toLowerCase()))return!1;return!0})}var te,me=P(()=>{"use strict";te=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ue(o){if(!o||o.length===0)return"";let e=o.filter(i=>i&&typeof i=="string").map(i=>i.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(i=>i.split("/").filter(Boolean)),n=[],r=Math.min(...t.map(i=>i.length));for(let i=0;i<r;i++){let s=t[0][i];if(t.every(a=>a[i]===s))n.push(s);else break}return n.join("/")}function ne(o){return o.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var de=P(()=>{"use strict"});function Y(o,e={}){if(e.flatten===!1)return o.map(n=>({path:ne(n),name:he(n)}));let t=ot(o);return o.map(n=>{let r=ne(n);if(t){let i=t.endsWith("/")?t:`${t}/`;r.startsWith(i)&&(r=r.substring(i.length))}return r||(r=he(n)),{path:r,name:he(n)}})}function ot(o){if(!o.length)return"";let t=o.map(i=>ne(i)).map(i=>i.split("/")),n=[],r=Math.min(...t.map(i=>i.length));for(let i=0;i<r-1;i++){let s=t[0][i];if(t.every(a=>a[i]===s))n.push(s);else break}return n.join("/")}function he(o){return o.split(/[/\\]/).pop()||o}var ye=P(()=>{"use strict";de()});var _e={};B(_e,{processFilesForNode:()=>ie});import{ShipError as w}from"@shipstatic/types";import*as v from"fs";import*as C from"path";function Le(o,e=new Set){let t=[],n=v.realpathSync(o);if(e.has(n))return t;e.add(n);let r=v.readdirSync(o);for(let i of r){let s=C.join(o,i),a=v.statSync(s);if(a.isDirectory()){let c=Le(s,e);t.push(...c)}else a.isFile()&&t.push(s)}return t}async function ie(o,e={}){if(E()!=="node")throw w.business("processFilesForNode can only be called in Node.js environment.");let t=o.flatMap(h=>{let y=C.resolve(h);try{return v.statSync(y).isDirectory()?Le(y):[y]}catch{throw w.file(`Path does not exist: ${h}`,h)}}),n=[...new Set(t)],r=G(n);if(r.length===0)return[];let i=o.map(h=>C.resolve(h)),s=Ue(i.map(h=>{try{return v.statSync(h).isDirectory()?h:C.dirname(h)}catch{return C.dirname(h)}})),a=r.map(h=>{if(s&&s.length>0){let y=C.relative(s,h);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return C.basename(h)}),c=Y(a,{flatten:e.pathDetect!==!1}),D=[],S=0,u=F();for(let h=0;h<r.length;h++){let y=r[h],T=c[h].path;try{let R=v.statSync(y);if(R.size===0)continue;if(R.size>u.maxFileSize)throw w.business(`File ${y} is too large. Maximum allowed size is ${u.maxFileSize/(1024*1024)}MB.`);if(S+=R.size,S>u.maxTotalSize)throw w.business(`Total deploy size is too large. Maximum allowed is ${u.maxTotalSize/(1024*1024)}MB.`);let U=v.readFileSync(y),{md5:ze}=await b(U);if(T.includes("\0")||T.includes("/../")||T.startsWith("../")||T.endsWith("/.."))throw w.business(`Security error: Unsafe file path "${T}" for file: ${y}`);D.push({path:T,content:U,size:U.length,md5:ze})}catch(R){if(R instanceof w)throw R;let U=R instanceof Error?R.message:String(R);throw w.file(`Failed to read file "${y}": ${U}`,y)}}if(D.length>u.maxFilesCount)throw w.business(`Too many files to deploy. Maximum allowed is ${u.maxFilesCount} files.`);return D}var Te=P(()=>{"use strict";I();ee();me();_();ye();de()});var J={};B(J,{ApiHttp:()=>x,DEFAULT_API:()=>ue,ErrorType:()=>ve,FILE_VALIDATION_STATUS:()=>f,JUNK_DIRECTORIES:()=>te,Ship:()=>W,ShipError:()=>Ce,__setTestEnvironment:()=>Q,allValidFilesReady:()=>De,calculateMD5:()=>b,createAccountResource:()=>j,createDeploymentResource:()=>q,createDomainResource:()=>H,createTokenResource:()=>V,default:()=>Ae,ensureShipError:()=>Ee,filterJunk:()=>G,formatFileSize:()=>N,getCurrentConfig:()=>F,getENV:()=>E,getValidFiles:()=>oe,loadConfig:()=>O,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>Y,pluralize:()=>fe,processFilesForNode:()=>ie,resolveConfig:()=>$,setPlatformConfig:()=>L,validateFiles:()=>ge});var m={};B(m,{ApiHttp:()=>x,DEFAULT_API:()=>ue,ErrorType:()=>ve,FILE_VALIDATION_STATUS:()=>f,JUNK_DIRECTORIES:()=>te,Ship:()=>W,ShipError:()=>Ce,__setTestEnvironment:()=>Q,allValidFilesReady:()=>De,calculateMD5:()=>b,createAccountResource:()=>j,createDeploymentResource:()=>q,createDomainResource:()=>H,createTokenResource:()=>V,default:()=>Ae,ensureShipError:()=>Ee,filterJunk:()=>G,formatFileSize:()=>N,getCurrentConfig:()=>F,getENV:()=>E,getValidFiles:()=>oe,loadConfig:()=>O,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>Y,pluralize:()=>fe,processFilesForNode:()=>ie,resolveConfig:()=>$,setPlatformConfig:()=>L,validateFiles:()=>ge});import{ShipError as A,DEFAULT_API as je}from"@shipstatic/types";var X=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let n=this.handlers.get(e);n&&(n.delete(t),n.size===0&&this.handlers.delete(e))}emit(e,...t){let n=this.handlers.get(e);if(!n)return;let r=Array.from(n);for(let i of r)try{i(...t)}catch(s){n.delete(i),e!=="error"&&setTimeout(()=>{s instanceof Error?this.emit("error",s,String(e)):this.emit("error",new Error(String(s)),String(e))},0)}}transfer(e){this.handlers.forEach((t,n)=>{t.forEach(r=>{e.on(n,r)})})}clear(){this.handlers.clear()}};var d={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Ve=3e4,x=class extends X{constructor(e){super(),this.apiUrl=e.apiUrl||je,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Ve,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,t,n){let r=this.mergeHeaders(t.headers),{signal:i,cleanup:s}=this.createTimeoutSignal(t.signal),a={...t,headers:r,credentials:r.Authorization?void 0:"include",signal:i};this.emit("request",e,a);try{let c=await fetch(e,a);return s(),c.ok||await this.handleResponseError(c,n),this.emit("response",this.safeClone(c),e),{data:await this.parseResponse(this.safeClone(c)),status:c.status}}catch(c){s();let D=c instanceof Error?c:new Error(String(c));this.emit("error",D,e),this.handleFetchError(c,n)}}async request(e,t,n){let{data:r}=await this.executeRequest(e,t,n);return r}async requestWithStatus(e,t,n){return this.executeRequest(e,t,n)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.timeout);if(e){let r=()=>t.abort();e.addEventListener("abort",r),e.aborted&&t.abort()}return{signal:t.signal,cleanup:()=>clearTimeout(n)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,t){let n={};try{if(e.headers.get("content-type")?.includes("application/json")){let s=await e.json();if(s&&typeof s=="object"){let a=s;typeof a.message=="string"&&(n.message=a.message),typeof a.error=="string"&&(n.error=a.error),typeof a.code=="string"&&(n.code=a.code)}}else n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let r=n.message||n.error||`${t} failed`;throw e.status===401?A.authentication(r):A.api(r,e.status,n.code,n)}handleFetchError(e,t){throw e instanceof A?e:e instanceof Error&&e.name==="AbortError"?A.cancelled(`${t} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?A.network(`${t} failed: ${e.message}`,e):e instanceof Error?A.business(`${t} failed: ${e.message}`):A.business(`${t} failed: Unknown error`)}async deploy(e,t={}){if(!e.length)throw A.business("No files to deploy");for(let s of e)if(!s.md5)throw A.file(`MD5 checksum missing for file: ${s.path}`,s.path);let{body:n,headers:r}=await this.createDeployBody(e,t.tags,t.via),i={};return t.deployToken?i.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(i.Authorization=`Bearer ${t.apiKey}`),t.caller&&(i["X-Caller"]=t.caller),this.request(`${t.apiUrl||this.apiUrl}${d.DEPLOYMENTS}`,{method:"POST",body:n,headers:{...r,...i},signal:t.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${d.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${d.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentTags(e,t){return this.request(`${this.apiUrl}${d.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:t})},"Update deployment tags")}async removeDeployment(e){await this.request(`${this.apiUrl}${d.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,t,n){let r={};t&&(r.deployment=t),n!==void 0&&(r.tags=n);let{data:i,status:s}=await this.requestWithStatus(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"Set domain");return{...i,isCreate:s===201}}async listDomains(){return this.request(`${this.apiUrl}${d.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async updateDomainTags(e,t){return this.request(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:t})},"Update domain tags")}async removeDomain(e){await this.request(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${d.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async createToken(e,t){let n={};return e!==void 0&&(n.ttl=e),t!==void 0&&(n.tags=t),this.request(`${this.apiUrl}${d.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${d.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${d.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${d.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${d.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${d.PING}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return this.request(`${this.apiUrl}${d.PING}`,{method:"GET"},"Ping")}async checkSPA(e){let t=e.find(s=>s.path==="index.html"||s.path==="/index.html");if(!t||t.size>100*1024)return!1;let n;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))n=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)n=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)n=await t.content.text();else return!1;let r={files:e.map(s=>s.path),index:n};return(await this.request(`${this.apiUrl}${d.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"SPA check")).isSPA}};_();import{ShipError as Oe}from"@shipstatic/types";import{ShipError as le}from"@shipstatic/types";I();import{DEFAULT_API as Xe}from"@shipstatic/types";async function Qe(o){let e=E();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(Z(),we));return t(o)}else return{}}function $(o={},e={}){let t={apiUrl:o.apiUrl||e.apiUrl||Xe,apiKey:o.apiKey!==void 0?o.apiKey:e.apiKey,deployToken:o.deployToken!==void 0?o.deployToken:e.deployToken},n={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(n.apiKey=t.apiKey),t.deployToken!==void 0&&(n.deployToken=t.deployToken),n}function K(o,e){let t={...o};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.caller===void 0&&e.caller!==void 0&&(t.caller=e.caller),t}ee();import{DEPLOYMENT_CONFIG_FILENAME as Fe}from"@shipstatic/types";async function tt(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await b(t);return{path:Fe,content:t,size:e.length,md5:n}}async function be(o,e,t){if(t.spaDetect===!1||o.some(n=>n.path===Fe))return o;try{if(await e.checkSPA(o)){let r=await tt();return[...o,r]}}catch{}return o}function q(o){let{getApi:e,ensureInit:t,processInput:n,clientDefaults:r,hasAuth:i}=o;return{create:async(s,a={})=>{await t();let c=r?K(a,r):a;if(i&&!i()&&!c.deployToken&&!c.apiKey)throw le.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw le.config("processInput function is not provided.");let D=e(),S=await n(s,c);return S=await be(S,D,c),D.deploy(S,c)},list:async()=>(await t(),e().listDeployments()),get:async s=>(await t(),e().getDeployment(s)),set:async(s,a)=>(await t(),e().updateDeploymentTags(s,a.tags)),remove:async s=>{await t(),await e().removeDeployment(s)}}}function H(o){let{getApi:e,ensureInit:t}=o;return{set:async(n,r={})=>{await t();let{deployment:i,tags:s}=r;if(i===void 0&&(!s||s.length===0))throw le.validation("Must provide deployment or tags");return i===void 0&&s!==void 0?e().updateDomainTags(n,s):e().setDomain(n,i,s)},list:async()=>(await t(),e().listDomains()),get:async n=>(await t(),e().getDomain(n)),remove:async n=>{await t(),await e().removeDomain(n)},verify:async n=>(await t(),e().verifyDomain(n)),dns:async n=>(await t(),e().getDomainDns(n)),records:async n=>(await t(),e().getDomainRecords(n)),share:async n=>(await t(),e().getDomainShare(n))}}function j(o){let{getApi:e,ensureInit:t}=o;return{get:async()=>(await t(),e().getAccount())}}function V(o){let{getApi:e,ensureInit:t}=o;return{create:async(n={})=>(await t(),e().createToken(n.ttl,n.tags)),list:async()=>(await t(),e().listTokens()),remove:async n=>{await t(),await e().removeToken(n)}}}var M=class{constructor(e={}){this.initPromise=null;this._config=null;this.auth=null;this.clientOptions=e,e.deployToken?this.auth={type:"token",value:e.deployToken}:e.apiKey&&(this.auth={type:"apiKey",value:e.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(e);this.http=new x({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=q({...n,processInput:(r,i)=>this.processInput(r,i),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=H(n),this._account=j(n),this._tokens=V(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=F(),this._config)}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}setDeployToken(e){if(!e||typeof e!="string")throw Oe.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw Oe.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};I();Z();import{ShipError as Re}from"@shipstatic/types";_();import{ShipError as Me}from"@shipstatic/types";import $e from"mime-db";var ce={};for(let o in $e){let e=$e[o];e&&e.extensions&&e.extensions.forEach(t=>{ce[t]||(ce[t]=o)})}function ke(o){let e=o.includes(".")?o.substring(o.lastIndexOf(".")+1).toLowerCase():"";return ce[e]||"application/octet-stream"}async function Ne(o,e,t){let{FormData:n,File:r}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),s=new n,a=[];for(let u of o){let h=ke(u.path),y;if(Buffer.isBuffer(u.content))y=new r([u.content],u.path,{type:h});else if(typeof Blob<"u"&&u.content instanceof Blob)y=new r([u.content],u.path,{type:h});else throw Me.file(`Unsupported file.content type for Node.js: ${u.path}`,u.path);if(!u.md5)throw Me.file(`File missing md5 checksum: ${u.path}`,u.path);let T=u.path.startsWith("/")?u.path:"/"+u.path;s.append("files[]",y,T),a.push(u.md5)}s.append("checksums",JSON.stringify(a)),e&&e.length>0&&s.append("tags",JSON.stringify(e)),t&&s.append("via",t);let c=new i(s),D=[];for await(let u of c.encode())D.push(Buffer.from(u));let S=Buffer.concat(D);return{body:S.buffer.slice(S.byteOffset,S.byteOffset+S.byteLength),headers:{"Content-Type":c.contentType,"Content-Length":Buffer.byteLength(S).toString()}}}var l={};B(l,{ApiHttp:()=>x,DEFAULT_API:()=>ue,ErrorType:()=>ve,FILE_VALIDATION_STATUS:()=>f,JUNK_DIRECTORIES:()=>te,Ship:()=>M,ShipError:()=>Ce,__setTestEnvironment:()=>Q,allValidFilesReady:()=>De,calculateMD5:()=>b,createAccountResource:()=>j,createDeploymentResource:()=>q,createDomainResource:()=>H,createTokenResource:()=>V,ensureShipError:()=>Ee,filterJunk:()=>G,formatFileSize:()=>N,getENV:()=>E,getValidFiles:()=>oe,loadConfig:()=>Qe,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>Y,pluralize:()=>fe,resolveConfig:()=>$,validateFiles:()=>ge});var g={};p(g,jt);import*as jt from"@shipstatic/types";p(l,g);import{DEFAULT_API as ue}from"@shipstatic/types";ee();function fe(o,e,t,n=!0){let r=o===1?e:t;return n?`${o} ${r}`:r}me();ye();I();import{FileValidationStatus as f}from"@shipstatic/types";import it from"mime-db";var Be=it,rt=new Set(Object.keys(Be)),st=new Map(Object.entries(Be).filter(([o,e])=>e.extensions).map(([o,e])=>[o,new Set(e.extensions)]));var at=[[/File name cannot|Invalid file name|File name contains|File name uses|traversal/i,"Invalid File Name"],[/File size must be positive/i,"Invalid File Size"],[/MIME type is required/i,"Missing MIME Type"],[/Invalid MIME type/i,"Invalid MIME Type"],[/not allowed/i,"Invalid File Type"],[/extension does not match/i,"Extension Mismatch"],[/Total size/i,"Total Size Exceeded"],[/exceeds limit/i,"File Too Large"]];function pt(o,e){if(o===f.PROCESSING_ERROR)return"Processing Error";if(o===f.EMPTY_FILE)return"Empty File";if(!e)return"Validation Failed";for(let[t,n]of at)if(t.test(e))return n;return"Validation Failed"}function N(o,e=1){if(o===0)return"0 Bytes";let t=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(o)/Math.log(t));return parseFloat((o/Math.pow(t,r)).toFixed(e))+" "+n[r]}function lt(o){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(o))return{valid:!1,reason:"File name contains unsafe characters"};if(o.startsWith(" ")||o.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(o.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,n=o.split("/").pop()||o;return t.test(n)?{valid:!1,reason:"File name uses a reserved system name"}:o.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function ct(o,e){if(o.startsWith("."))return!0;let t=o.toLowerCase().split(".");if(t.length>1&&t[t.length-1]){let n=t[t.length-1],r=st.get(e);if(r&&!r.has(n))return!1}return!0}function ge(o,e){let t=[],n=[];if(o.length===0){let i="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:i,errors:[i],isClientError:!0}}}if(o.length>e.maxFilesCount){let i=`Number of files (${o.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:o.map(s=>({...s,status:f.VALIDATION_FAILED,statusMessage:i})),validFiles:[],error:{error:"File Count Exceeded",details:i,errors:[i],isClientError:!0}}}let r=0;for(let i of o){let s=f.READY,a="Ready for upload",c=i.name?lt(i.name):{valid:!1,reason:"File name cannot be empty"};i.status===f.PROCESSING_ERROR?(s=f.PROCESSING_ERROR,a=i.statusMessage||"A file failed during processing.",t.push(`${i.name}: ${a}`)):!i.name||i.name.trim().length===0?(s=f.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${i.name||"(empty)"}: ${a}`)):i.name.includes("\0")?(s=f.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push(`${i.name}: ${a}`)):c.valid?i.size<=0?(s=f.EMPTY_FILE,a=i.size===0?"File is empty (0 bytes)":"File size must be positive",t.push(`${i.name}: ${a}`)):!i.type||i.type.trim().length===0?(s=f.VALIDATION_FAILED,a="File MIME type is required",t.push(`${i.name}: ${a}`)):e.allowedMimeTypes.some(D=>i.type.startsWith(D))?rt.has(i.type)?ct(i.name,i.type)?i.size>e.maxFileSize?(s=f.VALIDATION_FAILED,a=`File size (${N(i.size)}) exceeds limit of ${N(e.maxFileSize)}`,t.push(`${i.name}: ${a}`)):(r+=i.size,r>e.maxTotalSize&&(s=f.VALIDATION_FAILED,a=`Total size would exceed limit of ${N(e.maxTotalSize)}`,t.push(`${i.name}: ${a}`))):(s=f.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${i.name}: ${a}`)):(s=f.VALIDATION_FAILED,a=`Invalid MIME type "${i.type}"`,t.push(`${i.name}: ${a}`)):(s=f.VALIDATION_FAILED,a=`File type "${i.type}" is not allowed`,t.push(`${i.name}: ${a}`)):(s=f.VALIDATION_FAILED,a=c.reason||"Invalid file name",t.push(`${i.name}: ${a}`)),n.push({...i,status:s,statusMessage:a})}if(t.length>0){let i=n.find(a=>a.status!==f.READY&&a.status!==f.PENDING),s=pt(i?.status,i?.statusMessage);return{files:n.map(a=>({...a,status:f.VALIDATION_FAILED})),validFiles:[],error:{error:s,details:t.length===1?t[0]:`${t.length} file(s) failed validation`,errors:t,isClientError:!0}}}return{files:n,validFiles:n,error:null}}function oe(o){return o.filter(e=>e.status===f.READY)}function De(o){return oe(o).length>0}import{ShipError as Se}from"@shipstatic/types";function Ee(o){return o instanceof Se?o:o instanceof Error?Se.business(o.message):Se.business(String(o??"Unknown error"))}import{ShipError as Ce,ErrorType as ve}from"@shipstatic/types";p(m,l);Z();_();Te();I();var W=class extends M{constructor(e={}){if(E()!=="node")throw Re.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return $(e,{})}async loadFullConfig(){try{let e=await O(this.clientOptions.configFile),t=$(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let n=new x({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let r=await this.http.getConfig();L(r)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){let n=typeof e=="string"?[e]:e;if(!Array.isArray(n)||!n.every(i=>typeof i=="string"))throw Re.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw Re.business("No files to deploy.");let{processFilesForNode:r}=await Promise.resolve().then(()=>(Te(),_e));return r(n,t)}getDeployBodyCreator(){return Ne}},Ae=W;p(J,m);export{x as ApiHttp,ue as DEFAULT_API,ve as ErrorType,f as FILE_VALIDATION_STATUS,te as JUNK_DIRECTORIES,W as Ship,Ce as ShipError,Q as __setTestEnvironment,De as allValidFilesReady,b as calculateMD5,j as createAccountResource,q as createDeploymentResource,H as createDomainResource,V as createTokenResource,Ae as default,Ee as ensureShipError,G as filterJunk,N as formatFileSize,F as getCurrentConfig,E as getENV,oe as getValidFiles,O as loadConfig,K as mergeDeployOptions,Y as optimizeDeployPaths,fe as pluralize,ie as processFilesForNode,$ as resolveConfig,L as setPlatformConfig,ge as validateFiles};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|