@shipstatic/ship 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var bt=Object.create;var ke=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var xt=Object.getOwnPropertyNames;var Pt=Object.getPrototypeOf,$t=Object.prototype.hasOwnProperty;var L=(t,e)=>()=>(t&&(e=t(t=0)),e);var te=(t,e)=>{for(var o in e)ke(t,o,{get:e[o],enumerable:!0})},$e=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of xt(e))!$t.call(t,i)&&i!==o&&ke(t,i,{get:()=>e[i],enumerable:!(n=Ft(e,i))||n.enumerable});return t},f=(t,e,o)=>($e(t,e,"default"),o&&$e(o,e,"default")),F=(t,e,o)=>(o=t!=null?bt(Pt(t)):{},$e(e||!t||!t.__esModule?ke(o,"default",{value:t,enumerable:!0}):o,t));var Qe={};te(Qe,{__setTestEnvironment:()=>me,getENV:()=>D});function me(t){Re=t}function kt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function D(){return Re||kt()}var Re,R=L(()=>{"use strict";Re=null});function oe(t){Ne=t}function B(){if(Ne===null)throw tt.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return Ne}var tt,Ne,H=L(()=>{"use strict";tt=require("@shipstatic/types"),Ne=null});var nt={};te(nt,{loadConfig:()=>ne});function ot(t){try{return Ot.parse(t)}catch(e){if(e instanceof W.z.ZodError){let o=e.issues[0],n=o.path.length>0?` at ${o.path.join(".")}`:"";throw de.ShipError.config(`Configuration validation failed${n}: ${o.message}`)}throw de.ShipError.config("Configuration validation failed")}}async function Nt(t){try{if(D()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),o=await import("os"),n=e(Le,{searchPlaces:[`.${Le}rc`,"package.json",`${o.homedir()}/.${Le}rc`],stopDir:o.homedir()}),i;if(t?i=n.load(t):i=n.search(),i&&i.config)return ot(i.config)}catch(e){if(e instanceof de.ShipError)throw e}return{}}async function ne(t){if(D()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},o=await Nt(t),n={apiUrl:e.apiUrl??o.apiUrl,apiKey:e.apiKey??o.apiKey,deployToken:e.deployToken??o.deployToken};return ot(n)}var W,de,Le,Ot,ue=L(()=>{"use strict";W=require("zod"),de=require("@shipstatic/types");R();Le="ship",Ot=W.z.object({apiUrl:W.z.string().url().optional(),apiKey:W.z.string().optional(),deployToken:W.z.string().optional()}).strict()});async function Mt(t){let e=(await import("spark-md5")).default;return new Promise((o,n)=>{let s=Math.ceil(t.size/2097152),r=0,a=new e.ArrayBuffer,p=new FileReader,c=()=>{let m=r*2097152,l=Math.min(m+2097152,t.size);p.readAsArrayBuffer(t.slice(m,l))};p.onload=m=>{let l=m.target?.result;if(!l){n(G.ShipError.business("Failed to read file chunk"));return}a.append(l),r++,r<s?c():o({md5:a.end()})},p.onerror=()=>{n(G.ShipError.business("Failed to calculate MD5: FileReader error"))},c()})}async function jt(t){let e=await import("crypto");if(Buffer.isBuffer(t)){let n=e.createHash("md5");return n.update(t),{md5:n.digest("hex")}}let o=await import("fs");return new Promise((n,i)=>{let s=e.createHash("md5"),r=o.createReadStream(t);r.on("error",a=>i(G.ShipError.business(`Failed to read file for MD5: ${a.message}`))),r.on("data",a=>s.update(a)),r.on("end",()=>n({md5:s.digest("hex")}))})}async function K(t){let e=D();if(e==="browser"){if(!(t instanceof Blob))throw G.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Mt(t)}if(e==="node"){if(!(Buffer.isBuffer(t)||typeof t=="string"))throw G.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return jt(t)}throw G.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var G,se=L(()=>{"use strict";R();G=require("@shipstatic/types")});function Z(t){return!t||t.length===0?[]:t.filter(e=>{if(!e)return!1;let o=e.replace(/\\/g,"/").split("/").filter(Boolean);if(o.length===0)return!0;let n=o[o.length-1];if((0,at.isJunk)(n))return!1;let i=o.slice(0,-1);for(let s of i)if(_e.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var at,_e,De=L(()=>{"use strict";at=require("junk"),_e=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function lt(t){if(!t||t.length===0)return"";let e=t.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let o=e.map(s=>s.split("/").filter(Boolean)),n=[],i=Math.min(...o.map(s=>s.length));for(let s=0;s<i;s++){let r=o[0][s];if(o.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function Ce(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ze=L(()=>{"use strict"});function X(t,e={}){if(e.flatten===!1)return t.map(n=>({path:Ce(n),name:Ue(n)}));let o=zt(t);return t.map(n=>{let i=Ce(n);if(o){let s=o.endsWith("/")?o:`${o}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=Ue(n)),{path:i,name:Ue(n)}})}function zt(t){if(!t.length)return"";let o=t.map(s=>Ce(s)).map(s=>s.split("/")),n=[],i=Math.min(...o.map(s=>s.length));for(let s=0;s<i-1;s++){let r=o[0][s];if(o.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function Ue(t){return t.split(/[/\\]/).pop()||t}var ve=L(()=>{"use strict";ze()});function mt(t){let e=[];try{let o=_.readdirSync(t);for(let n of o){let i=I.join(t,n),s=_.statSync(i);if(s.isDirectory()){let r=mt(i);e.push(...r)}else s.isFile()&&e.push(i)}}catch(o){console.error(`Error reading directory ${t}:`,o)}return e}async function Te(t,e={}){if(D()!=="node")throw q.ShipError.business("processFilesForNode can only be called in Node.js environment.");let o=t.flatMap(h=>{let y=I.resolve(h);try{return _.statSync(y).isDirectory()?mt(y):[y]}catch{throw q.ShipError.file(`Path does not exist: ${h}`,h)}}),n=[...new Set(o)],i=Z(n);if(i.length===0)return[];let s=t.map(h=>I.resolve(h)),r=lt(s.map(h=>{try{return _.statSync(h).isDirectory()?h:I.dirname(h)}catch{return I.dirname(h)}})),a=i.map(h=>{if(r&&r.length>0){let y=I.relative(r,h);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return I.basename(h)}),p=X(a,{flatten:e.pathDetect!==!1}),c=[],m=0,l=B();for(let h=0;h<i.length;h++){let y=i[h],N=p[h].path;try{let j=_.statSync(y);if(j.size===0){console.warn(`Skipping empty file: ${y}`);continue}if(j.size>l.maxFileSize)throw q.ShipError.business(`File ${y} is too large. Maximum allowed size is ${l.maxFileSize/(1024*1024)}MB.`);if(m+=j.size,m>l.maxTotalSize)throw q.ShipError.business(`Total deploy size is too large. Maximum allowed is ${l.maxTotalSize/(1024*1024)}MB.`);let Pe=_.readFileSync(y),{md5:Et}=await K(Pe);if(N.includes("\0")||N.includes("/../")||N.startsWith("../")||N.endsWith("/.."))throw q.ShipError.business(`Security error: Unsafe file path "${N}" for file: ${y}`);c.push({path:N,content:Pe,size:Pe.length,md5:Et})}catch(j){if(j instanceof q.ShipError&&j.isClientError&&j.isClientError())throw j;console.error(`Could not process file ${y}:`,j)}}if(c.length>l.maxFilesCount)throw q.ShipError.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return c}var q,_,I,qe=L(()=>{"use strict";R();se();De();q=require("@shipstatic/types");H();ve();ze();_=F(require("fs"),1),I=F(require("path"),1)});async function ft(t,e={}){let{getENV:o}=await Promise.resolve().then(()=>(R(),Qe));if(o()!=="browser")throw Ve.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let n=Array.isArray(t)?t:Array.from(t),i=n.map(l=>l.webkitRelativePath||l.name),s=X(i,{flatten:e.pathDetect!==!1}),r=[];for(let l=0;l<n.length;l++){let h=n[l],y=s[l].path;if(y.includes("..")||y.includes("\0"))throw Ve.ShipError.business(`Security error: Unsafe file path "${y}" for file: ${h.name}`);r.push({file:h,relativePath:y})}let a=r.map(l=>l.relativePath),p=Z(a),c=new Set(p),m=[];for(let l of r){if(!c.has(l.relativePath))continue;let{md5:h}=await K(l.file);m.push({content:l.file,path:l.relativePath,size:l.file.size,md5:h})}return m}var Ve,dt=L(()=>{"use strict";se();Ve=require("@shipstatic/types");De();ve()});var St={};te(St,{convertBrowserInput:()=>yt,convertDeployInput:()=>qt,convertNodeInput:()=>He});function ut(t,e={}){let o=B();if(!e.skipEmptyCheck&&t.length===0)throw k.ShipError.business("No files to deploy.");if(t.length>o.maxFilesCount)throw k.ShipError.business(`Too many files to deploy. Maximum allowed is ${o.maxFilesCount}.`);let n=0;for(let i of t){if(i.size>o.maxFileSize)throw k.ShipError.business(`File ${i.name} is too large. Maximum allowed size is ${o.maxFileSize/(1024*1024)}MB.`);if(n+=i.size,n>o.maxTotalSize)throw k.ShipError.business(`Total deploy size is too large. Maximum allowed is ${o.maxTotalSize/(1024*1024)}MB.`)}}function ht(t,e){if(e==="node"){if(!Array.isArray(t))throw k.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(t.length===0)throw k.ShipError.business("No files to deploy.");if(!t.every(o=>typeof o=="string"))throw k.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&t instanceof HTMLInputElement&&!t.files)throw k.ShipError.business("No files selected in HTMLInputElement")}function gt(t){let e=t.map(o=>({name:o.path,size:o.size}));return ut(e,{skipEmptyCheck:!0}),t.forEach(o=>{o.path&&(o.path=o.path.replace(/\\/g,"/"))}),t}async function He(t,e={}){ht(t,"node");let o=await Te(t,e);return gt(o)}async function yt(t,e={}){ht(t,"browser");let o;if(t instanceof HTMLInputElement)o=Array.from(t.files);else if(typeof t=="object"&&t!==null&&typeof t.length=="number"&&typeof t.item=="function")o=Array.from(t);else if(Array.isArray(t)){if(t.length>0&&typeof t[0]=="string")throw k.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");o=t}else throw k.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");o=o.filter(i=>i.size===0?(console.warn(`Skipping empty file: ${i.name}`),!1):!0),ut(o);let n=await ft(o,e);return gt(n)}async function qt(t,e={},o){let n=D();if(n!=="node"&&n!=="browser")throw k.ShipError.business("Unsupported execution environment.");let i;if(n==="node")if(typeof t=="string")i=await He([t],e);else if(Array.isArray(t)&&t.every(s=>typeof s=="string"))i=await He(t,e);else throw k.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");else i=await yt(t,e);return i}var k,wt=L(()=>{"use strict";k=require("@shipstatic/types");R();qe();dt();H()});var Ct=require("commander");var T={};te(T,{ApiHttp:()=>U,DEFAULT_API:()=>je.DEFAULT_API,FILE_VALIDATION_STATUS:()=>w,JUNK_DIRECTORIES:()=>_e,Ship:()=>Q,ShipError:()=>$.ShipError,ShipErrorType:()=>$.ShipErrorType,__setTestEnvironment:()=>me,allValidFilesReady:()=>ct,calculateMD5:()=>K,createAccountResource:()=>Se,createDeploymentResource:()=>ge,createDomainResource:()=>ye,createTokenResource:()=>we,default:()=>Vt,filterJunk:()=>Z,formatFileSize:()=>re,getCurrentConfig:()=>B,getENV:()=>D,getValidFiles:()=>Ke,loadConfig:()=>ne,mergeDeployOptions:()=>he,optimizeDeployPaths:()=>X,pluralize:()=>rt,processFilesForNode:()=>Te,resolveConfig:()=>ie,setConfig:()=>oe,setPlatformConfig:()=>oe,validateFiles:()=>pt});var Ie=F(require("mime-db"),1),Ae={};for(let t in Ie.default){let e=Ie.default[t];e&&e.extensions&&e.extensions.forEach(o=>{Ae[o]||(Ae[o]=t)})}function pe(t){let e=t.includes(".")?t.substring(t.lastIndexOf(".")+1).toLowerCase():"";return Ae[e]||"application/octet-stream"}var P=require("@shipstatic/types");var ce=class{constructor(){this.handlers=new Map}on(e,o){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(o)}off(e,o){let n=this.handlers.get(e);n&&(n.delete(o),n.size===0&&this.handlers.delete(e))}emit(e,...o){let n=this.handlers.get(e);if(!n)return;let i=Array.from(n);for(let s of i)try{s(...o)}catch(r){n.delete(s),e!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(e)):this.emit("error",new Error(String(r)),String(e))},0)}}transfer(e){this.handlers.forEach((o,n)=>{o.forEach(i=>{e.on(n,i)})})}clear(){this.handlers.clear()}};R();var fe="/deployments",et="/ping",O="/domains",It="/config",At="/account",Oe="/tokens",Rt="/spa-check",U=class extends ce{constructor(e){super(),this.apiUrl=e.apiUrl||P.DEFAULT_API,this.apiKey=e.apiKey??"",this.deployToken=e.deployToken??""}transferEventsTo(e){this.transfer(e)}async request(e,o={},n){let i=this.getAuthHeaders(o.headers),s={...o,headers:i,credentials:this.needsCredentials(i)?"include":void 0};this.emit("request",e,s);try{let r=await fetch(e,s);r.ok||await this.handleResponseError(r,n);let a=this.safeClone(r),p=this.safeClone(r);return this.emit("response",a,e),await this.parseResponse(p)}catch(r){throw this.emit("error",r,e),this.handleFetchError(r,n),r}}getAuthHeaders(e={}){let o={...e};return this.deployToken?o.Authorization=`Bearer ${this.deployToken}`:this.apiKey&&(o.Authorization=`Bearer ${this.apiKey}`),o}needsCredentials(e){return!this.apiKey&&!this.deployToken&&!e.Authorization}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,o){let n={};try{e.headers.get("content-type")?.includes("application/json")?n=await e.json():n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let i=n.message||n.error||`${o} failed due to API error`;throw e.status===401?P.ShipError.authentication(i):P.ShipError.api(i,e.status,n.code,n)}handleFetchError(e,o){throw e.name==="AbortError"?P.ShipError.cancelled(`${o} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?P.ShipError.network(`${o} failed due to network error: ${e.message}`,e):e instanceof P.ShipError?e:P.ShipError.business(`An unexpected error occurred during ${o}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${et}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${et}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${It}`,{method:"GET"},"Config")}async deploy(e,o={}){this.validateFiles(e);let{requestBody:n,requestHeaders:i}=await this.prepareRequestPayload(e,o.tags),s={};o.deployToken?s={Authorization:`Bearer ${o.deployToken}`}:o.apiKey&&(s={Authorization:`Bearer ${o.apiKey}`});let r={method:"POST",body:n,headers:{...i,...s},signal:o.signal||null};return await this.request(`${o.apiUrl||this.apiUrl}${fe}`,r,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${fe}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${fe}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${fe}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,o,n){let i={deployment:o};n&&n.length>0&&(i.tags=n);let s={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},r=this.getAuthHeaders(s.headers),a={...s,headers:r,credentials:this.needsCredentials(r)?"include":void 0};this.emit("request",`${this.apiUrl}${O}/${encodeURIComponent(e)}`,a);try{let p=await fetch(`${this.apiUrl}${O}/${encodeURIComponent(e)}`,a);p.ok||await this.handleResponseError(p,"Set Domain");let c=this.safeClone(p),m=this.safeClone(p);return this.emit("response",c,`${this.apiUrl}${O}/${encodeURIComponent(e)}`),{...await this.parseResponse(m),isCreate:p.status===201}}catch(p){throw this.emit("error",p,`${this.apiUrl}${O}/${encodeURIComponent(e)}`),this.handleFetchError(p,"Set Domain"),p}}async getDomain(e){return await this.request(`${this.apiUrl}${O}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${O}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${O}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async confirmDomain(e){return await this.request(`${this.apiUrl}${O}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${O}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${O}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${O}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${At}`,{method:"GET"},"Get Account")}async createToken(e,o){let n={};return e!==void 0&&(n.ttl=e),o&&o.length>0&&(n.tags=o),await this.request(`${this.apiUrl}${Oe}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${Oe}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${Oe}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}async checkSPA(e){let o=e.find(r=>r.path==="index.html"||r.path==="/index.html");if(!o||o.size>100*1024)return!1;let n;if(typeof Buffer<"u"&&Buffer.isBuffer(o.content))n=o.content.toString("utf-8");else if(typeof Blob<"u"&&o.content instanceof Blob)n=await o.content.text();else if(typeof File<"u"&&o.content instanceof File)n=await o.content.text();else return!1;let i={files:e.map(r=>r.path),index:n};return(await this.request(`${this.apiUrl}${Rt}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw P.ShipError.business("No files to deploy.");for(let o of e)if(!o.md5)throw P.ShipError.file(`MD5 checksum missing for file: ${o.path}`,o.path)}async prepareRequestPayload(e,o){if(D()==="browser")return{requestBody:this.createBrowserBody(e,o),requestHeaders:{}};if(D()==="node"){let{body:n,headers:i}=await this.createNodeBody(e,o);return{requestBody:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),requestHeaders:i}}else throw P.ShipError.business("Unknown or unsupported execution environment")}createBrowserBody(e,o){let n=new FormData,i=[];for(let s of e){if(!(s.content instanceof File||s.content instanceof Blob))throw P.ShipError.file(`Unsupported file.content type for browser FormData: ${s.path}`,s.path);let r=this.getBrowserContentType(s.content instanceof File?s.content:s.path),a=new File([s.content],s.path,{type:r});n.append("files[]",a),i.push(s.md5)}return n.append("checksums",JSON.stringify(i)),o&&o.length>0&&n.append("tags",JSON.stringify(o)),n}async createNodeBody(e,o){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new n,a=[];for(let l of e){let h=pe(l.path),y;if(Buffer.isBuffer(l.content))y=new i([l.content],l.path,{type:h});else if(typeof Blob<"u"&&l.content instanceof Blob)y=new i([l.content],l.path,{type:h});else throw P.ShipError.file(`Unsupported file.content type for Node.js FormData: ${l.path}`,l.path);let N=l.path.startsWith("/")?l.path:"/"+l.path;r.append("files[]",y,N),a.push(l.md5)}r.append("checksums",JSON.stringify(a)),o&&o.length>0&&r.append("tags",JSON.stringify(o));let p=new s(r),c=[];for await(let l of p.encode())c.push(Buffer.from(l));let m=Buffer.concat(c);return{body:m,headers:{"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(m).toString()}}}getBrowserContentType(e){return typeof e=="string"?pe(e):e.type||pe(e.name)}};H();var it=require("@shipstatic/types");R();async function Lt(t){let e=D();if(e==="browser")return{};if(e==="node"){let{loadConfig:o}=await Promise.resolve().then(()=>(ue(),nt));return o(t)}else return{}}function ie(t={},e={}){let o={apiUrl:t.apiUrl||e.apiUrl||it.DEFAULT_API,apiKey:t.apiKey!==void 0?t.apiKey:e.apiKey,deployToken:t.deployToken!==void 0?t.deployToken:e.deployToken},n={apiUrl:o.apiUrl};return o.apiKey!==void 0&&(n.apiKey=o.apiKey),o.deployToken!==void 0&&(n.deployToken=o.deployToken),n}function he(t,e){let o={...t};return o.apiUrl===void 0&&e.apiUrl!==void 0&&(o.apiUrl=e.apiUrl),o.apiKey===void 0&&e.apiKey!==void 0&&(o.apiKey=e.apiKey),o.deployToken===void 0&&e.deployToken!==void 0&&(o.deployToken=e.deployToken),o.timeout===void 0&&e.timeout!==void 0&&(o.timeout=e.timeout),o.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(o.maxConcurrency=e.maxConcurrency),o.onProgress===void 0&&e.onProgress!==void 0&&(o.onProgress=e.onProgress),o.onProgressStats===void 0&&e.onProgressStats!==void 0&&(o.onProgressStats=e.onProgressStats),o}var Me=require("@shipstatic/types");se();async function _t(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),o;typeof Buffer<"u"?o=Buffer.from(e,"utf-8"):o=new Blob([e],{type:"application/json"});let{md5:n}=await K(o);return{path:Me.DEPLOYMENT_CONFIG_FILENAME,content:o,size:e.length,md5:n}}async function st(t,e,o){if(o.spaDetect===!1||t.some(n=>n.path===Me.DEPLOYMENT_CONFIG_FILENAME))return t;try{if(await e.checkSPA(t)){let i=await _t();return[...t,i]}}catch{}return t}function ge(t,e,o,n){return{create:async(i,s={})=>{o&&await o();let r=e?he(s,e):s,a=t();if(!n)throw new Error("processInput function is not provided.");let p=await n(i,r);return p=await st(p,a,r),await a.deploy(p,r)},list:async()=>(o&&await o(),t().listDeployments()),remove:async i=>{o&&await o(),await t().removeDeployment(i)},get:async i=>(o&&await o(),t().getDeployment(i))}}function ye(t,e){return{set:async(o,n,i)=>(e&&await e(),t().setDomain(o,n,i)),get:async o=>(e&&await e(),t().getDomain(o)),list:async()=>(e&&await e(),t().listDomains()),remove:async o=>{e&&await e(),await t().removeDomain(o)},confirm:async o=>(e&&await e(),t().confirmDomain(o)),dns:async o=>(e&&await e(),t().getDomainDns(o)),records:async o=>(e&&await e(),t().getDomainRecords(o)),share:async o=>(e&&await e(),t().getDomainShare(o))}}function Se(t,e){return{get:async()=>(e&&await e(),t().getAccount())}}function we(t,e){return{create:async(o,n)=>(e&&await e(),t().createToken(o,n)),list:async()=>(e&&await e(),t().listTokens()),remove:async o=>{e&&await e(),await t().removeToken(o)}}}var Y=class{constructor(e={}){this.initPromise=null;this._config=null;this.clientOptions=e;let o=this.resolveInitialConfig(e);this.http=new U({...e,...o});let n=()=>this.ensureInitialized(),i=()=>this.http;this._deployments=ge(i,this.clientOptions,n,(s,r)=>this.processInput(s,r)),this._domains=ye(i,n),this._account=Se(i,n),this._tokens=we(i,n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,o){return this.deployments.create(e,o)}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=B(),this._config)}on(e,o){this.http.on(e,o)}off(e,o){this.http.off(e,o)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(o){console.warn("Event transfer failed during client replacement:",o)}this.http=e}};var Ee=require("@shipstatic/types");R();ue();H();var d={};te(d,{ApiHttp:()=>U,DEFAULT_API:()=>je.DEFAULT_API,FILE_VALIDATION_STATUS:()=>w,JUNK_DIRECTORIES:()=>_e,Ship:()=>Y,ShipError:()=>$.ShipError,ShipErrorType:()=>$.ShipErrorType,__setTestEnvironment:()=>me,allValidFilesReady:()=>ct,calculateMD5:()=>K,createAccountResource:()=>Se,createDeploymentResource:()=>ge,createDomainResource:()=>ye,createTokenResource:()=>we,filterJunk:()=>Z,formatFileSize:()=>re,getENV:()=>D,getValidFiles:()=>Ke,loadConfig:()=>Lt,mergeDeployOptions:()=>he,optimizeDeployPaths:()=>X,pluralize:()=>rt,resolveConfig:()=>ie,validateFiles:()=>pt});var v={};f(v,require("@shipstatic/types"));f(d,v);var je=require("@shipstatic/types");se();function rt(t,e,o,n=!0){let i=t===1?e:o;return n?`${t} ${i}`:i}De();ve();R();var Be=F(require("mime-db"),1),Ut=new Set(Object.keys(Be.default)),Bt=new Map(Object.entries(Be.default).filter(([t,e])=>e.extensions).map(([t,e])=>[t,new Set(e.extensions)])),w={PENDING:"pending",PROCESSING_ERROR:"processing_error",EMPTY_FILE:"empty_file",VALIDATION_FAILED:"validation_failed",READY:"ready"};function re(t,e=1){if(t===0)return"0 Bytes";let o=1024,n=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/Math.pow(o,i)).toFixed(e))+" "+n[i]}function Kt(t,e){if(t.startsWith("."))return!0;let o=t.toLowerCase().split(".");if(o.length>1&&o[o.length-1]){let n=o[o.length-1],i=Bt.get(e);if(i&&!i.has(n))return!1}return!0}function pt(t,e){let o=[],n=[];if(t.length===0){let s="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:s,errors:[s],isClientError:!0}}}if(t.length>e.maxFilesCount){let s=`Number of files (${t.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:t.map(r=>({...r,status:w.VALIDATION_FAILED,statusMessage:s})),validFiles:[],error:{error:"File Count Exceeded",details:s,errors:[s],isClientError:!0}}}let i=0;for(let s of t){let r=w.READY,a="Ready for upload";s.status===w.PROCESSING_ERROR?(r=w.PROCESSING_ERROR,a=s.statusMessage||"A file failed during processing.",o.push(`${s.name}: ${a}`)):!s.name||s.name.trim().length===0?(r=w.VALIDATION_FAILED,a="File name cannot be empty",o.push(`${s.name||"(empty)"}: ${a}`)):s.name.includes("..")?(r=w.VALIDATION_FAILED,a="Invalid file name. File name contains invalid characters",o.push(`${s.name}: ${a}`)):s.name.includes("\0")?(r=w.VALIDATION_FAILED,a="Invalid file name. File name contains invalid characters",o.push(`${s.name}: ${a}`)):s.size<=0?(r=w.EMPTY_FILE,a=s.size===0?"File is empty (0 bytes)":"File size must be positive",o.push(`${s.name}: ${a}`)):!s.type||s.type.trim().length===0?(r=w.VALIDATION_FAILED,a="File MIME type is required",o.push(`${s.name}: ${a}`)):e.allowedMimeTypes.some(p=>s.type.startsWith(p))?Ut.has(s.type)?Kt(s.name,s.type)?s.size>e.maxFileSize?(r=w.VALIDATION_FAILED,a=`File size (${re(s.size)}) exceeds limit of ${re(e.maxFileSize)}`,o.push(`${s.name}: ${a}`)):(i+=s.size,i>e.maxTotalSize&&(r=w.VALIDATION_FAILED,a=`Total size would exceed limit of ${re(e.maxTotalSize)}`,o.push(`${s.name}: ${a}`))):(r=w.VALIDATION_FAILED,a="File extension does not match MIME type",o.push(`${s.name}: ${a}`)):(r=w.VALIDATION_FAILED,a=`Invalid MIME type "${s.type}"`,o.push(`${s.name}: ${a}`)):(r=w.VALIDATION_FAILED,a=`File type "${s.type}" is not allowed`,o.push(`${s.name}: ${a}`)),n.push({...s,status:r,statusMessage:a})}if(o.length>0){let s=n.find(a=>a.status!==w.READY&&a.status!==w.PENDING),r="Validation Failed";return s?.status===w.PROCESSING_ERROR?r="Processing Error":s?.status===w.EMPTY_FILE?r="Empty File":s?.statusMessage?.includes("File name cannot be empty")||s?.statusMessage?.includes("Invalid file name")?r="Invalid File Name":s?.statusMessage?.includes("File size must be positive")?r="Invalid File Size":s?.statusMessage?.includes("MIME type is required")?r="Missing MIME Type":s?.statusMessage?.includes("Invalid MIME type")?r="Invalid MIME Type":s?.statusMessage?.includes("not allowed")?r="Invalid File Type":s?.statusMessage?.includes("extension does not match")?r="Extension Mismatch":s?.statusMessage?.includes("Total size")?r="Total Size Exceeded":s?.statusMessage?.includes("exceeds limit")&&(r="File Too Large"),{files:n.map(a=>({...a,status:w.VALIDATION_FAILED})),validFiles:[],error:{error:r,details:o.length===1?o[0]:`${o.length} file(s) failed validation`,errors:o,isClientError:!0}}}return{files:n,validFiles:n,error:null}}function Ke(t){return t.filter(e=>e.status===w.READY)}function ct(t){return Ke(t).length>0}var $=require("@shipstatic/types");f(T,d);ue();H();H();qe();R();var Q=class extends Y{constructor(e={}){if(D()!=="node")throw Ee.ShipError.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return ie(e,{})}async loadFullConfig(){try{let e=await ne(this.clientOptions.configFile),o=ie(this.clientOptions,e),n=new U({...this.clientOptions,...o});this.replaceHttpClient(n);let i=await this.http.getConfig();oe(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,o){if(!this.#e(e))throw Ee.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw Ee.ShipError.business("No files to deploy.");let{convertDeployInput:n}=await Promise.resolve().then(()=>(wt(),St));return n(e,o,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(o=>typeof o=="string"):!1}},Vt=Q;var z=require("@shipstatic/types"),J=require("fs"),C=F(require("path"),1);var Ge=F(require("columnify"),1),g=require("yoctocolors"),b=(t,e,o)=>o?e:t(e),A=(t,e,o)=>{console.log(e?JSON.stringify({success:t},null,2)+`
3
- `:`${b(g.green,t.toLowerCase().replace(/\.$/,""),o)}
4
- `)},E=(t,e,o)=>{if(e)console.error(JSON.stringify({error:t},null,2)+`
5
- `);else{let n=b(s=>(0,g.inverse)((0,g.red)(s)),`${b(g.hidden,"[",o)}error${b(g.hidden,"]",o)}`,o),i=b(g.red,t.toLowerCase().replace(/\.$/,""),o);console.error(`${n} ${i}
2
+ "use strict";var Et=Object.create;var ke=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var Pt=Object.getOwnPropertyNames;var xt=Object.getPrototypeOf,$t=Object.prototype.hasOwnProperty;var M=(t,e)=>()=>(t&&(e=t(t=0)),e);var te=(t,e)=>{for(var o in e)ke(t,o,{get:e[o],enumerable:!0})},$e=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Pt(e))!$t.call(t,i)&&i!==o&&ke(t,i,{get:()=>e[i],enumerable:!(n=Ft(e,i))||n.enumerable});return t},f=(t,e,o)=>($e(t,e,"default"),o&&$e(o,e,"default")),F=(t,e,o)=>(o=t!=null?Et(xt(t)):{},$e(e||!t||!t.__esModule?ke(o,"default",{value:t,enumerable:!0}):o,t));var Qe={};te(Qe,{__setTestEnvironment:()=>me,getENV:()=>v});function me(t){Ae=t}function kt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function v(){return Ae||kt()}var Ae,A=M(()=>{"use strict";Ae=null});function oe(t){Ne=t}function B(){if(Ne===null)throw tt.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return Ne}var tt,Ne,G=M(()=>{"use strict";tt=require("@shipstatic/types"),Ne=null});var nt={};te(nt,{loadConfig:()=>ne});function ot(t){try{return Ot.parse(t)}catch(e){if(e instanceof W.z.ZodError){let o=e.issues[0],n=o.path.length>0?` at ${o.path.join(".")}`:"";throw de.ShipError.config(`Configuration validation failed${n}: ${o.message}`)}throw de.ShipError.config("Configuration validation failed")}}async function Nt(t){try{if(v()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),o=await import("os"),n=e(Me,{searchPlaces:[`.${Me}rc`,"package.json",`${o.homedir()}/.${Me}rc`],stopDir:o.homedir()}),i;if(t?i=n.load(t):i=n.search(),i&&i.config)return ot(i.config)}catch(e){if(e instanceof de.ShipError)throw e}return{}}async function ne(t){if(v()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},o=await Nt(t),n={apiUrl:e.apiUrl??o.apiUrl,apiKey:e.apiKey??o.apiKey,deployToken:e.deployToken??o.deployToken};return ot(n)}var W,de,Me,Ot,ue=M(()=>{"use strict";W=require("zod"),de=require("@shipstatic/types");A();Me="ship",Ot=W.z.object({apiUrl:W.z.string().url().optional(),apiKey:W.z.string().optional(),deployToken:W.z.string().optional()}).strict()});async function jt(t){let e=(await import("spark-md5")).default;return new Promise((o,n)=>{let s=Math.ceil(t.size/2097152),r=0,a=new e.ArrayBuffer,p=new FileReader,c=()=>{let m=r*2097152,l=Math.min(m+2097152,t.size);p.readAsArrayBuffer(t.slice(m,l))};p.onload=m=>{let l=m.target?.result;if(!l){n(H.ShipError.business("Failed to read file chunk"));return}a.append(l),r++,r<s?c():o({md5:a.end()})},p.onerror=()=>{n(H.ShipError.business("Failed to calculate MD5: FileReader error"))},c()})}async function _t(t){let e=await import("crypto");if(Buffer.isBuffer(t)){let n=e.createHash("md5");return n.update(t),{md5:n.digest("hex")}}let o=await import("fs");return new Promise((n,i)=>{let s=e.createHash("md5"),r=o.createReadStream(t);r.on("error",a=>i(H.ShipError.business(`Failed to read file for MD5: ${a.message}`))),r.on("data",a=>s.update(a)),r.on("end",()=>n({md5:s.digest("hex")}))})}async function K(t){let e=v();if(e==="browser"){if(!(t instanceof Blob))throw H.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return jt(t)}if(e==="node"){if(!(Buffer.isBuffer(t)||typeof t=="string"))throw H.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return _t(t)}throw H.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var H,se=M(()=>{"use strict";A();H=require("@shipstatic/types")});function Z(t){return!t||t.length===0?[]:t.filter(e=>{if(!e)return!1;let o=e.replace(/\\/g,"/").split("/").filter(Boolean);if(o.length===0)return!0;let n=o[o.length-1];if((0,at.isJunk)(n))return!1;let i=o.slice(0,-1);for(let s of i)if(Le.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var at,Le,ve=M(()=>{"use strict";at=require("junk"),Le=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function lt(t){if(!t||t.length===0)return"";let e=t.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let o=e.map(s=>s.split("/").filter(Boolean)),n=[],i=Math.min(...o.map(s=>s.length));for(let s=0;s<i;s++){let r=o[0][s];if(o.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function De(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Ue=M(()=>{"use strict"});function X(t,e={}){if(e.flatten===!1)return t.map(n=>({path:De(n),name:ze(n)}));let o=Ut(t);return t.map(n=>{let i=De(n);if(o){let s=o.endsWith("/")?o:`${o}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=ze(n)),{path:i,name:ze(n)}})}function Ut(t){if(!t.length)return"";let o=t.map(s=>De(s)).map(s=>s.split("/")),n=[],i=Math.min(...o.map(s=>s.length));for(let s=0;s<i-1;s++){let r=o[0][s];if(o.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function ze(t){return t.split(/[/\\]/).pop()||t}var Ce=M(()=>{"use strict";Ue()});function mt(t){let e=[];try{let o=L.readdirSync(t);for(let n of o){let i=k.join(t,n),s=L.statSync(i);if(s.isDirectory()){let r=mt(i);e.push(...r)}else s.isFile()&&e.push(i)}}catch(o){console.error(`Error reading directory ${t}:`,o)}return e}async function Te(t,e={}){if(v()!=="node")throw q.ShipError.business("processFilesForNode can only be called in Node.js environment.");let o=t.flatMap(h=>{let y=k.resolve(h);try{return L.statSync(y).isDirectory()?mt(y):[y]}catch{throw q.ShipError.file(`Path does not exist: ${h}`,h)}}),n=[...new Set(o)],i=Z(n);if(i.length===0)return[];let s=t.map(h=>k.resolve(h)),r=lt(s.map(h=>{try{return L.statSync(h).isDirectory()?h:k.dirname(h)}catch{return k.dirname(h)}})),a=i.map(h=>{if(r&&r.length>0){let y=k.relative(r,h);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return k.basename(h)}),p=X(a,{flatten:e.pathDetect!==!1}),c=[],m=0,l=B();for(let h=0;h<i.length;h++){let y=i[h],N=p[h].path;try{let _=L.statSync(y);if(_.size===0){console.warn(`Skipping empty file: ${y}`);continue}if(_.size>l.maxFileSize)throw q.ShipError.business(`File ${y} is too large. Maximum allowed size is ${l.maxFileSize/(1024*1024)}MB.`);if(m+=_.size,m>l.maxTotalSize)throw q.ShipError.business(`Total deploy size is too large. Maximum allowed is ${l.maxTotalSize/(1024*1024)}MB.`);let xe=L.readFileSync(y),{md5:bt}=await K(xe);if(N.includes("\0")||N.includes("/../")||N.startsWith("../")||N.endsWith("/.."))throw q.ShipError.business(`Security error: Unsafe file path "${N}" for file: ${y}`);c.push({path:N,content:xe,size:xe.length,md5:bt})}catch(_){if(_ instanceof q.ShipError&&_.isClientError&&_.isClientError())throw _;console.error(`Could not process file ${y}:`,_)}}if(c.length>l.maxFilesCount)throw q.ShipError.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return c}var q,L,k,qe=M(()=>{"use strict";A();se();ve();q=require("@shipstatic/types");G();Ce();Ue();L=F(require("fs"),1),k=F(require("path"),1)});async function ft(t,e={}){let{getENV:o}=await Promise.resolve().then(()=>(A(),Qe));if(o()!=="browser")throw Ve.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let n=t,i=n.map(l=>l.webkitRelativePath||l.name),s=X(i,{flatten:e.pathDetect!==!1}),r=[];for(let l=0;l<n.length;l++){let h=n[l],y=s[l].path;if(y.includes("..")||y.includes("\0"))throw Ve.ShipError.business(`Security error: Unsafe file path "${y}" for file: ${h.name}`);r.push({file:h,relativePath:y})}let a=r.map(l=>l.relativePath),p=Z(a),c=new Set(p),m=[];for(let l of r){if(!c.has(l.relativePath))continue;let{md5:h}=await K(l.file);m.push({content:l.file,path:l.relativePath,size:l.file.size,md5:h})}return m}var Ve,dt=M(()=>{"use strict";se();Ve=require("@shipstatic/types");ve();Ce()});var St={};te(St,{convertBrowserInput:()=>yt,convertDeployInput:()=>Vt,convertNodeInput:()=>Ge});function ut(t,e={}){let o=B();if(!e.skipEmptyCheck&&t.length===0)throw I.ShipError.business("No files to deploy.");if(t.length>o.maxFilesCount)throw I.ShipError.business(`Too many files to deploy. Maximum allowed is ${o.maxFilesCount}.`);let n=0;for(let i of t){if(i.size>o.maxFileSize)throw I.ShipError.business(`File ${i.name} is too large. Maximum allowed size is ${o.maxFileSize/(1024*1024)}MB.`);if(n+=i.size,n>o.maxTotalSize)throw I.ShipError.business(`Total deploy size is too large. Maximum allowed is ${o.maxTotalSize/(1024*1024)}MB.`)}}function ht(t,e){if(e==="node"){if(!Array.isArray(t))throw I.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(t.length===0)throw I.ShipError.business("No files to deploy.");if(!t.every(o=>typeof o=="string"))throw I.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}}function gt(t){let e=t.map(o=>({name:o.path,size:o.size}));return ut(e,{skipEmptyCheck:!0}),t.forEach(o=>{o.path&&(o.path=o.path.replace(/\\/g,"/"))}),t}async function Ge(t,e={}){ht(t,"node");let o=await Te(t,e);return gt(o)}async function yt(t,e={}){ht(t,"browser");let o;if(Array.isArray(t)){if(t.length>0&&typeof t[0]=="string")throw I.ShipError.business("Invalid input type for browser environment. Expected File[].");o=t}else throw I.ShipError.business("Invalid input type for browser environment. Expected File[].");o=o.filter(i=>i.size===0?(console.warn(`Skipping empty file: ${i.name}`),!1):!0),ut(o);let n=await ft(o,e);return gt(n)}async function Vt(t,e={},o){let n=v();if(n!=="node"&&n!=="browser")throw I.ShipError.business("Unsupported execution environment.");let i;if(n==="node")if(typeof t=="string")i=await Ge([t],e);else if(Array.isArray(t)&&t.every(s=>typeof s=="string"))i=await Ge(t,e);else throw I.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");else i=await yt(t,e);return i}var I,wt=M(()=>{"use strict";I=require("@shipstatic/types");A();qe();dt();G()});var Dt=require("commander");var T={};te(T,{ApiHttp:()=>z,DEFAULT_API:()=>_e.DEFAULT_API,FILE_VALIDATION_STATUS:()=>w,JUNK_DIRECTORIES:()=>Le,Ship:()=>Q,ShipError:()=>$.ShipError,ShipErrorType:()=>$.ShipErrorType,__setTestEnvironment:()=>me,allValidFilesReady:()=>ct,calculateMD5:()=>K,createAccountResource:()=>Se,createDeploymentResource:()=>ge,createDomainResource:()=>ye,createTokenResource:()=>we,default:()=>Gt,filterJunk:()=>Z,formatFileSize:()=>re,getCurrentConfig:()=>B,getENV:()=>v,getValidFiles:()=>Ke,loadConfig:()=>ne,mergeDeployOptions:()=>he,optimizeDeployPaths:()=>X,pluralize:()=>rt,processFilesForNode:()=>Te,resolveConfig:()=>ie,setConfig:()=>oe,setPlatformConfig:()=>oe,validateFiles:()=>pt});var Ie=F(require("mime-db"),1),Re={};for(let t in Ie.default){let e=Ie.default[t];e&&e.extensions&&e.extensions.forEach(o=>{Re[o]||(Re[o]=t)})}function pe(t){let e=t.includes(".")?t.substring(t.lastIndexOf(".")+1).toLowerCase():"";return Re[e]||"application/octet-stream"}var x=require("@shipstatic/types");var ce=class{constructor(){this.handlers=new Map}on(e,o){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(o)}off(e,o){let n=this.handlers.get(e);n&&(n.delete(o),n.size===0&&this.handlers.delete(e))}emit(e,...o){let n=this.handlers.get(e);if(!n)return;let i=Array.from(n);for(let s of i)try{s(...o)}catch(r){n.delete(s),e!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(e)):this.emit("error",new Error(String(r)),String(e))},0)}}transfer(e){this.handlers.forEach((o,n)=>{o.forEach(i=>{e.on(n,i)})})}clear(){this.handlers.clear()}};A();var fe="/deployments",et="/ping",O="/domains",It="/config",Rt="/account",Oe="/tokens",At="/spa-check",z=class extends ce{constructor(e){super(),this.apiUrl=e.apiUrl||x.DEFAULT_API,this.apiKey=e.apiKey??"",this.deployToken=e.deployToken??""}transferEventsTo(e){this.transfer(e)}async request(e,o={},n){let i=this.getAuthHeaders(o.headers),s={...o,headers:i,credentials:this.needsCredentials(i)?"include":void 0};this.emit("request",e,s);try{let r=await fetch(e,s);r.ok||await this.handleResponseError(r,n);let a=this.safeClone(r),p=this.safeClone(r);return this.emit("response",a,e),await this.parseResponse(p)}catch(r){throw this.emit("error",r,e),this.handleFetchError(r,n),r}}getAuthHeaders(e={}){let o={...e};return this.deployToken?o.Authorization=`Bearer ${this.deployToken}`:this.apiKey&&(o.Authorization=`Bearer ${this.apiKey}`),o}needsCredentials(e){return!this.apiKey&&!this.deployToken&&!e.Authorization}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,o){let n={};try{e.headers.get("content-type")?.includes("application/json")?n=await e.json():n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let i=n.message||n.error||`${o} failed due to API error`;throw e.status===401?x.ShipError.authentication(i):x.ShipError.api(i,e.status,n.code,n)}handleFetchError(e,o){throw e.name==="AbortError"?x.ShipError.cancelled(`${o} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?x.ShipError.network(`${o} failed due to network error: ${e.message}`,e):e instanceof x.ShipError?e:x.ShipError.business(`An unexpected error occurred during ${o}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${et}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${et}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${It}`,{method:"GET"},"Config")}async deploy(e,o={}){this.validateFiles(e);let{requestBody:n,requestHeaders:i}=await this.prepareRequestPayload(e,o.tags),s={};o.deployToken?s={Authorization:`Bearer ${o.deployToken}`}:o.apiKey&&(s={Authorization:`Bearer ${o.apiKey}`});let r={method:"POST",body:n,headers:{...i,...s},signal:o.signal||null};return await this.request(`${o.apiUrl||this.apiUrl}${fe}`,r,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${fe}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${fe}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${fe}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,o,n){let i={deployment:o};n&&n.length>0&&(i.tags=n);let s={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},r=this.getAuthHeaders(s.headers),a={...s,headers:r,credentials:this.needsCredentials(r)?"include":void 0};this.emit("request",`${this.apiUrl}${O}/${encodeURIComponent(e)}`,a);try{let p=await fetch(`${this.apiUrl}${O}/${encodeURIComponent(e)}`,a);p.ok||await this.handleResponseError(p,"Set Domain");let c=this.safeClone(p),m=this.safeClone(p);return this.emit("response",c,`${this.apiUrl}${O}/${encodeURIComponent(e)}`),{...await this.parseResponse(m),isCreate:p.status===201}}catch(p){throw this.emit("error",p,`${this.apiUrl}${O}/${encodeURIComponent(e)}`),this.handleFetchError(p,"Set Domain"),p}}async getDomain(e){return await this.request(`${this.apiUrl}${O}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${O}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${O}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async confirmDomain(e){return await this.request(`${this.apiUrl}${O}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${O}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${O}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${O}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${Rt}`,{method:"GET"},"Get Account")}async createToken(e,o){let n={};return e!==void 0&&(n.ttl=e),o&&o.length>0&&(n.tags=o),await this.request(`${this.apiUrl}${Oe}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${Oe}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${Oe}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}async checkSPA(e){let o=e.find(r=>r.path==="index.html"||r.path==="/index.html");if(!o||o.size>100*1024)return!1;let n;if(typeof Buffer<"u"&&Buffer.isBuffer(o.content))n=o.content.toString("utf-8");else if(typeof Blob<"u"&&o.content instanceof Blob)n=await o.content.text();else if(typeof File<"u"&&o.content instanceof File)n=await o.content.text();else return!1;let i={files:e.map(r=>r.path),index:n};return(await this.request(`${this.apiUrl}${At}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw x.ShipError.business("No files to deploy.");for(let o of e)if(!o.md5)throw x.ShipError.file(`MD5 checksum missing for file: ${o.path}`,o.path)}async prepareRequestPayload(e,o){if(v()==="browser")return{requestBody:this.createBrowserBody(e,o),requestHeaders:{}};if(v()==="node"){let{body:n,headers:i}=await this.createNodeBody(e,o);return{requestBody:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),requestHeaders:i}}else throw x.ShipError.business("Unknown or unsupported execution environment")}createBrowserBody(e,o){let n=new FormData,i=[];for(let s of e){if(!(s.content instanceof File||s.content instanceof Blob))throw x.ShipError.file(`Unsupported file.content type for browser FormData: ${s.path}`,s.path);let r=this.getBrowserContentType(s.content instanceof File?s.content:s.path),a=new File([s.content],s.path,{type:r});n.append("files[]",a),i.push(s.md5)}return n.append("checksums",JSON.stringify(i)),o&&o.length>0&&n.append("tags",JSON.stringify(o)),n}async createNodeBody(e,o){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new n,a=[];for(let l of e){let h=pe(l.path),y;if(Buffer.isBuffer(l.content))y=new i([l.content],l.path,{type:h});else if(typeof Blob<"u"&&l.content instanceof Blob)y=new i([l.content],l.path,{type:h});else throw x.ShipError.file(`Unsupported file.content type for Node.js FormData: ${l.path}`,l.path);let N=l.path.startsWith("/")?l.path:"/"+l.path;r.append("files[]",y,N),a.push(l.md5)}r.append("checksums",JSON.stringify(a)),o&&o.length>0&&r.append("tags",JSON.stringify(o));let p=new s(r),c=[];for await(let l of p.encode())c.push(Buffer.from(l));let m=Buffer.concat(c);return{body:m,headers:{"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(m).toString()}}}getBrowserContentType(e){return typeof e=="string"?pe(e):e.type||pe(e.name)}};G();var it=require("@shipstatic/types");A();async function Mt(t){let e=v();if(e==="browser")return{};if(e==="node"){let{loadConfig:o}=await Promise.resolve().then(()=>(ue(),nt));return o(t)}else return{}}function ie(t={},e={}){let o={apiUrl:t.apiUrl||e.apiUrl||it.DEFAULT_API,apiKey:t.apiKey!==void 0?t.apiKey:e.apiKey,deployToken:t.deployToken!==void 0?t.deployToken:e.deployToken},n={apiUrl:o.apiUrl};return o.apiKey!==void 0&&(n.apiKey=o.apiKey),o.deployToken!==void 0&&(n.deployToken=o.deployToken),n}function he(t,e){let o={...t};return o.apiUrl===void 0&&e.apiUrl!==void 0&&(o.apiUrl=e.apiUrl),o.apiKey===void 0&&e.apiKey!==void 0&&(o.apiKey=e.apiKey),o.deployToken===void 0&&e.deployToken!==void 0&&(o.deployToken=e.deployToken),o.timeout===void 0&&e.timeout!==void 0&&(o.timeout=e.timeout),o.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(o.maxConcurrency=e.maxConcurrency),o.onProgress===void 0&&e.onProgress!==void 0&&(o.onProgress=e.onProgress),o.onProgressStats===void 0&&e.onProgressStats!==void 0&&(o.onProgressStats=e.onProgressStats),o}var je=require("@shipstatic/types");se();async function Lt(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),o;typeof Buffer<"u"?o=Buffer.from(e,"utf-8"):o=new Blob([e],{type:"application/json"});let{md5:n}=await K(o);return{path:je.DEPLOYMENT_CONFIG_FILENAME,content:o,size:e.length,md5:n}}async function st(t,e,o){if(o.spaDetect===!1||t.some(n=>n.path===je.DEPLOYMENT_CONFIG_FILENAME))return t;try{if(await e.checkSPA(t)){let i=await Lt();return[...t,i]}}catch{}return t}function ge(t,e,o,n){return{create:async(i,s={})=>{o&&await o();let r=e?he(s,e):s,a=t();if(!n)throw new Error("processInput function is not provided.");let p=await n(i,r);return p=await st(p,a,r),await a.deploy(p,r)},list:async()=>(o&&await o(),t().listDeployments()),remove:async i=>{o&&await o(),await t().removeDeployment(i)},get:async i=>(o&&await o(),t().getDeployment(i))}}function ye(t,e){return{set:async(o,n,i)=>(e&&await e(),t().setDomain(o,n,i)),get:async o=>(e&&await e(),t().getDomain(o)),list:async()=>(e&&await e(),t().listDomains()),remove:async o=>{e&&await e(),await t().removeDomain(o)},confirm:async o=>(e&&await e(),t().confirmDomain(o)),dns:async o=>(e&&await e(),t().getDomainDns(o)),records:async o=>(e&&await e(),t().getDomainRecords(o)),share:async o=>(e&&await e(),t().getDomainShare(o))}}function Se(t,e){return{get:async()=>(e&&await e(),t().getAccount())}}function we(t,e){return{create:async(o,n)=>(e&&await e(),t().createToken(o,n)),list:async()=>(e&&await e(),t().listTokens()),remove:async o=>{e&&await e(),await t().removeToken(o)}}}var Y=class{constructor(e={}){this.initPromise=null;this._config=null;this.clientOptions=e;let o=this.resolveInitialConfig(e);this.http=new z({...e,...o});let n=()=>this.ensureInitialized(),i=()=>this.http;this._deployments=ge(i,this.clientOptions,n,(s,r)=>this.processInput(s,r)),this._domains=ye(i,n),this._account=Se(i,n),this._tokens=we(i,n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,o){return this.deployments.create(e,o)}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=B(),this._config)}on(e,o){this.http.on(e,o)}off(e,o){this.http.off(e,o)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(o){console.warn("Event transfer failed during client replacement:",o)}this.http=e}};var be=require("@shipstatic/types");A();ue();G();var d={};te(d,{ApiHttp:()=>z,DEFAULT_API:()=>_e.DEFAULT_API,FILE_VALIDATION_STATUS:()=>w,JUNK_DIRECTORIES:()=>Le,Ship:()=>Y,ShipError:()=>$.ShipError,ShipErrorType:()=>$.ShipErrorType,__setTestEnvironment:()=>me,allValidFilesReady:()=>ct,calculateMD5:()=>K,createAccountResource:()=>Se,createDeploymentResource:()=>ge,createDomainResource:()=>ye,createTokenResource:()=>we,filterJunk:()=>Z,formatFileSize:()=>re,getENV:()=>v,getValidFiles:()=>Ke,loadConfig:()=>Mt,mergeDeployOptions:()=>he,optimizeDeployPaths:()=>X,pluralize:()=>rt,resolveConfig:()=>ie,validateFiles:()=>pt});var C={};f(C,require("@shipstatic/types"));f(d,C);var _e=require("@shipstatic/types");se();function rt(t,e,o,n=!0){let i=t===1?e:o;return n?`${t} ${i}`:i}ve();Ce();A();var Be=F(require("mime-db"),1),zt=new Set(Object.keys(Be.default)),Bt=new Map(Object.entries(Be.default).filter(([t,e])=>e.extensions).map(([t,e])=>[t,new Set(e.extensions)])),w={PENDING:"pending",PROCESSING_ERROR:"processing_error",EMPTY_FILE:"empty_file",VALIDATION_FAILED:"validation_failed",READY:"ready"};function re(t,e=1){if(t===0)return"0 Bytes";let o=1024,n=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/Math.pow(o,i)).toFixed(e))+" "+n[i]}function Kt(t){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(t))return{valid:!1,reason:"File name contains unsafe characters"};if(t.startsWith(".")===!1&&(t.startsWith(" ")||t.endsWith(" ")||t.endsWith(".")))return{valid:!1,reason:"File name cannot start/end with spaces or end with dots"};let o=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,n=t.split("/").pop()||t;return o.test(n)?{valid:!1,reason:"File name uses a reserved system name"}:t.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function qt(t,e){if(t.startsWith("."))return!0;let o=t.toLowerCase().split(".");if(o.length>1&&o[o.length-1]){let n=o[o.length-1],i=Bt.get(e);if(i&&!i.has(n))return!1}return!0}function pt(t,e){let o=[],n=[];if(t.length===0){let s="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:s,errors:[s],isClientError:!0}}}if(t.length>e.maxFilesCount){let s=`Number of files (${t.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:t.map(r=>({...r,status:w.VALIDATION_FAILED,statusMessage:s})),validFiles:[],error:{error:"File Count Exceeded",details:s,errors:[s],isClientError:!0}}}let i=0;for(let s of t){let r=w.READY,a="Ready for upload",p=s.name?Kt(s.name):{valid:!1,reason:"File name cannot be empty"};s.status===w.PROCESSING_ERROR?(r=w.PROCESSING_ERROR,a=s.statusMessage||"A file failed during processing.",o.push(`${s.name}: ${a}`)):!s.name||s.name.trim().length===0?(r=w.VALIDATION_FAILED,a="File name cannot be empty",o.push(`${s.name||"(empty)"}: ${a}`)):s.name.includes("\0")?(r=w.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",o.push(`${s.name}: ${a}`)):p.valid?s.size<=0?(r=w.EMPTY_FILE,a=s.size===0?"File is empty (0 bytes)":"File size must be positive",o.push(`${s.name}: ${a}`)):!s.type||s.type.trim().length===0?(r=w.VALIDATION_FAILED,a="File MIME type is required",o.push(`${s.name}: ${a}`)):e.allowedMimeTypes.some(c=>s.type.startsWith(c))?zt.has(s.type)?qt(s.name,s.type)?s.size>e.maxFileSize?(r=w.VALIDATION_FAILED,a=`File size (${re(s.size)}) exceeds limit of ${re(e.maxFileSize)}`,o.push(`${s.name}: ${a}`)):(i+=s.size,i>e.maxTotalSize&&(r=w.VALIDATION_FAILED,a=`Total size would exceed limit of ${re(e.maxTotalSize)}`,o.push(`${s.name}: ${a}`))):(r=w.VALIDATION_FAILED,a="File extension does not match MIME type",o.push(`${s.name}: ${a}`)):(r=w.VALIDATION_FAILED,a=`Invalid MIME type "${s.type}"`,o.push(`${s.name}: ${a}`)):(r=w.VALIDATION_FAILED,a=`File type "${s.type}" is not allowed`,o.push(`${s.name}: ${a}`)):(r=w.VALIDATION_FAILED,a=p.reason||"Invalid file name",o.push(`${s.name}: ${a}`)),n.push({...s,status:r,statusMessage:a})}if(o.length>0){let s=n.find(a=>a.status!==w.READY&&a.status!==w.PENDING),r="Validation Failed";return s?.status===w.PROCESSING_ERROR?r="Processing Error":s?.status===w.EMPTY_FILE?r="Empty File":s?.statusMessage?.includes("File name cannot be empty")||s?.statusMessage?.includes("Invalid file name")||s?.statusMessage?.includes("File name contains")||s?.statusMessage?.includes("File name uses")||s?.statusMessage?.includes("File name cannot start")||s?.statusMessage?.includes("traversal")?r="Invalid File Name":s?.statusMessage?.includes("File size must be positive")?r="Invalid File Size":s?.statusMessage?.includes("MIME type is required")?r="Missing MIME Type":s?.statusMessage?.includes("Invalid MIME type")?r="Invalid MIME Type":s?.statusMessage?.includes("not allowed")?r="Invalid File Type":s?.statusMessage?.includes("extension does not match")?r="Extension Mismatch":s?.statusMessage?.includes("Total size")?r="Total Size Exceeded":s?.statusMessage?.includes("exceeds limit")&&(r="File Too Large"),{files:n.map(a=>({...a,status:w.VALIDATION_FAILED})),validFiles:[],error:{error:r,details:o.length===1?o[0]:`${o.length} file(s) failed validation`,errors:o,isClientError:!0}}}return{files:n,validFiles:n,error:null}}function Ke(t){return t.filter(e=>e.status===w.READY)}function ct(t){return Ke(t).length>0}var $=require("@shipstatic/types");f(T,d);ue();G();G();qe();A();var Q=class extends Y{constructor(e={}){if(v()!=="node")throw be.ShipError.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return ie(e,{})}async loadFullConfig(){try{let e=await ne(this.clientOptions.configFile),o=ie(this.clientOptions,e),n=new z({...this.clientOptions,...o});this.replaceHttpClient(n);let i=await this.http.getConfig();oe(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,o){if(!this.#e(e))throw be.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw be.ShipError.business("No files to deploy.");let{convertDeployInput:n}=await Promise.resolve().then(()=>(wt(),St));return n(e,o,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(o=>typeof o=="string"):!1}},Gt=Q;var U=require("@shipstatic/types"),J=require("fs"),D=F(require("path"),1);var He=F(require("columnify"),1),g=require("yoctocolors"),E=(t,e,o)=>o?e:t(e),R=(t,e,o)=>{console.log(e?JSON.stringify({success:t},null,2)+`
3
+ `:`${E(g.green,t.toLowerCase().replace(/\.$/,""),o)}
4
+ `)},b=(t,e,o)=>{if(e)console.error(JSON.stringify({error:t},null,2)+`
5
+ `);else{let n=E(s=>(0,g.inverse)((0,g.red)(s)),`${E(g.hidden,"[",o)}error${E(g.hidden,"]",o)}`,o),i=E(g.red,t.toLowerCase().replace(/\.$/,""),o);console.error(`${n} ${i}
6
6
  `)}},ee=(t,e,o)=>{if(e)console.log(JSON.stringify({warning:t},null,2)+`
7
- `);else{let n=b(s=>(0,g.inverse)((0,g.yellow)(s)),`${b(g.hidden,"[",o)}warning${b(g.hidden,"]",o)}`,o),i=b(g.yellow,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${i}
7
+ `);else{let n=E(s=>(0,g.inverse)((0,g.yellow)(s)),`${E(g.hidden,"[",o)}warning${E(g.hidden,"]",o)}`,o),i=E(g.yellow,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${i}
8
8
  `)}},ae=(t,e,o)=>{if(e)console.log(JSON.stringify({info:t},null,2)+`
9
- `);else{let n=b(s=>(0,g.inverse)((0,g.blue)(s)),`${b(g.hidden,"[",o)}info${b(g.hidden,"]",o)}`,o),i=b(g.blue,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${i}
10
- `)}},Ht=(t,e="details",o)=>{if(t==null||t===0)return"-";let n=new Date(t*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return e==="table"?n.replace(/T/,b(g.hidden,"T",o)).replace(/Z$/,b(g.hidden,"Z",o)):n},Dt=(t,e,o="details",n)=>{if(typeof e=="number"&&(t==="created"||t==="expires"||t==="confirmed"))return Ht(e,o,n);if(t==="size"&&typeof e=="number"){let i=e/1048576;return i>=1?`${i.toFixed(1)}Mb`:`${(e/1024).toFixed(1)}Kb`}if(t==="config"){if(typeof e=="boolean")return e?"yes":"no";if(typeof e=="number")return e===1?"yes":"no"}return String(e)},Je=(t,e,o)=>{if(!t||t.length===0)return"";let n=t[0]||{},i=e||Object.keys(n).filter(a=>n[a]!==void 0&&a!=="verified"&&a!=="isCreate"),s=t.map(a=>{let p={};return i.forEach(c=>{c in a&&a[c]!==void 0&&(p[c]=Dt(c,a[c],"table",o))}),p});return(0,Ge.default)(s,{columnSplitter:" ",columns:i,config:i.reduce((a,p)=>(a[p]={headingTransform:c=>b(g.dim,c,o)},a),{})}).split(`
9
+ `);else{let n=E(s=>(0,g.inverse)((0,g.blue)(s)),`${E(g.hidden,"[",o)}info${E(g.hidden,"]",o)}`,o),i=E(g.blue,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${i}
10
+ `)}},Ht=(t,e="details",o)=>{if(t==null||t===0)return"-";let n=new Date(t*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return e==="table"?n.replace(/T/,E(g.hidden,"T",o)).replace(/Z$/,E(g.hidden,"Z",o)):n},vt=(t,e,o="details",n)=>{if(typeof e=="number"&&(t==="created"||t==="expires"||t==="confirmed"))return Ht(e,o,n);if(t==="size"&&typeof e=="number"){let i=e/1048576;return i>=1?`${i.toFixed(1)}Mb`:`${(e/1024).toFixed(1)}Kb`}if(t==="config"){if(typeof e=="boolean")return e?"yes":"no";if(typeof e=="number")return e===1?"yes":"no"}return String(e)},Je=(t,e,o)=>{if(!t||t.length===0)return"";let n=t[0]||{},i=e||Object.keys(n).filter(a=>n[a]!==void 0&&a!=="verified"&&a!=="isCreate"),s=t.map(a=>{let p={};return i.forEach(c=>{c in a&&a[c]!==void 0&&(p[c]=vt(c,a[c],"table",o))}),p});return(0,He.default)(s,{columnSplitter:" ",columns:i,config:i.reduce((a,p)=>(a[p]={headingTransform:c=>E(g.dim,c,o)},a),{})}).split(`
11
11
  `).map(a=>a.replace(/\0/g,"").replace(/\s+$/,"")).join(`
12
12
  `)+`
13
- `},be=(t,e)=>{let o=Object.entries(t).filter(([s,r])=>s==="verified"||s==="isCreate"?!1:r!==void 0);if(o.length===0)return"";let n=o.map(([s,r])=>({property:s+":",value:Dt(s,r,"details",e)}));return(0,Ge.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>b(g.dim,s,e)}}}).split(`
13
+ `},Ee=(t,e)=>{let o=Object.entries(t).filter(([s,r])=>s==="verified"||s==="isCreate"?!1:r!==void 0);if(o.length===0)return"";let n=o.map(([s,r])=>({property:s+":",value:vt(s,r,"details",e)}));return(0,He.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>E(g.dim,s,e)}}}).split(`
14
14
  `).map(s=>s.replace(/\0/g,"")).join(`
15
15
  `)+`
16
- `};var Fe=require("yoctocolors"),S=F(require("fs"),1),Ye=F(require("os"),1),We={version:"0.0.0"};try{let t=C.resolve(__dirname,"../package.json");We=JSON.parse((0,J.readFileSync)(t,"utf-8"))}catch{let e=C.resolve(__dirname,"../../package.json");try{We=JSON.parse((0,J.readFileSync)(e,"utf-8"))}catch{}}var u=new Ct.Command;u.exitOverride(t=>{(t.code==="commander.help"||t.code==="commander.version"||t.exitCode===0)&&process.exit(t.exitCode||0);let e=u.opts(),o=t.message||"unknown command error";o=o.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),E(o,e.json,e.noColor),e.json||M(e.noColor),process.exit(t.exitCode||1)}).configureOutput({writeErr:t=>{t.startsWith("error:")||process.stderr.write(t)},writeOut:t=>process.stdout.write(t)});function M(t){let e=i=>t?i:(0,Fe.bold)(i),o=i=>t?i:(0,Fe.dim)(i),n=`${e("USAGE")}
16
+ `};var Fe=require("yoctocolors"),S=F(require("fs"),1),Ye=F(require("os"),1),We={version:"0.0.0"};try{let t=D.resolve(__dirname,"../package.json");We=JSON.parse((0,J.readFileSync)(t,"utf-8"))}catch{let e=D.resolve(__dirname,"../../package.json");try{We=JSON.parse((0,J.readFileSync)(e,"utf-8"))}catch{}}var u=new Dt.Command;u.exitOverride(t=>{(t.code==="commander.help"||t.code==="commander.version"||t.exitCode===0)&&process.exit(t.exitCode||0);let e=u.opts(),o=t.message||"unknown command error";o=o.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),b(o,e.json,e.noColor),e.json||j(e.noColor),process.exit(t.exitCode||1)}).configureOutput({writeErr:t=>{t.startsWith("error:")||process.stderr.write(t)},writeOut:t=>process.stdout.write(t)});function j(t){let e=i=>t?i:(0,Fe.bold)(i),o=i=>t?i:(0,Fe.dim)(i),n=`${e("USAGE")}
17
17
  ship <path> \u{1F680} Deploy static sites with simplicity
18
18
 
19
19
  ${e("COMMANDS")}
@@ -53,18 +53,18 @@ ${e("FLAGS")}
53
53
  --version Show version information
54
54
 
55
55
  ${o("Please report any issues to https://github.com/shipstatic/ship/issues")}
56
- `;console.log(n)}function Ze(t,e=[]){return e.concat([t])}function V(t){let e=t.optsWithGlobals?t.optsWithGlobals():t.opts();e.color===!1&&(e.noColor=!0);try{e.apiKey&&typeof e.apiKey=="string"&&(0,z.validateApiKey)(e.apiKey),e.deployToken&&typeof e.deployToken=="string"&&(0,z.validateDeployToken)(e.deployToken),e.apiUrl&&typeof e.apiUrl=="string"&&(0,z.validateApiUrl)(e.apiUrl)}catch(o){throw o instanceof $.ShipError&&(E(o.message,e.json,e.noColor),process.exit(1)),o}return e}function Gt(t,e,o){let n=u.opts();if(!(t instanceof $.ShipError)){let s=t.message||t;n.json?(console.error(JSON.stringify({error:s,details:{originalError:s}},null,2)),console.error()):(E(s,n.json,n.noColor),M(n.noColor)),process.exit(1)}let i=t.message;if(t.details?.data?.error==="not_found")if(e?.operation==="remove"){let s=e.resourceType||"resource";i=`${e.resourceId||""} ${s.toLowerCase()} not found`}else{let s=t.details.data.message||"Resource not found",r=s.match(/^(.*?)\s+(.+?)\s+not found$/);if(r){let[,a,p]=r;i=`${p} ${a.toLowerCase()} not found`}else i=s}else t.details?.data?.error==="business_logic_error"?i=t.details.data.message||"Business logic error occurred":t.isAuthError()?i="authentication failed":t.isNetworkError()?i="network error":!t.isFileError()&&!t.isValidationError()&&!t.isClientError()&&(i="server error");n.json?(console.error(JSON.stringify({error:i,...t.details?{details:t.details}:{}},null,2)),console.error()):(E(i,n.json,n.noColor),t.isValidationError()&&i.includes("unknown command")&&M(n.noColor)),process.exit(1)}function x(t,e){return async function(...o){try{let n=V(this),i=Jt(),s=await t(i,...o),r=e?{operation:e.operation,resourceType:e.resourceType,resourceId:e.getResourceId?e.getResourceId(...o):void 0,client:i}:{client:i};await Yt(s,r,n)}catch(n){let i=e?{operation:e.operation,resourceType:e.resourceType,resourceId:e.getResourceId?e.getResourceId(...o):void 0}:void 0,s=V(this);Gt(n,i,s)}}}function Jt(){let t=u.opts(),e={};return t.config!==void 0&&(e.configFile=t.config),t.apiUrl!==void 0&&(e.apiUrl=t.apiUrl),t.apiKey!==void 0&&(e.apiKey=t.apiKey),t.deployToken!==void 0&&(e.deployToken=t.deployToken),new Q(e)}var Wt={deployments:(t,e,o,n)=>{if(!t.deployments||t.deployments.length===0){o?console.log(JSON.stringify({deployments:[]},null,2)):(console.log("no deployments found"),console.log());return}let i=["deployment","url","created"];console.log(Je(t.deployments,i,n))},domains:(t,e,o,n)=>{if(!t.domains||t.domains.length===0){o?console.log(JSON.stringify({domains:[]},null,2)):(console.log("no domains found"),console.log());return}let i=["domain","deployment","url","created"];console.log(Je(t.domains,i,n))},domain:async(t,e,o,n)=>{if(t.domain){let i=t.isCreate?"created":"updated";A(`${t.domain} domain ${i}`,o,n)}if(!o&&t.isCreate&&t.domain?.includes(".")&&!t.confirmed&&e?.client)try{let[i,s]=await Promise.all([e.client.domains.records(t.domain),e.client.domains.share(t.domain)]);if(i.records&&i.records.length>0&&(console.log(),ae("DNS Records to configure:",o,n),i.records.forEach(r=>{console.log(` ${r.type}: ${r.name} \u2192 ${r.value}`)})),s.hash){let r=`https://setup.shipstatic.com/${s.hash}/${t.domain}`;console.log(),ae(`Setup instructions: ${r}`,o,n)}}catch{console.log(),ee(`To complete setup, configure DNS records for ${t.domain}`,o,n)}console.log(),console.log(be(t,n))},deployment:(t,e,o,n)=>{t.status&&e?.operation==="create"&&A(`${t.deployment} deployment created \u2728`,o,n),console.log(be(t,n))},email:(t,e,o,n)=>{console.log(be(t,n))},message:(t,e,o,n)=>{t.message&&A(t.message,o,n)}};async function vt(t,e,o,n){if(!(0,J.existsSync)(e))throw $.ShipError.file(`${e} path does not exist`,e);let i=(0,J.statSync)(e);if(!i.isDirectory()&&!i.isFile())throw $.ShipError.file(`${e} path must be a file or directory`,e);let s={};o?.tag&&o.tag.length>0&&(s.tags=o.tag),o?.noPathDetect!==void 0&&(s.pathDetect=!o.noPathDetect),o?.noSpaDetect!==void 0&&(s.spaDetect=!o.noSpaDetect);let r=new AbortController;s.signal=r.signal;let a=null,p=n?V(n):{};if(process.stdout.isTTY&&!p.json&&!p.noColor){let{default:m}=await import("yocto-spinner");a=m({text:"uploading\u2026"}).start()}let c=()=>{r.abort(),a&&a.stop(),process.exit(130)};process.on("SIGINT",c);try{let m=await t.deployments.create(e,s);return process.removeListener("SIGINT",c),a&&a.stop(),m}catch(m){throw process.removeListener("SIGINT",c),a&&a.stop(),m}}async function Yt(t,e,o){let n=o||u.opts();if(t===void 0){e?.operation==="remove"&&e.resourceType&&e.resourceId?A(`${e.resourceId} ${e.resourceType.toLowerCase()} removed`,n.json,n.noColor):A("removed successfully",n.json,n.noColor);return}if(t===!0||t&&typeof t=="object"&&t.hasOwnProperty("success")){t===!0||t.success?A("api reachable",n.json,n.noColor):E("api unreachable",n.json,n.noColor);return}if(n.json){console.log(JSON.stringify(t,null,2)),console.log();return}for(let[i,s]of Object.entries(Wt))if(t[i]){await s(t,e,n.json,n.noColor);return}A("success",n.json,n.noColor)}u.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(We.version,"--version","Show version information").option("--api-key <key>","API key for authenticated deployments").option("--deploy-token <token>","Deploy token for single-use deployments").option("--config <file>","Custom config file path").option("--api-url <url>","API URL (for development)").option("--json","Output results in JSON format").option("--no-color","Disable colored output").option("--help","Display help for command").helpOption(!1);u.hook("preAction",(t,e)=>{let o=t.opts();if(o.help){let n=o.color===!1||o.noColor;M(n),process.exit(0)}});u.hook("preAction",(t,e)=>{let o=t.opts();try{o.apiKey&&typeof o.apiKey=="string"&&(0,z.validateApiKey)(o.apiKey),o.deployToken&&typeof o.deployToken=="string"&&(0,z.validateDeployToken)(o.deployToken),o.apiUrl&&typeof o.apiUrl=="string"&&(0,z.validateApiUrl)(o.apiUrl)}catch(n){if(n instanceof $.ShipError){let i=o.color===!1||o.noColor;E(n.message,o.json,i),process.exit(1)}throw n}});u.command("ping").description("Check API connectivity").action(x(t=>t.ping()));u.command("whoami").description("Get current account information").action(x(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var xe=u.command("deployments").description("Manage deployments").action((...t)=>{let e=V(u),o=t[t.length-1];if(o&&o.args&&o.args.length>0){let n=o.args.find(i=>!["list","create","get","remove"].includes(i));n&&E(`unknown command '${n}'`,e.json,e.noColor)}M(e.noColor),process.exit(1)});xe.command("list").description("List all deployments").action(x(t=>t.deployments.list()));xe.command("create <path>").description("Create deployment from file or directory").option("--tag <tag>","Tag to add (can be repeated)",Ze,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(x(function(t,e,o){return vt(t,e,o,this)},{operation:"create"}));xe.command("get <deployment>").description("Show deployment information").action(x((t,e)=>t.deployments.get(e),{operation:"get",resourceType:"Deployment",getResourceId:t=>t}));xe.command("remove <deployment>").description("Delete deployment permanently").action(x((t,e)=>t.deployments.remove(e),{operation:"remove",resourceType:"Deployment",getResourceId:t=>t}));var le=u.command("domains").description("Manage domains").action((...t)=>{let e=V(u),o=t[t.length-1];if(o&&o.args&&o.args.length>0){let n=o.args.find(i=>!["list","get","set","remove"].includes(i));n&&E(`unknown command '${n}'`,e.json,e.noColor)}M(e.noColor),process.exit(1)});le.command("list").description("List all domains").action(x(t=>t.domains.list()));le.command("get <name>").description("Show domain information").action(x((t,e)=>t.domains.get(e),{operation:"get",resourceType:"Domain",getResourceId:t=>t}));le.command("confirm <name>").description("Trigger DNS confirmation for external domain").action(x((t,e)=>t.domains.confirm(e),{operation:"confirm",resourceType:"Domain",getResourceId:t=>t}));le.command("set <name> <deployment>").description("Create or update domain pointing to deployment").option("--tag <tag>","Tag to add (can be repeated)",Ze,[]).action(x((t,e,o,n)=>{let i=n?.tag&&n.tag.length>0?n.tag:void 0;return t.domains.set(e,o,i)},{operation:"set",resourceType:"Domain",getResourceId:t=>t}));le.command("remove <name>").description("Delete domain permanently").action(x((t,e)=>t.domains.remove(e),{operation:"remove",resourceType:"Domain",getResourceId:t=>t}));var Xe=u.command("tokens").description("Manage deploy tokens").action((...t)=>{let e=V(u),o=t[t.length-1];if(o&&o.args&&o.args.length>0){let n=o.args.find(i=>!["list","create","remove"].includes(i));n&&E(`unknown command '${n}'`,e.json,e.noColor)}M(e.noColor),process.exit(1)});Xe.command("list").description("List all tokens").action(x(t=>t.tokens.list()));Xe.command("create").description("Create a new deploy token").option("--ttl <seconds>","Time to live in seconds (default: never expires)",parseInt).option("--tag <tag>","Tag to add (can be repeated)",Ze,[]).action(x((t,e)=>{let o=e?.ttl,n=e?.tag&&e.tag.length>0?e.tag:void 0;return t.tokens.create(o,n)},{operation:"create",resourceType:"Token"}));Xe.command("remove <token>").description("Delete token permanently").action(x((t,e)=>t.tokens.remove(e),{operation:"remove",resourceType:"Token",getResourceId:t=>t}));var Zt=u.command("account").description("Manage account").action((...t)=>{let e=V(u),o=t[t.length-1];if(o&&o.args&&o.args.length>0){let n=o.args.find(i=>!["get"].includes(i));n&&E(`unknown command '${n}'`,e.json,e.noColor)}M(e.noColor),process.exit(1)});Zt.command("get").description("Show account information").action(x(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var Tt=u.command("completion").description("Setup shell completion").action((...t)=>{let e=V(u),o=t[t.length-1];if(o&&o.args&&o.args.length>0){let n=o.args.find(i=>!["install","uninstall"].includes(i));n&&E(`unknown command '${n}'`,e.json,e.noColor)}M(e.noColor),process.exit(1)});Tt.command("install").description("Install shell completion script").action(async()=>{let t=process.env.SHELL||"",e=Ye.homedir(),o,n,i="",s=C.resolve(__dirname,"completions/ship.bash"),r=C.resolve(__dirname,"completions/ship.zsh"),a=C.resolve(__dirname,"completions/ship.fish");try{if(t.includes("bash"))o=C.join(e,".ship_completion.bash"),n=C.join(e,".bash_profile"),i=`# ship
56
+ `;console.log(n)}function Ze(t,e=[]){return e.concat([t])}function V(t){let e=t.optsWithGlobals?t.optsWithGlobals():t.opts();e.color===!1&&(e.noColor=!0);try{e.apiKey&&typeof e.apiKey=="string"&&(0,U.validateApiKey)(e.apiKey),e.deployToken&&typeof e.deployToken=="string"&&(0,U.validateDeployToken)(e.deployToken),e.apiUrl&&typeof e.apiUrl=="string"&&(0,U.validateApiUrl)(e.apiUrl)}catch(o){throw o instanceof $.ShipError&&(b(o.message,e.json,e.noColor),process.exit(1)),o}return e}function Jt(t,e,o){let n=u.opts();if(!(t instanceof $.ShipError)){let s=t.message||t;n.json?(console.error(JSON.stringify({error:s,details:{originalError:s}},null,2)),console.error()):(b(s,n.json,n.noColor),j(n.noColor)),process.exit(1)}let i=t.message;if(t.details?.data?.error==="not_found")if(e?.operation==="remove"){let s=e.resourceType||"resource";i=`${e.resourceId||""} ${s.toLowerCase()} not found`}else{let s=t.details.data.message||"Resource not found",r=s.match(/^(.*?)\s+(.+?)\s+not found$/);if(r){let[,a,p]=r;i=`${p} ${a.toLowerCase()} not found`}else i=s}else t.details?.data?.error==="business_logic_error"?i=t.details.data.message||"Business logic error occurred":t.isAuthError()?i="authentication failed":t.isNetworkError()?i="network error":!t.isFileError()&&!t.isValidationError()&&!t.isClientError()&&(i="server error");n.json?(console.error(JSON.stringify({error:i,...t.details?{details:t.details}:{}},null,2)),console.error()):(b(i,n.json,n.noColor),t.isValidationError()&&i.includes("unknown command")&&j(n.noColor)),process.exit(1)}function P(t,e){return async function(...o){try{let n=V(this),i=Wt(),s=await t(i,...o),r=e?{operation:e.operation,resourceType:e.resourceType,resourceId:e.getResourceId?e.getResourceId(...o):void 0,client:i}:{client:i};await Zt(s,r,n)}catch(n){let i=e?{operation:e.operation,resourceType:e.resourceType,resourceId:e.getResourceId?e.getResourceId(...o):void 0}:void 0,s=V(this);Jt(n,i,s)}}}function Wt(){let t=u.opts(),e={};return t.config!==void 0&&(e.configFile=t.config),t.apiUrl!==void 0&&(e.apiUrl=t.apiUrl),t.apiKey!==void 0&&(e.apiKey=t.apiKey),t.deployToken!==void 0&&(e.deployToken=t.deployToken),new Q(e)}var Yt={deployments:(t,e,o,n)=>{if(!t.deployments||t.deployments.length===0){o?console.log(JSON.stringify({deployments:[]},null,2)):(console.log("no deployments found"),console.log());return}let i=["deployment","url","created"];console.log(Je(t.deployments,i,n))},domains:(t,e,o,n)=>{if(!t.domains||t.domains.length===0){o?console.log(JSON.stringify({domains:[]},null,2)):(console.log("no domains found"),console.log());return}let i=["domain","deployment","url","created"];console.log(Je(t.domains,i,n))},domain:async(t,e,o,n)=>{if(t.domain){let i=t.isCreate?"created":"updated";R(`${t.domain} domain ${i}`,o,n)}if(!o&&t.isCreate&&t.domain?.includes(".")&&!t.confirmed&&e?.client)try{let[i,s]=await Promise.all([e.client.domains.records(t.domain),e.client.domains.share(t.domain)]);if(i.records&&i.records.length>0&&(console.log(),ae("DNS Records to configure:",o,n),i.records.forEach(r=>{console.log(` ${r.type}: ${r.name} \u2192 ${r.value}`)})),s.hash){let r=`https://setup.shipstatic.com/${s.hash}/${t.domain}`;console.log(),ae(`Setup instructions: ${r}`,o,n)}}catch{console.log(),ee(`To complete setup, configure DNS records for ${t.domain}`,o,n)}console.log(),console.log(Ee(t,n))},deployment:(t,e,o,n)=>{t.status&&e?.operation==="create"&&R(`${t.deployment} deployment created \u2728`,o,n),console.log(Ee(t,n))},email:(t,e,o,n)=>{console.log(Ee(t,n))},message:(t,e,o,n)=>{t.message&&R(t.message,o,n)}};async function Ct(t,e,o,n){if(!(0,J.existsSync)(e))throw $.ShipError.file(`${e} path does not exist`,e);let i=(0,J.statSync)(e);if(!i.isDirectory()&&!i.isFile())throw $.ShipError.file(`${e} path must be a file or directory`,e);let s={};o?.tag&&o.tag.length>0&&(s.tags=o.tag),o?.noPathDetect!==void 0&&(s.pathDetect=!o.noPathDetect),o?.noSpaDetect!==void 0&&(s.spaDetect=!o.noSpaDetect);let r=new AbortController;s.signal=r.signal;let a=null,p=n?V(n):{};if(process.stdout.isTTY&&!p.json&&!p.noColor){let{default:m}=await import("yocto-spinner");a=m({text:"uploading\u2026"}).start()}let c=()=>{r.abort(),a&&a.stop(),process.exit(130)};process.on("SIGINT",c);try{let m=await t.deployments.create(e,s);return process.removeListener("SIGINT",c),a&&a.stop(),m}catch(m){throw process.removeListener("SIGINT",c),a&&a.stop(),m}}async function Zt(t,e,o){let n=o||u.opts();if(t===void 0){e?.operation==="remove"&&e.resourceType&&e.resourceId?R(`${e.resourceId} ${e.resourceType.toLowerCase()} removed`,n.json,n.noColor):R("removed successfully",n.json,n.noColor);return}if(t===!0||t&&typeof t=="object"&&t.hasOwnProperty("success")){t===!0||t.success?R("api reachable",n.json,n.noColor):b("api unreachable",n.json,n.noColor);return}if(n.json){console.log(JSON.stringify(t,null,2)),console.log();return}for(let[i,s]of Object.entries(Yt))if(t[i]){await s(t,e,n.json,n.noColor);return}R("success",n.json,n.noColor)}u.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(We.version,"--version","Show version information").option("--api-key <key>","API key for authenticated deployments").option("--deploy-token <token>","Deploy token for single-use deployments").option("--config <file>","Custom config file path").option("--api-url <url>","API URL (for development)").option("--json","Output results in JSON format").option("--no-color","Disable colored output").option("--help","Display help for command").helpOption(!1);u.hook("preAction",(t,e)=>{let o=t.opts();if(o.help){let n=o.color===!1||o.noColor;j(n),process.exit(0)}});u.hook("preAction",(t,e)=>{let o=t.opts();try{o.apiKey&&typeof o.apiKey=="string"&&(0,U.validateApiKey)(o.apiKey),o.deployToken&&typeof o.deployToken=="string"&&(0,U.validateDeployToken)(o.deployToken),o.apiUrl&&typeof o.apiUrl=="string"&&(0,U.validateApiUrl)(o.apiUrl)}catch(n){if(n instanceof $.ShipError){let i=o.color===!1||o.noColor;b(n.message,o.json,i),process.exit(1)}throw n}});u.command("ping").description("Check API connectivity").action(P(t=>t.ping()));u.command("whoami").description("Get current account information").action(P(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var Pe=u.command("deployments").description("Manage deployments").action((...t)=>{let e=V(u),o=t[t.length-1];if(o&&o.args&&o.args.length>0){let n=o.args.find(i=>!["list","create","get","remove"].includes(i));n&&b(`unknown command '${n}'`,e.json,e.noColor)}j(e.noColor),process.exit(1)});Pe.command("list").description("List all deployments").action(P(t=>t.deployments.list()));Pe.command("create <path>").description("Create deployment from file or directory").option("--tag <tag>","Tag to add (can be repeated)",Ze,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(P(function(t,e,o){return Ct(t,e,o,this)},{operation:"create"}));Pe.command("get <deployment>").description("Show deployment information").action(P((t,e)=>t.deployments.get(e),{operation:"get",resourceType:"Deployment",getResourceId:t=>t}));Pe.command("remove <deployment>").description("Delete deployment permanently").action(P((t,e)=>t.deployments.remove(e),{operation:"remove",resourceType:"Deployment",getResourceId:t=>t}));var le=u.command("domains").description("Manage domains").action((...t)=>{let e=V(u),o=t[t.length-1];if(o&&o.args&&o.args.length>0){let n=o.args.find(i=>!["list","get","set","remove"].includes(i));n&&b(`unknown command '${n}'`,e.json,e.noColor)}j(e.noColor),process.exit(1)});le.command("list").description("List all domains").action(P(t=>t.domains.list()));le.command("get <name>").description("Show domain information").action(P((t,e)=>t.domains.get(e),{operation:"get",resourceType:"Domain",getResourceId:t=>t}));le.command("confirm <name>").description("Trigger DNS confirmation for external domain").action(P((t,e)=>t.domains.confirm(e),{operation:"confirm",resourceType:"Domain",getResourceId:t=>t}));le.command("set <name> <deployment>").description("Create or update domain pointing to deployment").option("--tag <tag>","Tag to add (can be repeated)",Ze,[]).action(P((t,e,o,n)=>{let i=n?.tag&&n.tag.length>0?n.tag:void 0;return t.domains.set(e,o,i)},{operation:"set",resourceType:"Domain",getResourceId:t=>t}));le.command("remove <name>").description("Delete domain permanently").action(P((t,e)=>t.domains.remove(e),{operation:"remove",resourceType:"Domain",getResourceId:t=>t}));var Xe=u.command("tokens").description("Manage deploy tokens").action((...t)=>{let e=V(u),o=t[t.length-1];if(o&&o.args&&o.args.length>0){let n=o.args.find(i=>!["list","create","remove"].includes(i));n&&b(`unknown command '${n}'`,e.json,e.noColor)}j(e.noColor),process.exit(1)});Xe.command("list").description("List all tokens").action(P(t=>t.tokens.list()));Xe.command("create").description("Create a new deploy token").option("--ttl <seconds>","Time to live in seconds (default: never expires)",parseInt).option("--tag <tag>","Tag to add (can be repeated)",Ze,[]).action(P((t,e)=>{let o=e?.ttl,n=e?.tag&&e.tag.length>0?e.tag:void 0;return t.tokens.create(o,n)},{operation:"create",resourceType:"Token"}));Xe.command("remove <token>").description("Delete token permanently").action(P((t,e)=>t.tokens.remove(e),{operation:"remove",resourceType:"Token",getResourceId:t=>t}));var Xt=u.command("account").description("Manage account").action((...t)=>{let e=V(u),o=t[t.length-1];if(o&&o.args&&o.args.length>0){let n=o.args.find(i=>!["get"].includes(i));n&&b(`unknown command '${n}'`,e.json,e.noColor)}j(e.noColor),process.exit(1)});Xt.command("get").description("Show account information").action(P(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var Tt=u.command("completion").description("Setup shell completion").action((...t)=>{let e=V(u),o=t[t.length-1];if(o&&o.args&&o.args.length>0){let n=o.args.find(i=>!["install","uninstall"].includes(i));n&&b(`unknown command '${n}'`,e.json,e.noColor)}j(e.noColor),process.exit(1)});Tt.command("install").description("Install shell completion script").action(async()=>{let t=process.env.SHELL||"",e=Ye.homedir(),o,n,i="",s=D.resolve(__dirname,"completions/ship.bash"),r=D.resolve(__dirname,"completions/ship.zsh"),a=D.resolve(__dirname,"completions/ship.fish");try{if(t.includes("bash"))o=D.join(e,".ship_completion.bash"),n=D.join(e,".bash_profile"),i=`# ship
57
57
  source '${o}'
58
- # ship end`,S.copyFileSync(s,o);else if(t.includes("zsh"))o=C.join(e,".ship_completion.zsh"),n=C.join(e,".zshrc"),i=`# ship
58
+ # ship end`,S.copyFileSync(s,o);else if(t.includes("zsh"))o=D.join(e,".ship_completion.zsh"),n=D.join(e,".zshrc"),i=`# ship
59
59
  source '${o}'
60
- # ship end`,S.copyFileSync(r,o);else if(t.includes("fish")){let m=C.join(e,".config/fish/completions");S.existsSync(m)||S.mkdirSync(m,{recursive:!0}),o=C.join(m,"ship.fish"),S.copyFileSync(a,o);let l=u.opts();A("fish completion installed successfully",l.json,l.noColor),ae("please restart your shell to apply the changes",l.json,l.noColor);return}else{let m=u.opts();E(`unsupported shell: ${t}. could not install completion script`,m.json,m.noColor);return}if(S.existsSync(n)){let m=S.readFileSync(n,"utf-8");if(!m.includes("# ship")||!m.includes("# ship end")){let h=m.length>0&&!m.endsWith(`
60
+ # ship end`,S.copyFileSync(r,o);else if(t.includes("fish")){let m=D.join(e,".config/fish/completions");S.existsSync(m)||S.mkdirSync(m,{recursive:!0}),o=D.join(m,"ship.fish"),S.copyFileSync(a,o);let l=u.opts();R("fish completion installed successfully",l.json,l.noColor),ae("please restart your shell to apply the changes",l.json,l.noColor);return}else{let m=u.opts();b(`unsupported shell: ${t}. could not install completion script`,m.json,m.noColor);return}if(S.existsSync(n)){let m=S.readFileSync(n,"utf-8");if(!m.includes("# ship")||!m.includes("# ship end")){let h=m.length>0&&!m.endsWith(`
61
61
  `)?`
62
- `:"";S.appendFileSync(n,h+i)}}else S.writeFileSync(n,i);let c=u.opts();A(`completion script installed for ${t.split("/").pop()}`,c.json,c.noColor),ee(`run "source ${n}" or restart your shell`,c.json,c.noColor)}catch(p){let c=u.opts();E(`could not install completion script: ${p.message}`,c.json,c.noColor),(t.includes("bash")||t.includes("zsh"))&&ee(`add the following line to your profile file manually
63
- ${i}`,c.json,c.noColor)}});Tt.command("uninstall").description("Uninstall shell completion script").action(async()=>{let t=process.env.SHELL||"",e=Ye.homedir(),o,n;try{if(t.includes("bash"))o=C.join(e,".ship_completion.bash"),n=C.join(e,".bash_profile");else if(t.includes("zsh"))o=C.join(e,".ship_completion.zsh"),n=C.join(e,".zshrc");else if(t.includes("fish")){let i=C.join(e,".config/fish/completions");o=C.join(i,"ship.fish");let s=u.opts();S.existsSync(o)?(S.unlinkSync(o),A("fish completion uninstalled successfully",s.json,s.noColor)):ee("fish completion was not installed",s.json,s.noColor),ae("please restart your shell to apply the changes",s.json,s.noColor);return}else{let i=u.opts();E(`unsupported shell: ${t}. could not uninstall completion script`,i.json,i.noColor);return}if(S.existsSync(o)&&S.unlinkSync(o),S.existsSync(n)){let i=S.readFileSync(n,"utf-8"),s=i.split(`
62
+ `:"";S.appendFileSync(n,h+i)}}else S.writeFileSync(n,i);let c=u.opts();R(`completion script installed for ${t.split("/").pop()}`,c.json,c.noColor),ee(`run "source ${n}" or restart your shell`,c.json,c.noColor)}catch(p){let c=u.opts();b(`could not install completion script: ${p.message}`,c.json,c.noColor),(t.includes("bash")||t.includes("zsh"))&&ee(`add the following line to your profile file manually
63
+ ${i}`,c.json,c.noColor)}});Tt.command("uninstall").description("Uninstall shell completion script").action(async()=>{let t=process.env.SHELL||"",e=Ye.homedir(),o,n;try{if(t.includes("bash"))o=D.join(e,".ship_completion.bash"),n=D.join(e,".bash_profile");else if(t.includes("zsh"))o=D.join(e,".ship_completion.zsh"),n=D.join(e,".zshrc");else if(t.includes("fish")){let i=D.join(e,".config/fish/completions");o=D.join(i,"ship.fish");let s=u.opts();S.existsSync(o)?(S.unlinkSync(o),R("fish completion uninstalled successfully",s.json,s.noColor)):ee("fish completion was not installed",s.json,s.noColor),ae("please restart your shell to apply the changes",s.json,s.noColor);return}else{let i=u.opts();b(`unsupported shell: ${t}. could not uninstall completion script`,i.json,i.noColor);return}if(S.existsSync(o)&&S.unlinkSync(o),S.existsSync(n)){let i=S.readFileSync(n,"utf-8"),s=i.split(`
64
64
  `),r=[],a=0,p=!1;for(;a<s.length;){let m=s[a];if(m.trim()==="# ship"){for(p=!0,a++;a<s.length&&s[a].trim()!=="# ship end";)a++;a<s.length&&s[a].trim()==="# ship end"&&a++}else r.push(m),a++}let c=u.opts();if(p){let m=i.endsWith(`
65
65
  `),l;r.length===0?l="":m?l=r.join(`
66
66
  `)+`
67
67
  `:l=r.join(`
68
- `),S.writeFileSync(n,l),A(`completion script uninstalled for ${t.split("/").pop()}`,c.json,c.noColor),ee(`run "source ${n}" or restart your shell`,c.json,c.noColor)}else E("completion was not found in profile",c.json,c.noColor)}else{let i=u.opts();E("profile file not found",i.json,i.noColor)}}catch(i){let s=u.opts();E(`could not uninstall completion script: ${i.message}`,s.json,s.noColor)}});u.argument("[path]","Path to deploy").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(x(async function(t,e,o){if(!e){let n=u.opts(),i=n.color===!1||n.noColor;M(i),process.exit(0)}if(!e.includes("/")&&!e.startsWith(".")&&!e.startsWith("~"))throw $.ShipError.validation(`unknown command '${e}'`);return vt(t,e,o,this)},{operation:"create"}));function Xt(){let t=process.argv,e=t.includes("--compbash"),o=t.includes("--compzsh"),n=t.includes("--compfish");if(!e&&!o&&!n)return;console.log(["ping","whoami","deployments","domains","account","completion"].join(n?`
69
- `:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&Xt();if(process.env.NODE_ENV!=="test")try{u.parse(process.argv)}catch(t){throw t.code&&t.code.startsWith("commander.")&&process.exit(t.exitCode||1),t}
68
+ `),S.writeFileSync(n,l),R(`completion script uninstalled for ${t.split("/").pop()}`,c.json,c.noColor),ee(`run "source ${n}" or restart your shell`,c.json,c.noColor)}else b("completion was not found in profile",c.json,c.noColor)}else{let i=u.opts();b("profile file not found",i.json,i.noColor)}}catch(i){let s=u.opts();b(`could not uninstall completion script: ${i.message}`,s.json,s.noColor)}});u.argument("[path]","Path to deploy").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(P(async function(t,e,o){if(!e){let n=u.opts(),i=n.color===!1||n.noColor;j(i),process.exit(0)}if(!e.includes("/")&&!e.startsWith(".")&&!e.startsWith("~"))throw $.ShipError.validation(`unknown command '${e}'`);return Ct(t,e,o,this)},{operation:"create"}));function Qt(){let t=process.argv,e=t.includes("--compbash"),o=t.includes("--compzsh"),n=t.includes("--compfish");if(!e&&!o&&!n)return;console.log(["ping","whoami","deployments","domains","account","completion"].join(n?`
69
+ `:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&Qt();if(process.env.NODE_ENV!=="test")try{u.parse(process.argv)}catch(t){throw t.code&&t.code.startsWith("commander.")&&process.exit(t.exitCode||1),t}
70
70
  //# sourceMappingURL=cli.cjs.map