@shipstatic/ship 0.3.15 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var We=Object.create;var ee=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var Xe=Object.getPrototypeOf,Qe=Object.prototype.hasOwnProperty;var P=(n,e)=>()=>(n&&(e=n(n=0)),e);var z=(n,e)=>{for(var t in e)ee(n,t,{get:e[t],enumerable:!0})},Z=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Je(e))!Qe.call(n,r)&&r!==t&&ee(n,r,{get:()=>e[r],enumerable:!(o=Ye(e,r))||o.enumerable});return n},p=(n,e,t)=>(Z(n,e,"default"),t&&Z(t,e,"default")),E=(n,e,t)=>(t=n!=null?We(Xe(n)):{},Z(e||!n||!n.__esModule?ee(t,"default",{value:n,enumerable:!0}):t,n)),Ze=n=>Z(ee({},"__esModule",{value:!0}),n);function K(n){he=n}function k(){if(he===null)throw Me.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return he}var Me,he,q=P(()=>{"use strict";Me=require("@shipstatic/types"),he=null});function oe(n){ye=n}function it(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function C(){return ye||it()}var ye,I=P(()=>{"use strict";ye=null});var _e={};z(_e,{loadConfig:()=>M});function Be(n){try{return rt.parse(n)}catch(e){if(e instanceof N.z.ZodError){let t=e.issues[0],o=t.path.length>0?` at ${t.path.join(".")}`:"";throw ie.ShipError.config(`Configuration validation failed${o}: ${t.message}`)}throw ie.ShipError.config("Configuration validation failed")}}async function st(n){try{if(C()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),o=e(ge,{searchPlaces:[`.${ge}rc`,"package.json",`${t.homedir()}/.${ge}rc`],stopDir:t.homedir()}),r;if(n?r=o.load(n):r=o.search(),r&&r.config)return Be(r.config)}catch(e){if(e instanceof ie.ShipError)throw e}return{}}async function M(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 st(n),o={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Be(o)}var N,ie,ge,rt,re=P(()=>{"use strict";N=require("zod"),ie=require("@shipstatic/types");I();ge="ship",rt=N.z.object({apiUrl:N.z.string().url().optional(),apiKey:N.z.string().optional(),deployToken:N.z.string().optional()}).strict()});async function pt(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,f=new FileReader,c=()=>{let y=s*2097152,l=Math.min(y+2097152,n.size);f.readAsArrayBuffer(n.slice(y,l))};f.onload=y=>{let l=y.target?.result;if(!l){o(O.ShipError.business("Failed to read file chunk"));return}a.append(l),s++,s<i?c():t({md5:a.end()})},f.onerror=()=>{o(O.ShipError.business("Failed to calculate MD5: FileReader error"))},c()})}async function lt(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(O.ShipError.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 $(n){let e=C();if(e==="browser"){if(!(n instanceof Blob))throw O.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return pt(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw O.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return lt(n)}throw O.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var O,se=P(()=>{"use strict";I();O=require("@shipstatic/types")});function Y(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((0,qe.isJunk)(o))return!1;let r=t.slice(0,-1);for(let i of r)if(pe.some(s=>i.toLowerCase()===s.toLowerCase()))return!1;return!0})}var qe,pe,xe=P(()=>{"use strict";qe=require("junk"),pe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function He(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 le(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var we=P(()=>{"use strict"});function J(n,e={}){if(e.flatten===!1)return n.map(o=>({path:le(o),name:Ae(o)}));let t=ut(n);return n.map(o=>{let r=le(o);if(t){let i=t.endsWith("/")?t:`${t}/`;r.startsWith(i)&&(r=r.substring(i.length))}return r||(r=Ae(o)),{path:r,name:Ae(o)}})}function ut(n){if(!n.length)return"";let t=n.map(i=>le(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 Ae(n){return n.split(/[/\\]/).pop()||n}var Pe=P(()=>{"use strict";we()});var je={};z(je,{processFilesForNode:()=>fe});function Ve(n,e=new Set){let t=[],o=T.realpathSync(n);if(e.has(o))return t;e.add(o);let r=T.readdirSync(n);for(let i of r){let s=v.join(n,i),a=T.statSync(s);if(a.isDirectory()){let f=Ve(s,e);t.push(...f)}else a.isFile()&&t.push(s)}return t}async function fe(n,e={}){if(C()!=="node")throw A.ShipError.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(h=>{let g=v.resolve(h);try{return T.statSync(g).isDirectory()?Ve(g):[g]}catch{throw A.ShipError.file(`Path does not exist: ${h}`,h)}}),o=[...new Set(t)],r=Y(o);if(r.length===0)return[];let i=n.map(h=>v.resolve(h)),s=He(i.map(h=>{try{return T.statSync(h).isDirectory()?h:v.dirname(h)}catch{return v.dirname(h)}})),a=r.map(h=>{if(s&&s.length>0){let g=v.relative(s,h);if(g&&typeof g=="string"&&!g.startsWith(".."))return g.replace(/\\/g,"/")}return v.basename(h)}),f=J(a,{flatten:e.pathDetect!==!1}),c=[],y=0,l=k();for(let h=0;h<r.length;h++){let g=r[h],R=f[h].path;try{let x=T.statSync(g);if(x.size===0)continue;if(x.size>l.maxFileSize)throw A.ShipError.business(`File ${g} is too large. Maximum allowed size is ${l.maxFileSize/(1024*1024)}MB.`);if(y+=x.size,y>l.maxTotalSize)throw A.ShipError.business(`Total deploy size is too large. Maximum allowed is ${l.maxTotalSize/(1024*1024)}MB.`);let U=T.readFileSync(g),{md5:Ge}=await $(U);if(R.includes("\0")||R.includes("/../")||R.startsWith("../")||R.endsWith("/.."))throw A.ShipError.business(`Security error: Unsafe file path "${R}" for file: ${g}`);c.push({path:R,content:U,size:U.length,md5:Ge})}catch(x){if(x instanceof A.ShipError)throw x;let U=x instanceof Error?x.message:String(x);throw A.ShipError.file(`Failed to read file "${g}": ${U}`,g)}}if(c.length>l.maxFilesCount)throw A.ShipError.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return c}var A,T,v,Oe=P(()=>{"use strict";I();se();xe();A=require("@shipstatic/types");q();Pe();we();T=E(require("fs"),1),v=E(require("path"),1)});var Q={};z(Q,{ApiHttp:()=>w,DEFAULT_API:()=>ae.DEFAULT_API,ErrorType:()=>b.ErrorType,FILE_VALIDATION_STATUS:()=>m.FileValidationStatus,JUNK_DIRECTORIES:()=>pe,Ship:()=>X,ShipError:()=>b.ShipError,__setTestEnvironment:()=>oe,allValidFilesReady:()=>be,calculateMD5:()=>$,createAccountResource:()=>G,createDeploymentResource:()=>V,createDomainResource:()=>j,createTokenResource:()=>W,default:()=>$e,ensureShipError:()=>ke,filterJunk:()=>Y,formatFileSize:()=>L,getCurrentConfig:()=>k,getENV:()=>C,getValidFiles:()=>ce,loadConfig:()=>M,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>J,pluralize:()=>Re,processFilesForNode:()=>fe,resolveConfig:()=>B,setPlatformConfig:()=>K,validateFiles:()=>Ie});module.exports=Ze(Q);var d={};z(d,{ApiHttp:()=>w,DEFAULT_API:()=>ae.DEFAULT_API,ErrorType:()=>b.ErrorType,FILE_VALIDATION_STATUS:()=>m.FileValidationStatus,JUNK_DIRECTORIES:()=>pe,Ship:()=>X,ShipError:()=>b.ShipError,__setTestEnvironment:()=>oe,allValidFilesReady:()=>be,calculateMD5:()=>$,createAccountResource:()=>G,createDeploymentResource:()=>V,createDomainResource:()=>j,createTokenResource:()=>W,default:()=>$e,ensureShipError:()=>ke,filterJunk:()=>Y,formatFileSize:()=>L,getCurrentConfig:()=>k,getENV:()=>C,getValidFiles:()=>ce,loadConfig:()=>M,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>J,pluralize:()=>Re,processFilesForNode:()=>fe,resolveConfig:()=>B,setPlatformConfig:()=>K,validateFiles:()=>Ie});var S=require("@shipstatic/types");var te=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 ne="/deployments",Ne="/ping",F="/domains",et="/config",tt="/account",de="/tokens",nt="/spa-check",ot=3e4,w=class extends te{constructor(e){super(),this.apiUrl=e.apiUrl||S.DEFAULT_API,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??ot,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async request(e,t={},o){let r=this.getAuthHeaders(t.headers),i=new AbortController,s=setTimeout(()=>i.abort(),this.timeout),a=t.signal?this.combineSignals(t.signal,i.signal):i.signal,f={...t,headers:r,credentials:r.Authorization?void 0:"include",signal:a};this.emit("request",e,f);try{let c=await fetch(e,f);clearTimeout(s),c.ok||await this.handleResponseError(c,o);let y=this.safeClone(c),l=this.safeClone(c);return this.emit("response",y,e),await this.parseResponse(l)}catch(c){throw clearTimeout(s),this.emit("error",c,e),this.handleFetchError(c,o),c}}combineSignals(e,t){let o=new AbortController,r=()=>o.abort();return e.addEventListener("abort",r),t.addEventListener("abort",r),(e.aborted||t.aborted)&&o.abort(),o.signal}async requestWithStatus(e,t={},o){let r=this.getAuthHeaders(t.headers),i=new AbortController,s=setTimeout(()=>i.abort(),this.timeout),a=t.signal?this.combineSignals(t.signal,i.signal):i.signal,f={...t,headers:r,credentials:r.Authorization?void 0:"include",signal:a};this.emit("request",e,f);try{let c=await fetch(e,f);clearTimeout(s),c.ok||await this.handleResponseError(c,o);let y=this.safeClone(c),l=this.safeClone(c);return this.emit("response",y,e),{data:await this.parseResponse(l),status:c.status}}catch(c){throw clearTimeout(s),this.emit("error",c,e),this.handleFetchError(c,o),c}}getAuthHeaders(e={}){let t=this.getAuthHeadersCallback();return{...e,...t}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return await e.json()}async handleResponseError(e,t){let o={};try{e.headers.get("content-type")?.includes("application/json")?o=await e.json():o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}let r=o.message||o.error||`${t} failed due to API error`;throw e.status===401?S.ShipError.authentication(r):S.ShipError.api(r,e.status,o.code,o)}handleFetchError(e,t){throw e.name==="AbortError"?S.ShipError.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?S.ShipError.network(`${t} failed due to network error: ${e.message}`,e):e instanceof S.ShipError?e:S.ShipError.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${Ne}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${Ne}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${et}`,{method:"GET"},"Config")}async deploy(e,t={}){if(!e.length)throw S.ShipError.business("No files to deploy.");for(let a of e)if(!a.md5)throw S.ShipError.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:o,headers:r}=await this.createDeployBody(e,t.tags,t.via),i={};t.deployToken?i.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(i.Authorization=`Bearer ${t.apiKey}`),t.caller&&(i["X-Caller"]=t.caller);let s={method:"POST",body:o,headers:{...r,...i},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${ne}`,s,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${ne}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${ne}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${ne}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,t,o){let r={};t&&(r.deployment=t),o&&o.length>0&&(r.tags=o);let i=`${this.apiUrl}${F}/${encodeURIComponent(e)}`,{data:s,status:a}=await this.requestWithStatus(i,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"Set Domain");return{...s,isCreate:a===201}}async getDomain(e){return await this.request(`${this.apiUrl}${F}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${F}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${F}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async verifyDomain(e){return await this.request(`${this.apiUrl}${F}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${F}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${F}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${F}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${tt}`,{method:"GET"},"Get Account")}async createToken(e,t){let o={};return e!==void 0&&(o.ttl=e),t&&t.length>0&&(o.tags=t),await this.request(`${this.apiUrl}${de}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${de}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${de}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}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}${nt}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"SPA Check")).isSPA}};var ve=require("@shipstatic/types");q();var Ce=require("@shipstatic/types");var Le=require("@shipstatic/types");I();async function at(n){let e=C();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(re(),_e));return t(n)}else return{}}function B(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||Le.DEFAULT_API,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 H(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}var De=require("@shipstatic/types");se();async function ct(){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 $(t);return{path:De.DEPLOYMENT_CONFIG_FILENAME,content:t,size:e.length,md5:o}}async function Ue(n,e,t){if(t.spaDetect===!1||n.some(o=>o.path===De.DEPLOYMENT_CONFIG_FILENAME))return n;try{if(await e.checkSPA(n)){let r=await ct();return[...n,r]}}catch{}return n}function V(n){let{getApi:e,ensureInit:t,processInput:o,clientDefaults:r,hasAuth:i}=n;return{create:async(s,a={})=>{await t();let f=r?H(a,r):a;if(i&&!i()&&!f.deployToken&&!f.apiKey)throw Ce.ShipError.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!o)throw Ce.ShipError.config("processInput function is not provided.");let c=e(),y=await o(s,f);return y=await Ue(y,c,f),c.deploy(y,f)},list:async()=>(await t(),e().listDeployments()),remove:async s=>{await t(),await e().removeDeployment(s)},get:async s=>(await t(),e().getDeployment(s))}}function j(n){let{getApi:e,ensureInit:t}=n;return{set:async(o,r,i)=>(await t(),e().setDomain(o,r,i)),get:async o=>(await t(),e().getDomain(o)),list:async()=>(await t(),e().listDomains()),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 G(n){let{getApi:e,ensureInit:t}=n;return{get:async()=>(await t(),e().getAccount())}}function W(n){let{getApi:e,ensureInit:t}=n;return{create:async(o,r)=>(await t(),e().createToken(o,r)),list:async()=>(await t(),e().listTokens()),remove:async o=>{await t(),await e().removeToken(o)}}}var _=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 w({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let o={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=V({...o,processInput:(r,i)=>this.processInput(r,i),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=j(o),this._account=G(o),this._tokens=W(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=k(),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 ve.ShipError.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 ve.ShipError.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}};var me=require("@shipstatic/types");I();re();q();var Te=require("@shipstatic/types");var Ee=E(require("mime-db"),1),Se={};for(let n in Ee.default){let e=Ee.default[n];e&&e.extensions&&e.extensions.forEach(t=>{Se[t]||(Se[t]=n)})}function ze(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return Se[e]||"application/octet-stream"}async function Ke(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 l of n){let h=ze(l.path),g;if(Buffer.isBuffer(l.content))g=new r([l.content],l.path,{type:h});else if(typeof Blob<"u"&&l.content instanceof Blob)g=new r([l.content],l.path,{type:h});else throw Te.ShipError.file(`Unsupported file.content type for Node.js: ${l.path}`,l.path);if(!l.md5)throw Te.ShipError.file(`File missing md5 checksum: ${l.path}`,l.path);let R=l.path.startsWith("/")?l.path:"/"+l.path;s.append("files[]",g,R),a.push(l.md5)}s.append("checksums",JSON.stringify(a)),e&&e.length>0&&s.append("tags",JSON.stringify(e)),t&&s.append("via",t);let f=new i(s),c=[];for await(let l of f.encode())c.push(Buffer.from(l));let y=Buffer.concat(c);return{body:y.buffer.slice(y.byteOffset,y.byteOffset+y.byteLength),headers:{"Content-Type":f.contentType,"Content-Length":Buffer.byteLength(y).toString()}}}var u={};z(u,{ApiHttp:()=>w,DEFAULT_API:()=>ae.DEFAULT_API,ErrorType:()=>b.ErrorType,FILE_VALIDATION_STATUS:()=>m.FileValidationStatus,JUNK_DIRECTORIES:()=>pe,Ship:()=>_,ShipError:()=>b.ShipError,__setTestEnvironment:()=>oe,allValidFilesReady:()=>be,calculateMD5:()=>$,createAccountResource:()=>G,createDeploymentResource:()=>V,createDomainResource:()=>j,createTokenResource:()=>W,ensureShipError:()=>ke,filterJunk:()=>Y,formatFileSize:()=>L,getENV:()=>C,getValidFiles:()=>ce,loadConfig:()=>at,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>J,pluralize:()=>Re,resolveConfig:()=>B,validateFiles:()=>Ie});var D={};p(D,require("@shipstatic/types"));p(u,D);var ae=require("@shipstatic/types");se();function Re(n,e,t,o=!0){let r=n===1?e:t;return o?`${n} ${r}`:r}xe();Pe();I();var m=require("@shipstatic/types"),Fe=E(require("mime-db"),1),ft=new Set(Object.keys(Fe.default)),mt=new Map(Object.entries(Fe.default).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)]));var dt=[[/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 ht(n,e){if(n===m.FileValidationStatus.PROCESSING_ERROR)return"Processing Error";if(n===m.FileValidationStatus.EMPTY_FILE)return"Empty File";if(!e)return"Validation Failed";for(let[t,o]of dt)if(t.test(e))return o;return"Validation Failed"}function L(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 yt(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 gt(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=mt.get(e);if(r&&!r.has(o))return!1}return!0}function Ie(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:m.FileValidationStatus.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=m.FileValidationStatus.READY,a="Ready for upload",f=i.name?yt(i.name):{valid:!1,reason:"File name cannot be empty"};i.status===m.FileValidationStatus.PROCESSING_ERROR?(s=m.FileValidationStatus.PROCESSING_ERROR,a=i.statusMessage||"A file failed during processing.",t.push(`${i.name}: ${a}`)):!i.name||i.name.trim().length===0?(s=m.FileValidationStatus.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${i.name||"(empty)"}: ${a}`)):i.name.includes("\0")?(s=m.FileValidationStatus.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push(`${i.name}: ${a}`)):f.valid?i.size<=0?(s=m.FileValidationStatus.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=m.FileValidationStatus.VALIDATION_FAILED,a="File MIME type is required",t.push(`${i.name}: ${a}`)):e.allowedMimeTypes.some(c=>i.type.startsWith(c))?ft.has(i.type)?gt(i.name,i.type)?i.size>e.maxFileSize?(s=m.FileValidationStatus.VALIDATION_FAILED,a=`File size (${L(i.size)}) exceeds limit of ${L(e.maxFileSize)}`,t.push(`${i.name}: ${a}`)):(r+=i.size,r>e.maxTotalSize&&(s=m.FileValidationStatus.VALIDATION_FAILED,a=`Total size would exceed limit of ${L(e.maxTotalSize)}`,t.push(`${i.name}: ${a}`))):(s=m.FileValidationStatus.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${i.name}: ${a}`)):(s=m.FileValidationStatus.VALIDATION_FAILED,a=`Invalid MIME type "${i.type}"`,t.push(`${i.name}: ${a}`)):(s=m.FileValidationStatus.VALIDATION_FAILED,a=`File type "${i.type}" is not allowed`,t.push(`${i.name}: ${a}`)):(s=m.FileValidationStatus.VALIDATION_FAILED,a=f.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!==m.FileValidationStatus.READY&&a.status!==m.FileValidationStatus.PENDING),s=ht(i?.status,i?.statusMessage);return{files:o.map(a=>({...a,status:m.FileValidationStatus.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 ce(n){return n.filter(e=>e.status===m.FileValidationStatus.READY)}function be(n){return ce(n).length>0}var ue=require("@shipstatic/types");function ke(n){return n instanceof ue.ShipError?n:n instanceof Error?ue.ShipError.business(n.message):ue.ShipError.business(String(n??"Unknown error"))}var b=require("@shipstatic/types");p(d,u);re();q();Oe();I();var X=class extends _{constructor(e={}){if(C()!=="node")throw me.ShipError.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return B(e,{})}async loadFullConfig(){try{let e=await M(this.clientOptions.configFile),t=B(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let o=new w({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(o);let r=await this.http.getConfig();K(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 me.ShipError.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw me.ShipError.business("No files to deploy.");let{processFilesForNode:r}=await Promise.resolve().then(()=>(Oe(),je));return r(o,t)}getDeployBodyCreator(){return Ke}},$e=X;p(Q,d,module.exports);0&&(module.exports={ApiHttp,DEFAULT_API,ErrorType,FILE_VALIDATION_STATUS,JUNK_DIRECTORIES,Ship,ShipError,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,ensureShipError,filterJunk,formatFileSize,getCurrentConfig,getENV,getValidFiles,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,setPlatformConfig,validateFiles});
1
+ "use strict";var je=Object.create;var ee=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var Ge=Object.getOwnPropertyNames;var Ye=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty;var w=(n,e)=>()=>(n&&(e=n(n=0)),e);var z=(n,e)=>{for(var t in e)ee(n,t,{get:e[t],enumerable:!0})},Z=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ge(e))!We.call(n,r)&&r!==t&&ee(n,r,{get:()=>e[r],enumerable:!(o=Ve(e,r))||o.enumerable});return n},p=(n,e,t)=>(Z(n,e,"default"),t&&Z(t,e,"default")),v=(n,e,t)=>(t=n!=null?je(Ye(n)):{},Z(e||!n||!n.__esModule?ee(t,"default",{value:n,enumerable:!0}):t,n)),Je=n=>Z(ee({},"__esModule",{value:!0}),n);function K(n){de=n}function O(){if(de===null)throw $e.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return de}var $e,de,q=w(()=>{"use strict";$e=require("@shipstatic/types"),de=null});function ne(n){he=n}function Qe(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function C(){return he||Qe()}var he,F=w(()=>{"use strict";he=null});var Me={};z(Me,{loadConfig:()=>N});function ke(n){try{return Ze.parse(n)}catch(e){if(e instanceof M.z.ZodError){let t=e.issues[0],o=t.path.length>0?` at ${t.path.join(".")}`:"";throw oe.ShipError.config(`Configuration validation failed${o}: ${t.message}`)}throw oe.ShipError.config("Configuration validation failed")}}async function et(n){try{if(C()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),o=e(ye,{searchPlaces:[`.${ye}rc`,"package.json",`${t.homedir()}/.${ye}rc`],stopDir:t.homedir()}),r;if(n?r=o.load(n):r=o.search(),r&&r.config)return ke(r.config)}catch(e){if(e instanceof oe.ShipError)throw e}return{}}async function N(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 et(n),o={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return ke(o)}var M,oe,ye,Ze,ie=w(()=>{"use strict";M=require("zod"),oe=require("@shipstatic/types");F();ye="ship",Ze=M.z.object({apiUrl:M.z.string().url().optional(),apiKey:M.z.string().optional(),deployToken:M.z.string().optional()}).strict()});async function nt(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($.ShipError.business("Failed to read file chunk"));return}a.append(c),s++,s<i?S():t({md5:a.end()})},u.onerror=()=>{o($.ShipError.business("Failed to calculate MD5: FileReader error"))},S()})}async function ot(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($.ShipError.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 k(n){let e=C();if(e==="browser"){if(!(n instanceof Blob))throw $.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return nt(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw $.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return ot(n)}throw $.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var $,re=w(()=>{"use strict";F();$=require("@shipstatic/types")});function W(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((0,_e.isJunk)(o))return!1;let r=t.slice(0,-1);for(let i of r)if(pe.some(s=>i.toLowerCase()===s.toLowerCase()))return!1;return!0})}var _e,pe,Te=w(()=>{"use strict";_e=require("junk"),pe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function ze(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 le(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Re=w(()=>{"use strict"});function J(n,e={}){if(e.flatten===!1)return n.map(o=>({path:le(o),name:xe(o)}));let t=rt(n);return n.map(o=>{let r=le(o);if(t){let i=t.endsWith("/")?t:`${t}/`;r.startsWith(i)&&(r=r.substring(i.length))}return r||(r=xe(o)),{path:r,name:xe(o)}})}function rt(n){if(!n.length)return"";let t=n.map(i=>le(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 xe(n){return n.split(/[/\\]/).pop()||n}var Ae=w(()=>{"use strict";Re()});var qe={};z(qe,{processFilesForNode:()=>fe});function Ke(n,e=new Set){let t=[],o=R.realpathSync(n);if(e.has(o))return t;e.add(o);let r=R.readdirSync(n);for(let i of r){let s=E.join(n,i),a=R.statSync(s);if(a.isDirectory()){let u=Ke(s,e);t.push(...u)}else a.isFile()&&t.push(s)}return t}async function fe(n,e={}){if(C()!=="node")throw I.ShipError.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(h=>{let y=E.resolve(h);try{return R.statSync(y).isDirectory()?Ke(y):[y]}catch{throw I.ShipError.file(`Path does not exist: ${h}`,h)}}),o=[...new Set(t)],r=W(o);if(r.length===0)return[];let i=n.map(h=>E.resolve(h)),s=ze(i.map(h=>{try{return R.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=J(a,{flatten:e.pathDetect!==!1}),S=[],D=0,c=O();for(let h=0;h<r.length;h++){let y=r[h],x=u[h].path;try{let A=R.statSync(y);if(A.size===0)continue;if(A.size>c.maxFileSize)throw I.ShipError.business(`File ${y} is too large. Maximum allowed size is ${c.maxFileSize/(1024*1024)}MB.`);if(D+=A.size,D>c.maxTotalSize)throw I.ShipError.business(`Total deploy size is too large. Maximum allowed is ${c.maxTotalSize/(1024*1024)}MB.`);let _=R.readFileSync(y),{md5:He}=await k(_);if(x.includes("\0")||x.includes("/../")||x.startsWith("../")||x.endsWith("/.."))throw I.ShipError.business(`Security error: Unsafe file path "${x}" for file: ${y}`);S.push({path:x,content:_,size:_.length,md5:He})}catch(A){if(A instanceof I.ShipError)throw A;let _=A instanceof Error?A.message:String(A);throw I.ShipError.file(`Failed to read file "${y}": ${_}`,y)}}if(S.length>c.maxFilesCount)throw I.ShipError.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return S}var I,R,E,be=w(()=>{"use strict";F();re();Te();I=require("@shipstatic/types");q();Ae();Re();R=v(require("fs"),1),E=v(require("path"),1)});var Q={};z(Q,{ApiHttp:()=>P,DEFAULT_API:()=>ae.DEFAULT_API,ErrorType:()=>b.ErrorType,FILE_VALIDATION_STATUS:()=>f.FileValidationStatus,JUNK_DIRECTORIES:()=>pe,Ship:()=>X,ShipError:()=>b.ShipError,__setTestEnvironment:()=>ne,allValidFilesReady:()=>we,calculateMD5:()=>k,createAccountResource:()=>G,createDeploymentResource:()=>j,createDomainResource:()=>V,createTokenResource:()=>Y,default:()=>Oe,ensureShipError:()=>Fe,filterJunk:()=>W,formatFileSize:()=>L,getCurrentConfig:()=>O,getENV:()=>C,getValidFiles:()=>ce,loadConfig:()=>N,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>J,pluralize:()=>ve,processFilesForNode:()=>fe,resolveConfig:()=>U,setPlatformConfig:()=>K,validateFiles:()=>Ie});module.exports=Je(Q);var m={};z(m,{ApiHttp:()=>P,DEFAULT_API:()=>ae.DEFAULT_API,ErrorType:()=>b.ErrorType,FILE_VALIDATION_STATUS:()=>f.FileValidationStatus,JUNK_DIRECTORIES:()=>pe,Ship:()=>X,ShipError:()=>b.ShipError,__setTestEnvironment:()=>ne,allValidFilesReady:()=>we,calculateMD5:()=>k,createAccountResource:()=>G,createDeploymentResource:()=>j,createDomainResource:()=>V,createTokenResource:()=>Y,default:()=>Oe,ensureShipError:()=>Fe,filterJunk:()=>W,formatFileSize:()=>L,getCurrentConfig:()=>O,getENV:()=>C,getValidFiles:()=>ce,loadConfig:()=>N,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>J,pluralize:()=>ve,processFilesForNode:()=>fe,resolveConfig:()=>U,setPlatformConfig:()=>K,validateFiles:()=>Ie});var T=require("@shipstatic/types");var te=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"},Xe=3e4,P=class extends te{constructor(e){super(),this.apiUrl=e.apiUrl||T.DEFAULT_API,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Xe,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?T.ShipError.authentication(r):T.ShipError.api(r,e.status,o.code,o)}handleFetchError(e,t){throw e.name==="AbortError"?T.ShipError.cancelled(`${t} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?T.ShipError.network(`${t} failed: ${e.message}`,e):e instanceof T.ShipError?e:T.ShipError.business(`${t} failed: ${e.message||"Unknown error"}`)}async deploy(e,t={}){if(!e.length)throw T.ShipError.business("No files to deploy");for(let s of e)if(!s.md5)throw T.ShipError.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}};var De=require("@shipstatic/types");q();var se=require("@shipstatic/types");var Ne=require("@shipstatic/types");F();async function tt(n){let e=C();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(ie(),Me));return t(n)}else return{}}function U(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||Ne.DEFAULT_API,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 H(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}var ge=require("@shipstatic/types");re();async function it(){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 k(t);return{path:ge.DEPLOYMENT_CONFIG_FILENAME,content:t,size:e.length,md5:o}}async function Ue(n,e,t){if(t.spaDetect===!1||n.some(o=>o.path===ge.DEPLOYMENT_CONFIG_FILENAME))return n;try{if(await e.checkSPA(n)){let r=await it();return[...n,r]}}catch{}return n}function j(n){let{getApi:e,ensureInit:t,processInput:o,clientDefaults:r,hasAuth:i}=n;return{create:async(s,a={})=>{await t();let u=r?H(a,r):a;if(i&&!i()&&!u.deployToken&&!u.apiKey)throw se.ShipError.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!o)throw se.ShipError.config("processInput function is not provided.");let S=e(),D=await o(s,u);return D=await Ue(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 V(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 se.ShipError.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 G(n){let{getApi:e,ensureInit:t}=n;return{get:async()=>(await t(),e().getAccount())}}function Y(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 B=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 P({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let o={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=j({...o,processInput:(r,i)=>this.processInput(r,i),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=V(o),this._account=G(o),this._tokens=Y(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=O(),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 De.ShipError.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 De.ShipError.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}};var me=require("@shipstatic/types");F();ie();q();var Ee=require("@shipstatic/types");var Se=v(require("mime-db"),1),Ce={};for(let n in Se.default){let e=Se.default[n];e&&e.extensions&&e.extensions.forEach(t=>{Ce[t]||(Ce[t]=n)})}function Be(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return Ce[e]||"application/octet-stream"}async function Le(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=Be(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 Ee.ShipError.file(`Unsupported file.content type for Node.js: ${c.path}`,c.path);if(!c.md5)throw Ee.ShipError.file(`File missing md5 checksum: ${c.path}`,c.path);let x=c.path.startsWith("/")?c.path:"/"+c.path;s.append("files[]",y,x),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={};z(l,{ApiHttp:()=>P,DEFAULT_API:()=>ae.DEFAULT_API,ErrorType:()=>b.ErrorType,FILE_VALIDATION_STATUS:()=>f.FileValidationStatus,JUNK_DIRECTORIES:()=>pe,Ship:()=>B,ShipError:()=>b.ShipError,__setTestEnvironment:()=>ne,allValidFilesReady:()=>we,calculateMD5:()=>k,createAccountResource:()=>G,createDeploymentResource:()=>j,createDomainResource:()=>V,createTokenResource:()=>Y,ensureShipError:()=>Fe,filterJunk:()=>W,formatFileSize:()=>L,getENV:()=>C,getValidFiles:()=>ce,loadConfig:()=>tt,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>J,pluralize:()=>ve,resolveConfig:()=>U,validateFiles:()=>Ie});var g={};p(g,require("@shipstatic/types"));p(l,g);var ae=require("@shipstatic/types");re();function ve(n,e,t,o=!0){let r=n===1?e:t;return o?`${n} ${r}`:r}Te();Ae();F();var f=require("@shipstatic/types"),Pe=v(require("mime-db"),1),st=new Set(Object.keys(Pe.default)),at=new Map(Object.entries(Pe.default).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)]));var pt=[[/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 lt(n,e){if(n===f.FileValidationStatus.PROCESSING_ERROR)return"Processing Error";if(n===f.FileValidationStatus.EMPTY_FILE)return"Empty File";if(!e)return"Validation Failed";for(let[t,o]of pt)if(t.test(e))return o;return"Validation Failed"}function L(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 ct(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 ut(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=at.get(e);if(r&&!r.has(o))return!1}return!0}function Ie(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.FileValidationStatus.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.FileValidationStatus.READY,a="Ready for upload",u=i.name?ct(i.name):{valid:!1,reason:"File name cannot be empty"};i.status===f.FileValidationStatus.PROCESSING_ERROR?(s=f.FileValidationStatus.PROCESSING_ERROR,a=i.statusMessage||"A file failed during processing.",t.push(`${i.name}: ${a}`)):!i.name||i.name.trim().length===0?(s=f.FileValidationStatus.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${i.name||"(empty)"}: ${a}`)):i.name.includes("\0")?(s=f.FileValidationStatus.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push(`${i.name}: ${a}`)):u.valid?i.size<=0?(s=f.FileValidationStatus.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.FileValidationStatus.VALIDATION_FAILED,a="File MIME type is required",t.push(`${i.name}: ${a}`)):e.allowedMimeTypes.some(S=>i.type.startsWith(S))?st.has(i.type)?ut(i.name,i.type)?i.size>e.maxFileSize?(s=f.FileValidationStatus.VALIDATION_FAILED,a=`File size (${L(i.size)}) exceeds limit of ${L(e.maxFileSize)}`,t.push(`${i.name}: ${a}`)):(r+=i.size,r>e.maxTotalSize&&(s=f.FileValidationStatus.VALIDATION_FAILED,a=`Total size would exceed limit of ${L(e.maxTotalSize)}`,t.push(`${i.name}: ${a}`))):(s=f.FileValidationStatus.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${i.name}: ${a}`)):(s=f.FileValidationStatus.VALIDATION_FAILED,a=`Invalid MIME type "${i.type}"`,t.push(`${i.name}: ${a}`)):(s=f.FileValidationStatus.VALIDATION_FAILED,a=`File type "${i.type}" is not allowed`,t.push(`${i.name}: ${a}`)):(s=f.FileValidationStatus.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.FileValidationStatus.READY&&a.status!==f.FileValidationStatus.PENDING),s=lt(i?.status,i?.statusMessage);return{files:o.map(a=>({...a,status:f.FileValidationStatus.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 ce(n){return n.filter(e=>e.status===f.FileValidationStatus.READY)}function we(n){return ce(n).length>0}var ue=require("@shipstatic/types");function Fe(n){return n instanceof ue.ShipError?n:n instanceof Error?ue.ShipError.business(n.message):ue.ShipError.business(String(n??"Unknown error"))}var b=require("@shipstatic/types");p(m,l);ie();q();be();F();var X=class extends B{constructor(e={}){if(C()!=="node")throw me.ShipError.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return U(e,{})}async loadFullConfig(){try{let e=await N(this.clientOptions.configFile),t=U(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let o=new P({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(o);let r=await this.http.getConfig();K(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 me.ShipError.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw me.ShipError.business("No files to deploy.");let{processFilesForNode:r}=await Promise.resolve().then(()=>(be(),qe));return r(o,t)}getDeployBodyCreator(){return Le}},Oe=X;p(Q,m,module.exports);0&&(module.exports={ApiHttp,DEFAULT_API,ErrorType,FILE_VALIDATION_STATUS,JUNK_DIRECTORIES,Ship,ShipError,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,ensureShipError,filterJunk,formatFileSize,getCurrentConfig,getENV,getValidFiles,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,setPlatformConfig,validateFiles});
2
2
 
3
3
  // Ship SDK: Enable axios-style CommonJS imports
4
4
  const originalExports = module.exports;