@shipstatic/ship 0.6.4 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -1,42 +1,42 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var wt=Object.create;var de=Object.defineProperty;var Et=Object.getOwnPropertyDescriptor;var Tt=Object.getOwnPropertyNames;var xt=Object.getPrototypeOf,At=Object.prototype.hasOwnProperty;var k=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ot=(t,e)=>{for(var n in e)de(t,n,{get:e[n],enumerable:!0})},kt=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Tt(e))!At.call(t,i)&&i!==n&&de(t,i,{get:()=>e[i],enumerable:!(o=Et(e,i))||o.enumerable});return t};var E=(t,e,n)=>(n=t!=null?wt(xt(t)):{},kt(e||!t||!t.__esModule?de(n,"default",{value:t,enumerable:!0}):n,t));function A(t){return t!==null&&typeof t=="object"&&"name"in t&&t.name==="ShipError"&&"status"in t}function ge(t){let e=t.lastIndexOf(".");if(e===-1||e===t.length-1)return!1;let n=t.slice(e+1).toLowerCase();return Rt.has(n)}function Q(t){if(!t.startsWith(N))throw l.validation(`API key must start with "${N}"`);if(t.length!==Ae)throw l.validation(`API key must be ${Ae} characters total (${N} + ${fe} hex chars)`);let e=t.slice(N.length);if(!/^[a-f0-9]{64}$/i.test(e))throw l.validation(`API key must contain ${fe} hexadecimal characters after "${N}" prefix`)}function ke(t){if(!t.startsWith(_))throw l.validation(`Deploy token must start with "${_}"`);if(t.length!==Oe)throw l.validation(`Deploy token must be ${Oe} characters total (${_} + ${he} hex chars)`);let e=t.slice(_.length);if(!/^[a-f0-9]{64}$/i.test(e))throw l.validation(`Deploy token must contain ${he} hexadecimal characters after "${_}" prefix`)}function Re(t){try{let e=new URL(t);if(!["http:","https:"].includes(e.protocol))throw l.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw l.validation("API URL must not contain a path");if(e.search||e.hash)throw l.validation("API URL must not contain query parameters or fragments")}catch(e){throw A(e)?e:l.validation("API URL must be a valid URL")}}var g,me,l,Rt,N,fe,Ae,_,he,Oe,ye,U,C=k(()=>{"use strict";(function(t){t.Validation="validation_failed",t.NotFound="not_found",t.RateLimit="rate_limit_exceeded",t.Authentication="authentication_failed",t.Business="business_logic_error",t.Api="internal_server_error",t.Network="network_error",t.Cancelled="operation_cancelled",t.File="file_error",t.Config="config_error"})(g||(g={}));me={client:new Set([g.Business,g.Config,g.File,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},l=class t extends Error{type;status;details;constructor(e,n,o,i){super(n),this.type=e,this.status=o,this.details=i,this.name="ShipError"}toResponse(){let e=this.type===g.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static fromResponse(e){return new t(e.error,e.message,e.status,e.details)}static validation(e,n){return new t(g.Validation,e,400,n)}static notFound(e,n){let o=n?`${e} ${n} not found`:`${e} not found`;return new t(g.NotFound,o,404)}static rateLimit(e="Too many requests"){return new t(g.RateLimit,e,429)}static authentication(e="Authentication required",n){return new t(g.Authentication,e,401,n)}static business(e,n=400){return new t(g.Business,e,n)}static network(e,n){return new t(g.Network,e,void 0,{cause:n})}static cancelled(e){return new t(g.Cancelled,e)}static file(e,n){return new t(g.File,e,void 0,{filePath:n})}static config(e,n){return new t(g.Config,e,void 0,n)}static api(e,n=500){return new t(g.Api,e,n)}static database(e,n=500){return new t(g.Api,e,n)}static storage(e,n=500){return new t(g.Api,e,n)}get filePath(){return this.details?.filePath}isClientError(){return me.client.has(this.type)}isNetworkError(){return me.network.has(this.type)}isAuthError(){return me.auth.has(this.type)}isValidationError(){return this.type===g.Validation}isFileError(){return this.type===g.File}isConfigError(){return this.type===g.Config}isType(e){return this.type===e}};Rt=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);N="ship-",fe=64,Ae=N.length+fe,_="token-",he=64,Oe=_.length+he,ye="ship.json";U="https://api.shipstatic.com"});function Ie(t){Se=t}function te(){if(Se===null)throw l.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return Se}var Se,ne=k(()=>{"use strict";C();Se=null});function Ft(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function I(){return Pe||Ft()}var Pe,V=k(()=>{"use strict";Pe=null});async function Pt(t){let e=(await import("spark-md5")).default;return new Promise((n,o)=>{let s=Math.ceil(t.size/2097152),r=0,p=new e.ArrayBuffer,a=new FileReader,c=()=>{let u=r*2097152,d=Math.min(u+2097152,t.size);a.readAsArrayBuffer(t.slice(u,d))};a.onload=u=>{let d=u.target?.result;if(!d){o(l.business("Failed to read file chunk"));return}p.append(d),r++,r<s?c():n({md5:p.end()})},a.onerror=()=>{o(l.business("Failed to calculate MD5: FileReader error"))},c()})}async function $t(t){let e=await import("crypto");if(Buffer.isBuffer(t)){let o=e.createHash("md5");return o.update(t),{md5:o.digest("hex")}}let n=await import("fs");return new Promise((o,i)=>{let s=e.createHash("md5"),r=n.createReadStream(t);r.on("error",p=>i(l.business(`Failed to read file for MD5: ${p.message}`))),r.on("data",p=>s.update(p)),r.on("end",()=>o({md5:s.digest("hex")}))})}async function oe(t){let e=I();if(e==="browser"){if(!(t instanceof Blob))throw l.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Pt(t)}if(e==="node"){if(!(Buffer.isBuffer(t)||typeof t=="string"))throw l.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return $t(t)}throw l.business("Unknown or unsupported execution environment for MD5 calculation.")}var be=k(()=>{"use strict";V();C()});function ze(t){return!t||t.length===0?[]:t.filter(e=>{if(!e)return!1;let n=e.replace(/\\/g,"/").split("/").filter(Boolean);if(n.length===0)return!0;let o=n[n.length-1];if((0,Be.isJunk)(o))return!1;for(let s of n)if(s!==".well-known"&&(s.startsWith(".")||s.length>255))return!1;let i=n.slice(0,-1);for(let s of i)if(Ut.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var Be,Ut,Ge=k(()=>{"use strict";Be=require("junk"),Ut=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function He(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 n=e.map(s=>s.split("/").filter(Boolean)),o=[],i=Math.min(...n.map(s=>s.length));for(let s=0;s<i;s++){let r=n[0][s];if(n.every(p=>p[s]===r))o.push(r);else break}return o.join("/")}function se(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ve=k(()=>{"use strict"});function Ve(t,e={}){if(e.flatten===!1)return t.map(o=>({path:se(o),name:we(o)}));let n=Kt(t);return t.map(o=>{let i=se(o);if(n){let s=n.endsWith("/")?n:`${n}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=we(o)),{path:i,name:we(o)}})}function Kt(t){if(!t.length)return"";let n=t.map(s=>se(s)).map(s=>s.split("/")),o=[],i=Math.min(...n.map(s=>s.length));for(let s=0;s<i-1;s++){let r=n[0][s];if(n.every(p=>p[s]===r))o.push(r);else break}return o.join("/")}function we(t){return t.split(/[/\\]/).pop()||t}var qe=k(()=>{"use strict";ve()});function Je(t){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(t))return{valid:!1,reason:"File name contains unsafe characters"};if(t.startsWith(" ")||t.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(t.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let n=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,o=t.split("/").pop()||t;return n.test(o)?{valid:!1,reason:"File name uses a reserved system name"}:t.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}var We=k(()=>{"use strict";C()});function Ye(t,e){if(t.includes("\0")||t.includes("/../")||t.startsWith("../")||t.endsWith("/.."))throw l.business(`Security error: Unsafe file path "${t}" for file: ${e}`)}function Xe(t,e){let n=Je(t);if(!n.valid)throw l.business(n.reason||"Invalid file name");if(ge(t))throw l.business(`File extension not allowed: "${e}"`)}var Ze=k(()=>{"use strict";C();We()});var et={};Ot(et,{processFilesForNode:()=>jt});function Qe(t,e=new Set){let n=[],o=O.realpathSync(t);if(e.has(o))return n;e.add(o);let i=O.readdirSync(t);for(let s of i){let r=x.join(t,s),p=O.statSync(r);if(p.isDirectory()){let a=Qe(r,e);n.push(...a)}else p.isFile()&&n.push(r)}return n}async function jt(t,e={}){if(I()!=="node")throw l.business("processFilesForNode can only be called in Node.js environment.");let n=t.flatMap(f=>{let b=x.resolve(f);try{return O.statSync(b).isDirectory()?Qe(b):[b]}catch{throw l.file(`Path does not exist: ${f}`,f)}}),o=[...new Set(n)],i=ze(o);if(i.length===0)return[];let s=t.map(f=>x.resolve(f)),r=He(s.map(f=>{try{return O.statSync(f).isDirectory()?f:x.dirname(f)}catch{return x.dirname(f)}})),p=i.map(f=>{if(r&&r.length>0){let b=x.relative(r,f);if(b&&typeof b=="string"&&!b.startsWith(".."))return b.replace(/\\/g,"/")}return x.basename(f)}),a=Ve(p,{flatten:e.pathDetect!==!1}),c=[],u=0,d=te();for(let f=0;f<i.length;f++){let b=i[f],G=a[f].path;try{Ye(G,b);let R=O.statSync(b);if(R.size===0)continue;if(Xe(G,b),R.size>d.maxFileSize)throw l.business(`File ${b} is too large. Maximum allowed size is ${d.maxFileSize/(1024*1024)}MB.`);if(u+=R.size,u>d.maxTotalSize)throw l.business(`Total deploy size is too large. Maximum allowed is ${d.maxTotalSize/(1024*1024)}MB.`);let H=O.readFileSync(b),{md5:vt}=await oe(H);c.push({path:G,content:H,size:H.length,md5:vt})}catch(R){if(A(R))throw R;let H=R instanceof Error?R.message:String(R);throw l.file(`Failed to read file "${b}": ${H}`,b)}}if(c.length>d.maxFilesCount)throw l.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return c}var O,x,tt=k(()=>{"use strict";V();be();Ge();Ze();C();ne();qe();ve();O=E(require("fs"),1),x=E(require("path"),1)});var St=require("commander");C();var ee=class{constructor(){this.handlers=new Map}on(e,n){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(n)}off(e,n){let o=this.handlers.get(e);o&&(o.delete(n),o.size===0&&this.handlers.delete(e))}emit(e,...n){let o=this.handlers.get(e);if(!o)return;let i=Array.from(o);for(let s of i)try{s(...n)}catch(r){o.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((n,o)=>{n.forEach(i=>{e.on(o,i)})})}clear(){this.handlers.clear()}};var S={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},It=3e4,K=class extends ee{constructor(e){super(),this.apiUrl=e.apiUrl||U,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??It,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,n,o){let i=this.mergeHeaders(n.headers),{signal:s,cleanup:r}=this.createTimeoutSignal(n.signal),p={...n,headers:i,credentials:i.Authorization?void 0:"include",signal:s};this.emit("request",e,p);try{let a=await fetch(e,p);return r(),a.ok||await this.handleResponseError(a,o),this.emit("response",this.safeClone(a),e),{data:await this.parseResponse(this.safeClone(a)),status:a.status}}catch(a){r();let c=a instanceof Error?a:new Error(String(a));this.emit("error",c,e),this.handleFetchError(a,o)}}async request(e,n,o){let{data:i}=await this.executeRequest(e,n,o);return i}async requestWithStatus(e,n,o){return this.executeRequest(e,n,o)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let n=new AbortController,o=setTimeout(()=>n.abort(),this.timeout);if(e){let i=()=>n.abort();e.addEventListener("abort",i),e.aborted&&n.abort()}return{signal:n.signal,cleanup:()=>clearTimeout(o)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,n){let o={};try{if(e.headers.get("content-type")?.includes("application/json")){let r=await e.json();if(r&&typeof r=="object"){let p=r;typeof p.message=="string"&&(o.message=p.message),typeof p.error=="string"&&(o.error=p.error)}}else o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}let i=o.message||o.error||`${n} failed`;throw e.status===401?l.authentication(i):l.api(i,e.status)}handleFetchError(e,n){throw A(e)?e:e instanceof Error&&e.name==="AbortError"?l.cancelled(`${n} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?l.network(`${n} failed: ${e.message}`,e):e instanceof Error?l.business(`${n} failed: ${e.message}`):l.business(`${n} failed: Unknown error`)}async deploy(e,n={}){if(!e.length)throw l.business("No files to deploy");for(let r of e)if(!r.md5)throw l.file(`MD5 checksum missing for file: ${r.path}`,r.path);let{body:o,headers:i}=await this.createDeployBody(e,n.labels,n.via),s={};return n.deployToken?s.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(s.Authorization=`Bearer ${n.apiKey}`),n.caller&&(s["X-Caller"]=n.caller),this.request(`${n.apiUrl||this.apiUrl}${S.DEPLOYMENTS}`,{method:"POST",body:o,headers:{...i,...s},signal:n.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,n){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:n})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,n,o){let i={};n&&(i.deployment=n),o!==void 0&&(i.labels=o);let{data:s,status:r}=await this.requestWithStatus(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Set domain");return{...s,isCreate:r===201}}async listDomains(){return this.request(`${this.apiUrl}${S.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${S.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,n){let o={};return e!==void 0&&(o.ttl=e),n!==void 0&&(o.labels=n),this.request(`${this.apiUrl}${S.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${S.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${S.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${S.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${S.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${S.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e){let n=e.find(r=>r.path==="index.html"||r.path==="/index.html");if(!n||n.size>100*1024)return!1;let o;if(typeof Buffer<"u"&&Buffer.isBuffer(n.content))o=n.content.toString("utf-8");else if(typeof Blob<"u"&&n.content instanceof Blob)o=await n.content.text();else if(typeof File<"u"&&n.content instanceof File)o=await n.content.text();else return!1;let i={files:e.map(r=>r.path),index:o};return(await this.request(`${this.apiUrl}${S.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA check")).isSPA}};C();ne();C();C();function De(t={},e={}){let n={apiUrl:t.apiUrl||e.apiUrl||U,apiKey:t.apiKey!==void 0?t.apiKey:e.apiKey,deployToken:t.deployToken!==void 0?t.deployToken:e.deployToken},o={apiUrl:n.apiUrl};return n.apiKey!==void 0&&(o.apiKey=n.apiKey),n.deployToken!==void 0&&(o.deployToken=n.deployToken),o}function Fe(t,e){let n={...t};return n.apiUrl===void 0&&e.apiUrl!==void 0&&(n.apiUrl=e.apiUrl),n.apiKey===void 0&&e.apiKey!==void 0&&(n.apiKey=e.apiKey),n.deployToken===void 0&&e.deployToken!==void 0&&(n.deployToken=e.deployToken),n.timeout===void 0&&e.timeout!==void 0&&(n.timeout=e.timeout),n.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(n.maxConcurrency=e.maxConcurrency),n.onProgress===void 0&&e.onProgress!==void 0&&(n.onProgress=e.onProgress),n.caller===void 0&&e.caller!==void 0&&(n.caller=e.caller),n}C();be();async function Lt(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),n;typeof Buffer<"u"?n=Buffer.from(e,"utf-8"):n=new Blob([e],{type:"application/json"});let{md5:o}=await oe(n);return{path:ye,content:n,size:e.length,md5:o}}async function $e(t,e,n){if(n.spaDetect===!1||t.some(o=>o.path===ye))return t;try{if(await e.checkSPA(t)){let i=await Lt();return[...t,i]}}catch{}return t}function Le(t){let{getApi:e,ensureInit:n,processInput:o,clientDefaults:i,hasAuth:s}=t;return{create:async(r,p={})=>{await n();let a=i?Fe(p,i):p;if(s&&!s()&&!a.deployToken&&!a.apiKey)throw l.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!o)throw l.config("processInput function is not provided.");let c=e(),u=await o(r,a);return u=await $e(u,c,a),c.deploy(u,a)},list:async()=>(await n(),e().listDeployments()),get:async r=>(await n(),e().getDeployment(r)),set:async(r,p)=>(await n(),e().updateDeploymentLabels(r,p.labels)),remove:async r=>{await n(),await e().removeDeployment(r)}}}function Ne(t){let{getApi:e,ensureInit:n}=t;return{set:async(o,i={})=>(await n(),e().setDomain(o,i.deployment,i.labels)),list:async()=>(await n(),e().listDomains()),get:async o=>(await n(),e().getDomain(o)),remove:async o=>{await n(),await e().removeDomain(o)},verify:async o=>(await n(),e().verifyDomain(o)),validate:async o=>(await n(),e().validateDomain(o)),dns:async o=>(await n(),e().getDomainDns(o)),records:async o=>(await n(),e().getDomainRecords(o)),share:async o=>(await n(),e().getDomainShare(o))}}function _e(t){let{getApi:e,ensureInit:n}=t;return{get:async()=>(await n(),e().getAccount())}}function Ue(t){let{getApi:e,ensureInit:n}=t;return{create:async(o={})=>(await n(),e().createToken(o.ttl,o.labels)),list:async()=>(await n(),e().listTokens()),remove:async o=>{await n(),await e().removeToken(o)}}}var ie=class{constructor(e={}){this.initPromise=null;this._config=null;this.auth=null;this.clientOptions=e,e.deployToken?this.auth={type:"token",value:e.deployToken}:e.apiKey&&(this.auth={type:"apiKey",value:e.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let n=this.resolveInitialConfig(e);this.http=new K({...e,...n,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let o={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=Le({...o,processInput:(i,s)=>this.processInput(i,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=Ne(o),this._account=_e(o),this._tokens=Ue(o)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,n){return this.deployments.create(e,n)}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=te(),this._config)}on(e,n){this.http.on(e,n)}off(e,n){this.http.off(e,n)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(n){console.warn("Event transfer failed during client replacement:",n)}this.http=e}setDeployToken(e){if(!e||typeof e!="string")throw l.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw l.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};C();V();var j=require("zod");C();V();var Ce="ship",Nt=j.z.object({apiUrl:j.z.string().url().optional(),apiKey:j.z.string().optional(),deployToken:j.z.string().optional()}).strict();function Ke(t){try{return Nt.parse(t)}catch(e){if(e instanceof j.z.ZodError){let n=e.issues[0],o=n.path.length>0?` at ${n.path.join(".")}`:"";throw l.config(`Configuration validation failed${o}: ${n.message}`)}throw l.config("Configuration validation failed")}}async function _t(t){try{if(I()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),n=await import("os"),o=e(Ce,{searchPlaces:[`.${Ce}rc`,"package.json",`${n.homedir()}/.${Ce}rc`],stopDir:n.homedir()}),i;if(t?i=o.load(t):i=o.search(),i&&i.config)return Ke(i.config)}catch(e){if(A(e))throw e}return{}}async function je(t){if(I()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},n=await _t(t),o={apiUrl:e.apiUrl??n.apiUrl,apiKey:e.apiKey??n.apiKey,deployToken:e.deployToken??n.deployToken};return Ke(o)}ne();C();async function Me(t,e,n){let{FormData:o,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new o,p=[];for(let d of t){if(!Buffer.isBuffer(d.content)&&!(typeof Blob<"u"&&d.content instanceof Blob))throw l.file(`Unsupported file.content type for Node.js: ${d.path}`,d.path);if(!d.md5)throw l.file(`File missing md5 checksum: ${d.path}`,d.path);let f=new i([d.content],d.path,{type:"application/octet-stream"});r.append("files[]",f),p.push(d.md5)}r.append("checksums",JSON.stringify(p)),e&&e.length>0&&r.append("labels",JSON.stringify(e)),n&&r.append("via",n);let a=new s(r),c=[];for await(let d of a.encode())c.push(Buffer.from(d));let u=Buffer.concat(c);return{body:u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),headers:{"Content-Type":a.contentType,"Content-Length":Buffer.byteLength(u).toString()}}}var re=class extends ie{constructor(e={}){if(I()!=="node")throw l.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return De(e,{})}async loadFullConfig(){try{let e=await je(this.clientOptions.configFile),n=De(this.clientOptions,e);n.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(n.deployToken):n.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(n.apiKey);let o=new K({...this.clientOptions,...n,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(o);let i=await this.http.getConfig();Ie(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,n){let o=typeof e=="string"?[e]:e;if(!Array.isArray(o)||!o.every(s=>typeof s=="string"))throw l.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw l.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(tt(),et));return i(o,n)}getDeployBodyCreator(){return Me}};C();var L=require("fs"),ce=E(require("path"),1);var Ee=E(require("columnify"),1),m=require("yoctocolors"),nt=["isCreate"],v=(t,e,n)=>n?e:t(e),w=(t,e,n)=>{console.log(e?JSON.stringify({success:t},null,2)+`
3
- `:`${v(m.green,t.toLowerCase().replace(/\.$/,""),n)}
4
- `)},T=(t,e,n)=>{if(e)console.error(JSON.stringify({error:t},null,2)+`
5
- `);else{let o=v(s=>(0,m.inverse)((0,m.red)(s)),`${v(m.hidden,"[",n)}error${v(m.hidden,"]",n)}`,n),i=v(m.red,t.toLowerCase().replace(/\.$/,""),n);console.error(`${o} ${i}
6
- `)}},ae=(t,e,n)=>{if(e)console.log(JSON.stringify({warning:t},null,2)+`
7
- `);else{let o=v(s=>(0,m.inverse)((0,m.yellow)(s)),`${v(m.hidden,"[",n)}warning${v(m.hidden,"]",n)}`,n),i=v(m.yellow,t.toLowerCase().replace(/\.$/,""),n);console.log(`${o} ${i}
8
- `)}},M=(t,e,n)=>{if(e)console.log(JSON.stringify({info:t},null,2)+`
9
- `);else{let o=v(s=>(0,m.inverse)((0,m.blue)(s)),`${v(m.hidden,"[",n)}info${v(m.hidden,"]",n)}`,n),i=v(m.blue,t.toLowerCase().replace(/\.$/,""),n);console.log(`${o} ${i}
10
- `)}},Mt=(t,e="details",n)=>{if(t==null||t===0)return"-";let o=new Date(t*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return e==="table"?o.replace(/T/,v(m.hidden,"T",n)).replace(/Z$/,v(m.hidden,"Z",n)):o},ot=(t,e,n="details",o)=>{if(e===null)return"-";if(typeof e=="number"&&(t==="created"||t==="expires"||t==="linked"))return Mt(e,n,o);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)},le=(t,e,n,o)=>{if(!t||t.length===0)return"";let i=t[0],s=e||Object.keys(i).filter(a=>i[a]!==void 0&&!nt.includes(a)),r=t.map(a=>{let c=a,u={};return s.forEach(d=>{d in c&&c[d]!==void 0&&(u[d]=ot(d,c[d],"table",n))}),u});return(0,Ee.default)(r,{columnSplitter:" ",columns:s,config:s.reduce((a,c)=>(a[c]={headingTransform:u=>v(m.dim,o?.[u]||u,n)},a),{})}).split(`
11
- `).map(a=>a.replace(/\0/g,"").replace(/\s+$/,"")).join(`
2
+ "use strict";var wt=Object.create;var ue=Object.defineProperty;var Et=Object.getOwnPropertyDescriptor;var Tt=Object.getOwnPropertyNames;var xt=Object.getPrototypeOf,At=Object.prototype.hasOwnProperty;var R=(e,o)=>()=>(e&&(o=e(e=0)),o);var Ot=(e,o)=>{for(var t in o)ue(e,t,{get:o[t],enumerable:!0})},Rt=(e,o,t,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of Tt(o))!At.call(e,i)&&i!==t&&ue(e,i,{get:()=>o[i],enumerable:!(n=Et(o,i))||n.enumerable});return e};var E=(e,o,t)=>(t=e!=null?wt(xt(e)):{},Rt(o||!e||!e.__esModule?ue(t,"default",{value:e,enumerable:!0}):t,e));function A(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function ge(e){let o=e.lastIndexOf(".");if(o===-1||o===e.length-1)return!1;let t=e.slice(o+1).toLowerCase();return kt.has(t)}function Q(e){if(!e.startsWith(N))throw l.validation(`API key must start with "${N}"`);if(e.length!==Ae)throw l.validation(`API key must be ${Ae} characters total (${N} + ${fe} hex chars)`);let o=e.slice(N.length);if(!/^[a-f0-9]{64}$/i.test(o))throw l.validation(`API key must contain ${fe} hexadecimal characters after "${N}" prefix`)}function Re(e){if(!e.startsWith(_))throw l.validation(`Deploy token must start with "${_}"`);if(e.length!==Oe)throw l.validation(`Deploy token must be ${Oe} characters total (${_} + ${he} hex chars)`);let o=e.slice(_.length);if(!/^[a-f0-9]{64}$/i.test(o))throw l.validation(`Deploy token must contain ${he} hexadecimal characters after "${_}" prefix`)}function ke(e){try{let o=new URL(e);if(!["http:","https:"].includes(o.protocol))throw l.validation("API URL must use http:// or https:// protocol");if(o.pathname!=="/"&&o.pathname!=="")throw l.validation("API URL must not contain a path");if(o.search||o.hash)throw l.validation("API URL must not contain query parameters or fragments")}catch(o){throw A(o)?o:l.validation("API URL must be a valid URL")}}var g,me,l,kt,N,fe,Ae,_,he,Oe,ye,U,C=R(()=>{"use strict";(function(e){e.Validation="validation_failed",e.NotFound="not_found",e.RateLimit="rate_limit_exceeded",e.Authentication="authentication_failed",e.Business="business_logic_error",e.Api="internal_server_error",e.Network="network_error",e.Cancelled="operation_cancelled",e.File="file_error",e.Config="config_error"})(g||(g={}));me={client:new Set([g.Business,g.Config,g.File,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},l=class e extends Error{type;status;details;constructor(o,t,n,i){super(t),this.type=o,this.status=n,this.details=i,this.name="ShipError"}toResponse(){let o=this.type===g.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:o}}static fromResponse(o){return new e(o.error,o.message,o.status,o.details)}static validation(o,t){return new e(g.Validation,o,400,t)}static notFound(o,t){let n=t?`${o} ${t} not found`:`${o} not found`;return new e(g.NotFound,n,404)}static rateLimit(o="Too many requests"){return new e(g.RateLimit,o,429)}static authentication(o="Authentication required",t){return new e(g.Authentication,o,401,t)}static business(o,t=400){return new e(g.Business,o,t)}static network(o,t){return new e(g.Network,o,void 0,{cause:t})}static cancelled(o){return new e(g.Cancelled,o)}static file(o,t){return new e(g.File,o,void 0,{filePath:t})}static config(o,t){return new e(g.Config,o,void 0,t)}static api(o,t=500){return new e(g.Api,o,t)}static database(o,t=500){return new e(g.Api,o,t)}static storage(o,t=500){return new e(g.Api,o,t)}get filePath(){return this.details?.filePath}isClientError(){return me.client.has(this.type)}isNetworkError(){return me.network.has(this.type)}isAuthError(){return me.auth.has(this.type)}isValidationError(){return this.type===g.Validation}isFileError(){return this.type===g.File}isConfigError(){return this.type===g.Config}isType(o){return this.type===o}};kt=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);N="ship-",fe=64,Ae=N.length+fe,_="token-",he=64,Oe=_.length+he,ye="ship.json";U="https://api.shipstatic.com"});function Ie(e){Se=e}function te(){if(Se===null)throw l.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return Se}var Se,oe=R(()=>{"use strict";C();Se=null});function Ft(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function I(){return Pe||Ft()}var Pe,V=R(()=>{"use strict";Pe=null});async function Pt(e){let o=(await import("spark-md5")).default;return new Promise((t,n)=>{let s=Math.ceil(e.size/2097152),r=0,a=new o.ArrayBuffer,p=new FileReader,c=()=>{let d=r*2097152,u=Math.min(d+2097152,e.size);p.readAsArrayBuffer(e.slice(d,u))};p.onload=d=>{let u=d.target?.result;if(!u){n(l.business("Failed to read file chunk"));return}a.append(u),r++,r<s?c():t({md5:a.end()})},p.onerror=()=>{n(l.business("Failed to calculate MD5: FileReader error"))},c()})}async function $t(e){let o=await import("crypto");if(Buffer.isBuffer(e)){let n=o.createHash("md5");return n.update(e),{md5:n.digest("hex")}}let t=await import("fs");return new Promise((n,i)=>{let s=o.createHash("md5"),r=t.createReadStream(e);r.on("error",a=>i(l.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 ne(e){let o=I();if(o==="browser"){if(!(e instanceof Blob))throw l.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Pt(e)}if(o==="node"){if(!(Buffer.isBuffer(e)||typeof e=="string"))throw l.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return $t(e)}throw l.business("Unknown or unsupported execution environment for MD5 calculation.")}var be=R(()=>{"use strict";V();C()});function ze(e){return!e||e.length===0?[]:e.filter(o=>{if(!o)return!1;let t=o.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let n=t[t.length-1];if((0,Be.isJunk)(n))return!1;for(let s of t)if(s!==".well-known"&&(s.startsWith(".")||s.length>255))return!1;let i=t.slice(0,-1);for(let s of i)if(Ut.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var Be,Ut,Ge=R(()=>{"use strict";Be=require("junk"),Ut=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function He(e){if(!e||e.length===0)return"";let o=e.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(o.length===0)return"";if(o.length===1)return o[0];let t=o.map(s=>s.split("/").filter(Boolean)),n=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i;s++){let r=t[0][s];if(t.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function se(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ve=R(()=>{"use strict"});function Ve(e,o={}){if(o.flatten===!1)return e.map(n=>({path:se(n),name:we(n)}));let t=jt(e);return e.map(n=>{let i=se(n);if(t){let s=t.endsWith("/")?t:`${t}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=we(n)),{path:i,name:we(n)}})}function jt(e){if(!e.length)return"";let t=e.map(s=>se(s)).map(s=>s.split("/")),n=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i-1;s++){let r=t[0][s];if(t.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function we(e){return e.split(/[/\\]/).pop()||e}var qe=R(()=>{"use strict";ve()});function Je(e){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(e))return{valid:!1,reason:"File name contains unsafe characters"};if(e.startsWith(" ")||e.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(e.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,n=e.split("/").pop()||e;return t.test(n)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}var We=R(()=>{"use strict";C()});function Ye(e,o){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw l.business(`Security error: Unsafe file path "${e}" for file: ${o}`)}function Xe(e,o){let t=Je(e);if(!t.valid)throw l.business(t.reason||"Invalid file name");if(ge(e))throw l.business(`File extension not allowed: "${o}"`)}var Ze=R(()=>{"use strict";C();We()});var et={};Ot(et,{processFilesForNode:()=>Kt});function Qe(e,o=new Set){let t=[],n=O.realpathSync(e);if(o.has(n))return t;o.add(n);let i=O.readdirSync(e);for(let s of i){let r=x.join(e,s),a=O.statSync(r);if(a.isDirectory()){let p=Qe(r,o);t.push(...p)}else a.isFile()&&t.push(r)}return t}async function Kt(e,o={}){if(I()!=="node")throw l.business("processFilesForNode can only be called in Node.js environment.");let t=e.flatMap(f=>{let b=x.resolve(f);try{return O.statSync(b).isDirectory()?Qe(b):[b]}catch{throw l.file(`Path does not exist: ${f}`,f)}}),n=[...new Set(t)],i=ze(n);if(i.length===0)return[];let s=e.map(f=>x.resolve(f)),r=He(s.map(f=>{try{return O.statSync(f).isDirectory()?f:x.dirname(f)}catch{return x.dirname(f)}})),a=i.map(f=>{if(r&&r.length>0){let b=x.relative(r,f);if(b&&typeof b=="string"&&!b.startsWith(".."))return b.replace(/\\/g,"/")}return x.basename(f)}),p=Ve(a,{flatten:o.pathDetect!==!1}),c=[],d=0,u=te();for(let f=0;f<i.length;f++){let b=i[f],G=p[f].path;try{Ye(G,b);let k=O.statSync(b);if(k.size===0)continue;if(Xe(G,b),k.size>u.maxFileSize)throw l.business(`File ${b} is too large. Maximum allowed size is ${u.maxFileSize/(1024*1024)}MB.`);if(d+=k.size,d>u.maxTotalSize)throw l.business(`Total deploy size is too large. Maximum allowed is ${u.maxTotalSize/(1024*1024)}MB.`);let H=O.readFileSync(b),{md5:vt}=await ne(H);c.push({path:G,content:H,size:H.length,md5:vt})}catch(k){if(A(k))throw k;let H=k instanceof Error?k.message:String(k);throw l.file(`Failed to read file "${b}": ${H}`,b)}}if(c.length>u.maxFilesCount)throw l.business(`Too many files to deploy. Maximum allowed is ${u.maxFilesCount} files.`);return c}var O,x,tt=R(()=>{"use strict";V();be();Ge();Ze();C();oe();qe();ve();O=E(require("fs"),1),x=E(require("path"),1)});var St=require("commander");C();var ee=class{constructor(){this.handlers=new Map}on(o,t){this.handlers.has(o)||this.handlers.set(o,new Set),this.handlers.get(o).add(t)}off(o,t){let n=this.handlers.get(o);n&&(n.delete(t),n.size===0&&this.handlers.delete(o))}emit(o,...t){let n=this.handlers.get(o);if(!n)return;let i=Array.from(n);for(let s of i)try{s(...t)}catch(r){n.delete(s),o!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(o)):this.emit("error",new Error(String(r)),String(o))},0)}}transfer(o){this.handlers.forEach((t,n)=>{t.forEach(i=>{o.on(n,i)})})}clear(){this.handlers.clear()}};var S={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},It=3e4,j=class extends ee{constructor(t){super();this.globalHeaders={};this.apiUrl=t.apiUrl||U,this.getAuthHeadersCallback=t.getAuthHeaders,this.timeout=t.timeout??It,this.createDeployBody=t.createDeployBody}setGlobalHeaders(t){this.globalHeaders=t}transferEventsTo(t){this.transfer(t)}async executeRequest(t,n,i){let s=this.mergeHeaders(n.headers),{signal:r,cleanup:a}=this.createTimeoutSignal(n.signal),p={...n,headers:s,credentials:s.Authorization?void 0:"include",signal:r};this.emit("request",t,p);try{let c=await fetch(t,p);return a(),c.ok||await this.handleResponseError(c,i),this.emit("response",this.safeClone(c),t),{data:await this.parseResponse(this.safeClone(c)),status:c.status}}catch(c){a();let d=c instanceof Error?c:new Error(String(c));this.emit("error",d,t),this.handleFetchError(c,i)}}async request(t,n,i){let{data:s}=await this.executeRequest(t,n,i);return s}async requestWithStatus(t,n,i){return this.executeRequest(t,n,i)}mergeHeaders(t={}){return{...this.globalHeaders,...t,...this.getAuthHeadersCallback()}}createTimeoutSignal(t){let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeout);if(t){let s=()=>n.abort();t.addEventListener("abort",s),t.aborted&&n.abort()}return{signal:n.signal,cleanup:()=>clearTimeout(i)}}safeClone(t){try{return t.clone()}catch{return t}}async parseResponse(t){if(!(t.headers.get("Content-Length")==="0"||t.status===204))return t.json()}async handleResponseError(t,n){let i={};try{if(t.headers.get("content-type")?.includes("application/json")){let a=await t.json();if(a&&typeof a=="object"){let p=a;typeof p.message=="string"&&(i.message=p.message),typeof p.error=="string"&&(i.error=p.error)}}else i={message:await t.text()}}catch{i={message:"Failed to parse error response"}}let s=i.message||i.error||`${n} failed`;throw t.status===401?l.authentication(s):l.api(s,t.status)}handleFetchError(t,n){throw A(t)?t:t instanceof Error&&t.name==="AbortError"?l.cancelled(`${n} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?l.network(`${n} failed: ${t.message}`,t):t instanceof Error?l.business(`${n} failed: ${t.message}`):l.business(`${n} failed: Unknown error`)}async deploy(t,n={}){if(!t.length)throw l.business("No files to deploy");for(let a of t)if(!a.md5)throw l.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:i,headers:s}=await this.createDeployBody(t,n.labels,n.via),r={};return n.deployToken?r.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(r.Authorization=`Bearer ${n.apiKey}`),n.caller&&(r["X-Caller"]=n.caller),this.request(`${n.apiUrl||this.apiUrl}${S.DEPLOYMENTS}`,{method:"POST",body:i,headers:{...s,...r},signal:n.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(t){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(t,n){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:n})},"Update deployment labels")}async removeDeployment(t){await this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove deployment")}async setDomain(t,n,i){let s={};n&&(s.deployment=n),i!==void 0&&(s.labels=i);let{data:r,status:a}=await this.requestWithStatus(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Set domain");return{...r,isCreate:a===201}}async listDomains(){return this.request(`${this.apiUrl}${S.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}`,{method:"GET"},"Get domain")}async removeDomain(t){await this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/share`,{method:"GET"},"Get domain share")}async validateDomain(t){return this.request(`${this.apiUrl}${S.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:t})},"Validate domain")}async createToken(t,n){let i={};return t!==void 0&&(i.ttl=t),n!==void 0&&(i.labels=n),this.request(`${this.apiUrl}${S.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${S.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(t){await this.request(`${this.apiUrl}${S.TOKENS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${S.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${S.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${S.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(t){let n=t.find(a=>a.path==="index.html"||a.path==="/index.html");if(!n||n.size>100*1024)return!1;let i;if(typeof Buffer<"u"&&Buffer.isBuffer(n.content))i=n.content.toString("utf-8");else if(typeof Blob<"u"&&n.content instanceof Blob)i=await n.content.text();else if(typeof File<"u"&&n.content instanceof File)i=await n.content.text();else return!1;let s={files:t.map(a=>a.path),index:i};return(await this.request(`${this.apiUrl}${S.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA check")).isSPA}};C();oe();C();C();function De(e={},o={}){let t={apiUrl:e.apiUrl||o.apiUrl||U,apiKey:e.apiKey!==void 0?e.apiKey:o.apiKey,deployToken:e.deployToken!==void 0?e.deployToken:o.deployToken},n={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(n.apiKey=t.apiKey),t.deployToken!==void 0&&(n.deployToken=t.deployToken),n}function Fe(e,o){let t={...e};return t.apiUrl===void 0&&o.apiUrl!==void 0&&(t.apiUrl=o.apiUrl),t.apiKey===void 0&&o.apiKey!==void 0&&(t.apiKey=o.apiKey),t.deployToken===void 0&&o.deployToken!==void 0&&(t.deployToken=o.deployToken),t.timeout===void 0&&o.timeout!==void 0&&(t.timeout=o.timeout),t.maxConcurrency===void 0&&o.maxConcurrency!==void 0&&(t.maxConcurrency=o.maxConcurrency),t.onProgress===void 0&&o.onProgress!==void 0&&(t.onProgress=o.onProgress),t.caller===void 0&&o.caller!==void 0&&(t.caller=o.caller),t}C();be();async function Lt(){let o=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(o,"utf-8"):t=new Blob([o],{type:"application/json"});let{md5:n}=await ne(t);return{path:ye,content:t,size:o.length,md5:n}}async function $e(e,o,t){if(t.spaDetect===!1||e.some(n=>n.path===ye))return e;try{if(await o.checkSPA(e)){let i=await Lt();return[...e,i]}}catch{}return e}function Le(e){let{getApi:o,ensureInit:t,processInput:n,clientDefaults:i,hasAuth:s}=e;return{upload:async(r,a={})=>{await t();let p=i?Fe(a,i):a;if(s&&!s()&&!p.deployToken&&!p.apiKey)throw l.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw l.config("processInput function is not provided.");let c=o(),d=await n(r,p);return d=await $e(d,c,p),c.deploy(d,p)},list:async()=>(await t(),o().listDeployments()),get:async r=>(await t(),o().getDeployment(r)),set:async(r,a)=>(await t(),o().updateDeploymentLabels(r,a.labels)),remove:async r=>{await t(),await o().removeDeployment(r)}}}function Ne(e){let{getApi:o,ensureInit:t}=e;return{set:async(n,i={})=>(await t(),o().setDomain(n,i.deployment,i.labels)),list:async()=>(await t(),o().listDomains()),get:async n=>(await t(),o().getDomain(n)),remove:async n=>{await t(),await o().removeDomain(n)},verify:async n=>(await t(),o().verifyDomain(n)),validate:async n=>(await t(),o().validateDomain(n)),dns:async n=>(await t(),o().getDomainDns(n)),records:async n=>(await t(),o().getDomainRecords(n)),share:async n=>(await t(),o().getDomainShare(n))}}function _e(e){let{getApi:o,ensureInit:t}=e;return{get:async()=>(await t(),o().getAccount())}}function Ue(e){let{getApi:o,ensureInit:t}=e;return{create:async(n={})=>(await t(),o().createToken(n.ttl,n.labels)),list:async()=>(await t(),o().listTokens()),remove:async n=>{await t(),await o().removeToken(n)}}}var ie=class{constructor(o={}){this.initPromise=null;this._config=null;this.auth=null;this.customHeaders={};this.clientOptions=o,o.deployToken?this.auth={type:"token",value:o.deployToken}:o.apiKey&&(this.auth={type:"apiKey",value:o.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(o);this.http=new j({...o,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=Le({...n,processInput:(i,s)=>this.processInput(i,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=Ne(n),this._account=_e(n),this._tokens=Ue(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(o,t){return this.deployments.upload(o,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=te(),this._config)}on(o,t){this.http.on(o,t)}off(o,t){this.http.off(o,t)}setHeaders(o){this.customHeaders=o,this.http.setGlobalHeaders(o)}clearHeaders(){this.customHeaders={},this.http.setGlobalHeaders({})}replaceHttpClient(o){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(o)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=o,Object.keys(this.customHeaders).length>0&&this.http.setGlobalHeaders(this.customHeaders)}setDeployToken(o){if(!o||typeof o!="string")throw l.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:o}}setApiKey(o){if(!o||typeof o!="string")throw l.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:o}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};C();V();var K=require("zod");C();V();var Ce="ship",Nt=K.z.object({apiUrl:K.z.string().url().optional(),apiKey:K.z.string().optional(),deployToken:K.z.string().optional()}).strict();function je(e){try{return Nt.parse(e)}catch(o){if(o instanceof K.z.ZodError){let t=o.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw l.config(`Configuration validation failed${n}: ${t.message}`)}throw l.config("Configuration validation failed")}}async function _t(e){try{if(I()!=="node")return{};let{cosmiconfigSync:o}=await import("cosmiconfig"),t=await import("os"),n=o(Ce,{searchPlaces:[`.${Ce}rc`,"package.json",`${t.homedir()}/.${Ce}rc`],stopDir:t.homedir()}),i;if(e?i=n.load(e):i=n.search(),i&&i.config)return je(i.config)}catch(o){if(A(o))throw o}return{}}async function Ke(e){if(I()!=="node")return{};let o={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await _t(e),n={apiUrl:o.apiUrl??t.apiUrl,apiKey:o.apiKey??t.apiKey,deployToken:o.deployToken??t.deployToken};return je(n)}oe();C();async function Me(e,o,t){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new n,a=[];for(let u of e){if(!Buffer.isBuffer(u.content)&&!(typeof Blob<"u"&&u.content instanceof Blob))throw l.file(`Unsupported file.content type for Node.js: ${u.path}`,u.path);if(!u.md5)throw l.file(`File missing md5 checksum: ${u.path}`,u.path);let f=new i([u.content],u.path,{type:"application/octet-stream"});r.append("files[]",f),a.push(u.md5)}r.append("checksums",JSON.stringify(a)),o&&o.length>0&&r.append("labels",JSON.stringify(o)),t&&r.append("via",t);let p=new s(r),c=[];for await(let u of p.encode())c.push(Buffer.from(u));let d=Buffer.concat(c);return{body:d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength),headers:{"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(d).toString()}}}var re=class extends ie{constructor(o={}){if(I()!=="node")throw l.business("Node.js Ship class can only be used in Node.js environment.");super(o)}resolveInitialConfig(o){return De(o,{})}async loadFullConfig(){try{let o=await Ke(this.clientOptions.configFile),t=De(this.clientOptions,o);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let n=new j({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();Ie(i)}catch(o){throw this.initPromise=null,o}}async processInput(o,t){let n=typeof o=="string"?[o]:o;if(!Array.isArray(n)||!n.every(s=>typeof s=="string"))throw l.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw l.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(tt(),et));return i(n,t)}getDeployBodyCreator(){return Me}};C();var L=require("fs"),ce=E(require("path"),1);var Ee=E(require("columnify"),1),m=require("yoctocolors"),ot=["isCreate"],v=(e,o,t)=>t?o:e(o),w=(e,o,t)=>{console.log(o?JSON.stringify({success:e},null,2)+`
3
+ `:`${v(m.green,e.toLowerCase().replace(/\.$/,""),t)}
4
+ `)},T=(e,o,t)=>{if(o)console.error(JSON.stringify({error:e},null,2)+`
5
+ `);else{let n=v(s=>(0,m.inverse)((0,m.red)(s)),`${v(m.hidden,"[",t)}error${v(m.hidden,"]",t)}`,t),i=v(m.red,e.toLowerCase().replace(/\.$/,""),t);console.error(`${n} ${i}
6
+ `)}},ae=(e,o,t)=>{if(o)console.log(JSON.stringify({warning:e},null,2)+`
7
+ `);else{let n=v(s=>(0,m.inverse)((0,m.yellow)(s)),`${v(m.hidden,"[",t)}warning${v(m.hidden,"]",t)}`,t),i=v(m.yellow,e.toLowerCase().replace(/\.$/,""),t);console.log(`${n} ${i}
8
+ `)}},M=(e,o,t)=>{if(o)console.log(JSON.stringify({info:e},null,2)+`
9
+ `);else{let n=v(s=>(0,m.inverse)((0,m.blue)(s)),`${v(m.hidden,"[",t)}info${v(m.hidden,"]",t)}`,t),i=v(m.blue,e.toLowerCase().replace(/\.$/,""),t);console.log(`${n} ${i}
10
+ `)}},Mt=(e,o="details",t)=>{if(e==null||e===0)return"-";let n=new Date(e*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return o==="table"?n.replace(/T/,v(m.hidden,"T",t)).replace(/Z$/,v(m.hidden,"Z",t)):n},nt=(e,o,t="details",n)=>{if(o===null)return"-";if(typeof o=="number"&&(e==="created"||e==="activated"||e==="expires"||e==="linked"||e==="grace"))return Mt(o,t,n);if(e==="size"&&typeof o=="number"){let i=o/1048576;return i>=1?`${i.toFixed(1)}Mb`:`${(o/1024).toFixed(1)}Kb`}if(e==="config"){if(typeof o=="boolean")return o?"yes":"no";if(typeof o=="number")return o===1?"yes":"no"}return String(o)},le=(e,o,t,n)=>{if(!e||e.length===0)return"";let i=e[0],s=o||Object.keys(i).filter(p=>i[p]!==void 0&&!ot.includes(p)),r=e.map(p=>{let c=p,d={};return s.forEach(u=>{u in c&&c[u]!==void 0&&(d[u]=nt(u,c[u],"table",t))}),d});return(0,Ee.default)(r,{columnSplitter:" ",columns:s,config:s.reduce((p,c)=>(p[c]={headingTransform:d=>v(m.dim,n?.[d]||d,t)},p),{})}).split(`
11
+ `).map(p=>p.replace(/\0/g,"").replace(/\s+$/,"")).join(`
12
12
  `)+`
13
- `},q=(t,e)=>{let n=Object.entries(t).filter(([s,r])=>nt.includes(s)?!1:r!==void 0);if(n.length===0)return"";let o=n.map(([s,r])=>({property:s+":",value:ot(s,r,"details",e)}));return(0,Ee.default)(o,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>v(m.dim,s,e)}}}).split(`
13
+ `},q=(e,o)=>{let t=Object.entries(e).filter(([s,r])=>ot.includes(s)?!1:r!==void 0);if(t.length===0)return"";let n=t.map(([s,r])=>({property:s+":",value:nt(s,r,"details",o)}));return(0,Ee.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>v(m.dim,s,o)}}}).split(`
14
14
  `).map(s=>s.replace(/\0/g,"")).join(`
15
15
  `)+`
16
- `};function Bt(t,e,n){let{noColor:o}=n;if(t.deployments.length===0){console.log("no deployments found"),console.log();return}let i=["url","labels","created"];console.log(le(t.deployments,i,o,{url:"deployment"}))}function zt(t,e,n){let{noColor:o}=n;if(t.domains.length===0){console.log("no domains found"),console.log();return}let i=["url","deployment","labels","linked","created"];console.log(le(t.domains,i,o,{url:"domain"}))}function Gt(t,e,n){let{noColor:o}=n,{_dnsRecords:i,_shareHash:s,isCreate:r,...p}=t;if(e.operation==="set"){let a=r?"created":"updated";w(`${t.domain} domain ${a}`,!1,o)}i&&i.length>0&&(console.log(),M("DNS Records to configure:",!1,o),i.forEach(a=>{console.log(` ${a.type}: ${a.name} \u2192 ${a.value}`)})),s&&(console.log(),M(`Setup instructions: https://setup.shipstatic.com/${s}/${t.domain}`,!1,o)),console.log(),console.log(q(p,o))}function Ht(t,e,n){let{noColor:o}=n;e.operation==="create"&&w(`${t.deployment} deployment created`,!1,o),console.log(q(t,o))}function Vt(t,e,n){let{noColor:o}=n;console.log(q(t,o))}function qt(t,e,n){let{noColor:o}=n;t.message&&w(t.message,!1,o)}function Jt(t,e,n){let{noColor:o}=n;if(t.valid){if(w("domain is valid",!1,o),console.log(),t.normalized&&console.log(` normalized: ${t.normalized}`),t.available!==null){let i=t.available?"available \u2713":"already taken";console.log(` availability: ${i}`)}console.log()}else T(t.error||"domain is invalid",!1,o)}function Wt(t,e,n){let{noColor:o}=n;if(t.tokens.length===0){console.log("no tokens found"),console.log();return}let i=["token","labels","created","expires"];console.log(le(t.tokens,i,o))}function Yt(t,e,n){let{noColor:o}=n;e.operation==="create"&&t.token&&w(`token ${t.token} created`,!1,o),console.log(q(t,o))}function it(t,e,n){let{json:o,noColor:i}=n;if(t===void 0){e.operation==="remove"&&e.resourceType&&e.resourceId?w(`${e.resourceId} ${e.resourceType.toLowerCase()} removed`,o,i):w("removed successfully",o,i);return}if(typeof t=="boolean"){t?w("api reachable",o,i):T("api unreachable",o,i);return}if(o&&t!==null&&typeof t=="object"){let s={...t};delete s._dnsRecords,delete s._shareHash,delete s.isCreate,console.log(JSON.stringify(s,null,2)),console.log();return}t!==null&&typeof t=="object"?"deployments"in t?Bt(t,e,n):"domains"in t?zt(t,e,n):"tokens"in t?Wt(t,e,n):"domain"in t?Gt(t,e,n):"deployment"in t?Ht(t,e,n):"token"in t?Yt(t,e,n):"email"in t?Vt(t,e,n):"valid"in t?Jt(t,e,n):"message"in t?qt(t,e,n):w("success",o,i):w("success",o,i)}var y=E(require("fs"),1),F=E(require("path"),1),Te=E(require("os"),1);function st(){let t=process.env.SHELL||"";return t.includes("bash")?"bash":t.includes("zsh")?"zsh":t.includes("fish")?"fish":null}function rt(t,e){switch(t){case"bash":return{completionFile:F.join(e,".ship_completion.bash"),profileFile:F.join(e,".bash_profile"),scriptName:"ship.bash"};case"zsh":return{completionFile:F.join(e,".ship_completion.zsh"),profileFile:F.join(e,".zshrc"),scriptName:"ship.zsh"};case"fish":return{completionFile:F.join(e,".config/fish/completions/ship.fish"),profileFile:null,scriptName:"ship.fish"}}}function at(t,e={}){let{json:n,noColor:o}=e,i=st(),s=Te.homedir();if(!i){T(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,n,o);return}let r=rt(i,s),p=F.join(t,r.scriptName);try{if(i==="fish"){let c=F.dirname(r.completionFile);y.existsSync(c)||y.mkdirSync(c,{recursive:!0}),y.copyFileSync(p,r.completionFile),w("fish completion installed successfully",n,o),M("please restart your shell to apply the changes",n,o);return}y.copyFileSync(p,r.completionFile);let a=`# ship
16
+ `};function Bt(e,o,t){let{noColor:n}=t;if(e.deployments.length===0){console.log("no deployments found"),console.log();return}let i=["url","labels","created"];console.log(le(e.deployments,i,n,{url:"deployment"}))}function zt(e,o,t){let{noColor:n}=t;if(e.domains.length===0){console.log("no domains found"),console.log();return}let i=["url","deployment","labels","linked","created"];console.log(le(e.domains,i,n,{url:"domain"}))}function Gt(e,o,t){let{noColor:n}=t,{_dnsRecords:i,_shareHash:s,isCreate:r,...a}=e;if(o.operation==="set"){let p=r?"created":"updated";w(`${e.domain} domain ${p}`,!1,n)}i&&i.length>0&&(console.log(),M("DNS Records to configure:",!1,n),i.forEach(p=>{console.log(` ${p.type}: ${p.name} \u2192 ${p.value}`)})),s&&(console.log(),M(`Setup instructions: https://setup.shipstatic.com/${s}/${e.domain}`,!1,n)),console.log(),console.log(q(a,n))}function Ht(e,o,t){let{noColor:n}=t;o.operation==="upload"&&w(`${e.deployment} deployment uploaded`,!1,n),console.log(q(e,n))}function Vt(e,o,t){let{noColor:n}=t;console.log(q(e,n))}function qt(e,o,t){let{noColor:n}=t;e.message&&w(e.message,!1,n)}function Jt(e,o,t){let{noColor:n}=t;if(e.valid){if(w("domain is valid",!1,n),console.log(),e.normalized&&console.log(` normalized: ${e.normalized}`),e.available!==null){let i=e.available?"available \u2713":"already taken";console.log(` availability: ${i}`)}console.log()}else T(e.error||"domain is invalid",!1,n)}function Wt(e,o,t){let{noColor:n}=t;if(e.tokens.length===0){console.log("no tokens found"),console.log();return}let i=["token","labels","created","expires"];console.log(le(e.tokens,i,n))}function Yt(e,o,t){let{noColor:n}=t;o.operation==="create"&&e.token&&w(`token ${e.token} created`,!1,n),console.log(q(e,n))}function it(e,o,t){let{json:n,noColor:i}=t;if(e===void 0){o.operation==="remove"&&o.resourceType&&o.resourceId?w(`${o.resourceId} ${o.resourceType.toLowerCase()} removed`,n,i):w("removed successfully",n,i);return}if(typeof e=="boolean"){e?w("api reachable",n,i):T("api unreachable",n,i);return}if(n&&e!==null&&typeof e=="object"){let s={...e};delete s._dnsRecords,delete s._shareHash,delete s.isCreate,console.log(JSON.stringify(s,null,2)),console.log();return}e!==null&&typeof e=="object"?"deployments"in e?Bt(e,o,t):"domains"in e?zt(e,o,t):"tokens"in e?Wt(e,o,t):"domain"in e?Gt(e,o,t):"deployment"in e?Ht(e,o,t):"token"in e?Yt(e,o,t):"email"in e?Vt(e,o,t):"valid"in e?Jt(e,o,t):"message"in e?qt(e,o,t):w("success",n,i):w("success",n,i)}var y=E(require("fs"),1),F=E(require("path"),1),Te=E(require("os"),1);function st(){let e=process.env.SHELL||"";return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":null}function rt(e,o){switch(e){case"bash":return{completionFile:F.join(o,".ship_completion.bash"),profileFile:F.join(o,".bash_profile"),scriptName:"ship.bash"};case"zsh":return{completionFile:F.join(o,".ship_completion.zsh"),profileFile:F.join(o,".zshrc"),scriptName:"ship.zsh"};case"fish":return{completionFile:F.join(o,".config/fish/completions/ship.fish"),profileFile:null,scriptName:"ship.fish"}}}function at(e,o={}){let{json:t,noColor:n}=o,i=st(),s=Te.homedir();if(!i){T(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,t,n);return}let r=rt(i,s),a=F.join(e,r.scriptName);try{if(i==="fish"){let c=F.dirname(r.completionFile);y.existsSync(c)||y.mkdirSync(c,{recursive:!0}),y.copyFileSync(a,r.completionFile),w("fish completion installed successfully",t,n),M("please restart your shell to apply the changes",t,n);return}y.copyFileSync(a,r.completionFile);let p=`# ship
17
17
  source '${r.completionFile}'
18
- # ship end`;if(r.profileFile){if(y.existsSync(r.profileFile)){let c=y.readFileSync(r.profileFile,"utf-8");if(!c.includes("# ship")||!c.includes("# ship end")){let u=c.length>0&&!c.endsWith(`
18
+ # ship end`;if(r.profileFile){if(y.existsSync(r.profileFile)){let c=y.readFileSync(r.profileFile,"utf-8");if(!c.includes("# ship")||!c.includes("# ship end")){let d=c.length>0&&!c.endsWith(`
19
19
  `)?`
20
- `:"";y.appendFileSync(r.profileFile,u+a)}}else y.writeFileSync(r.profileFile,a);w(`completion script installed for ${i}`,n,o),ae(`run "source ${r.profileFile}" or restart your shell`,n,o)}}catch(a){let c=a instanceof Error?a.message:String(a);T(`could not install completion script: ${c}`,n,o)}}function lt(t={}){let{json:e,noColor:n}=t,o=st(),i=Te.homedir();if(!o){T(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,e,n);return}let s=rt(o,i);try{if(o==="fish"){y.existsSync(s.completionFile)?(y.unlinkSync(s.completionFile),w("fish completion uninstalled successfully",e,n)):ae("fish completion was not installed",e,n),M("please restart your shell to apply the changes",e,n);return}if(y.existsSync(s.completionFile)&&y.unlinkSync(s.completionFile),!s.profileFile)return;if(!y.existsSync(s.profileFile)){T("profile file not found",e,n);return}let r=y.readFileSync(s.profileFile,"utf-8"),p=r.split(`
21
- `),a=[],c=0,u=!1;for(;c<p.length;)if(p[c].trim()==="# ship"){for(u=!0,c++;c<p.length&&p[c].trim()!=="# ship end";)c++;c<p.length&&c++}else a.push(p[c]),c++;if(u){let d=r.endsWith(`
22
- `),f=a.length===0?"":a.join(`
23
- `)+(d?`
24
- `:"");y.writeFileSync(s.profileFile,f),w(`completion script uninstalled for ${o}`,e,n),ae(`run "source ${s.profileFile}" or restart your shell`,e,n)}else T("completion was not found in profile",e,n)}catch(r){let p=r instanceof Error?r.message:String(r);T(`could not uninstall completion script: ${p}`,e,n)}}var ut=require("readline/promises"),$=require("fs"),dt=require("os"),mt=require("path");C();var pe=require("yoctocolors"),B=(0,mt.join)((0,dt.homedir)(),".shiprc");function pt(t){return t.length<13?t:t.slice(0,9)+"..."+t.slice(-4)}function ct(){try{return(0,$.existsSync)(B)?JSON.parse((0,$.readFileSync)(B,"utf-8")):{}}catch{return{}}}async function ft(t={}){let{noColor:e,json:n}=t,o=u=>e?u:(0,pe.dim)(u),i=u=>e?u:(0,pe.green)(u);if(n){let u=ct(),d=typeof u.apiKey=="string"?u.apiKey:void 0,f=typeof u.apiUrl=="string"?u.apiUrl:void 0;console.log(JSON.stringify({path:B,exists:(0,$.existsSync)(B),...d?{apiKey:pt(d)}:{},...f&&f!==U?{apiUrl:f}:{}},null,2)+`
25
- `);return}let s=ct(),r=typeof s.apiKey=="string"?s.apiKey:void 0,p=(0,ut.createInterface)({input:process.stdin,output:process.stdout});console.log("");let a=r?` API Key (${o(pt(r))}): `:" API Key: ",c;try{c=(await p.question(a)).trim()}finally{p.close()}c&&(Q(c),s.apiKey=c),(0,$.writeFileSync)(B,JSON.stringify(s,null,2)+`
20
+ `:"";y.appendFileSync(r.profileFile,d+p)}}else y.writeFileSync(r.profileFile,p);w(`completion script installed for ${i}`,t,n),ae(`run "source ${r.profileFile}" or restart your shell`,t,n)}}catch(p){let c=p instanceof Error?p.message:String(p);T(`could not install completion script: ${c}`,t,n)}}function lt(e={}){let{json:o,noColor:t}=e,n=st(),i=Te.homedir();if(!n){T(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,o,t);return}let s=rt(n,i);try{if(n==="fish"){y.existsSync(s.completionFile)?(y.unlinkSync(s.completionFile),w("fish completion uninstalled successfully",o,t)):ae("fish completion was not installed",o,t),M("please restart your shell to apply the changes",o,t);return}if(y.existsSync(s.completionFile)&&y.unlinkSync(s.completionFile),!s.profileFile)return;if(!y.existsSync(s.profileFile)){T("profile file not found",o,t);return}let r=y.readFileSync(s.profileFile,"utf-8"),a=r.split(`
21
+ `),p=[],c=0,d=!1;for(;c<a.length;)if(a[c].trim()==="# ship"){for(d=!0,c++;c<a.length&&a[c].trim()!=="# ship end";)c++;c<a.length&&c++}else p.push(a[c]),c++;if(d){let u=r.endsWith(`
22
+ `),f=p.length===0?"":p.join(`
23
+ `)+(u?`
24
+ `:"");y.writeFileSync(s.profileFile,f),w(`completion script uninstalled for ${n}`,o,t),ae(`run "source ${s.profileFile}" or restart your shell`,o,t)}else T("completion was not found in profile",o,t)}catch(r){let a=r instanceof Error?r.message:String(r);T(`could not uninstall completion script: ${a}`,o,t)}}var dt=require("readline/promises"),$=require("fs"),ut=require("os"),mt=require("path");C();var pe=require("yoctocolors"),B=(0,mt.join)((0,ut.homedir)(),".shiprc");function pt(e){return e.length<13?e:e.slice(0,9)+"..."+e.slice(-4)}function ct(){try{return(0,$.existsSync)(B)?JSON.parse((0,$.readFileSync)(B,"utf-8")):{}}catch{return{}}}async function ft(e={}){let{noColor:o,json:t}=e,n=d=>o?d:(0,pe.dim)(d),i=d=>o?d:(0,pe.green)(d);if(t){let d=ct(),u=typeof d.apiKey=="string"?d.apiKey:void 0,f=typeof d.apiUrl=="string"?d.apiUrl:void 0;console.log(JSON.stringify({path:B,exists:(0,$.existsSync)(B),...u?{apiKey:pt(u)}:{},...f&&f!==U?{apiUrl:f}:{}},null,2)+`
25
+ `);return}let s=ct(),r=typeof s.apiKey=="string"?s.apiKey:void 0,a=(0,dt.createInterface)({input:process.stdin,output:process.stdout});console.log("");let p=r?` API Key (${n(pt(r))}): `:" API Key: ",c;try{c=(await a.question(p)).trim()}finally{a.close()}c&&(Q(c),s.apiKey=c),(0,$.writeFileSync)(B,JSON.stringify(s,null,2)+`
26
26
  `),console.log(`
27
- ${i("saved to")} ${o(B)}
28
- `)}C();function ht(t){return A(t)?t:t instanceof Error?l.business(t.message):l.business(String(t??"Unknown error"))}function gt(t,e,n){if(t.isAuthError())return n?.apiKey?"authentication failed: invalid API key":n?.deployToken?"authentication failed: invalid or expired deploy token":"authentication required: use --api-key or --deploy-token, or set SHIP_API_KEY";if(t.isNetworkError()){let o=t.details?.url;return o?`network error: could not reach ${o}`:"network error: could not reach the API. check your internet connection"}return t.isFileError()||t.isValidationError()||t.isClientError()||t.status&&t.status>=400&&t.status<500?t.message:"server error: please try again or check https://status.shipstatic.com"}function yt(t,e){return JSON.stringify({error:t,...e?{details:e}:{}},null,2)}var ue=require("yoctocolors");function Xt(){let t=[ce.resolve(__dirname,"../package.json"),ce.resolve(__dirname,"../../package.json")];for(let e of t)try{return JSON.parse((0,L.readFileSync)(e,"utf-8"))}catch{}return{version:"0.0.0"}}var Zt=Xt(),h=new St.Command;h.exitOverride(t=>{(t.code==="commander.help"||t.code==="commander.version"||t.exitCode===0)&&process.exit(t.exitCode||0);let e=P(h),n=t.message||"unknown command error";n=n.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),T(n,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,ue.bold)(i),n=i=>t?i:(0,ue.dim)(i),o=`${e("USAGE")}
27
+ ${i("saved to")} ${n(B)}
28
+ `)}C();function ht(e){return A(e)?e:e instanceof Error?l.business(e.message):l.business(String(e??"Unknown error"))}function gt(e,o,t){if(e.isAuthError())return t?.apiKey?"authentication failed: invalid API key":t?.deployToken?"authentication failed: invalid or expired deploy token":"authentication required: use --api-key or --deploy-token, or set SHIP_API_KEY";if(e.isNetworkError()){let n=e.details?.url;return n?`network error: could not reach ${n}`:"network error: could not reach the API. check your internet connection"}return e.isFileError()||e.isValidationError()||e.isClientError()||e.status&&e.status>=400&&e.status<500?e.message:"server error: please try again or check https://status.shipstatic.com"}function yt(e,o){return JSON.stringify({error:e,...o?{details:o}:{}},null,2)}var de=require("yoctocolors");function Xt(){let e=[ce.resolve(__dirname,"../package.json"),ce.resolve(__dirname,"../../package.json")];for(let o of e)try{return JSON.parse((0,L.readFileSync)(o,"utf-8"))}catch{}return{version:"0.0.0"}}var Zt=Xt(),h=new St.Command;h.exitOverride(e=>{(e.code==="commander.help"||e.code==="commander.version"||e.exitCode===0)&&process.exit(e.exitCode||0);let o=P(h),t=e.message||"unknown command error";t=t.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),T(t,o.json,o.noColor),o.json||J(o.noColor),process.exit(e.exitCode||1)}).configureOutput({writeErr:e=>{e.startsWith("error:")||process.stderr.write(e)},writeOut:e=>process.stdout.write(e)});function J(e){let o=i=>e?i:(0,de.bold)(i),t=i=>e?i:(0,de.dim)(i),n=`${o("USAGE")}
29
29
  ship <path> \u{1F680} Deploy static sites with simplicity
30
30
 
31
- ${e("COMMANDS")}
32
- \u{1F4E6} ${e("Deployments")}
31
+ ${o("COMMANDS")}
32
+ \u{1F4E6} ${o("Deployments")}
33
33
  ship deployments list List all deployments
34
- ship deployments create <path> Create deployment from directory
34
+ ship deployments upload <path> Upload deployment from directory
35
35
  ship deployments get <id> Show deployment information
36
36
  ship deployments set <id> Set deployment labels
37
37
  ship deployments remove <id> Delete deployment permanently
38
38
 
39
- \u{1F30E} ${e("Domains")}
39
+ \u{1F30E} ${o("Domains")}
40
40
  ship domains list List all domains
41
41
  ship domains set <name> [deployment] Create domain, link to deployment, or update labels
42
42
  ship domains get <name> Show domain information
@@ -44,20 +44,20 @@ ${e("COMMANDS")}
44
44
  ship domains verify <name> Trigger DNS verification for external domain
45
45
  ship domains remove <name> Delete domain permanently
46
46
 
47
- \u{1F511} ${e("Tokens")}
47
+ \u{1F511} ${o("Tokens")}
48
48
  ship tokens list List all deploy tokens
49
49
  ship tokens create Create a new deploy token
50
50
  ship tokens remove <token> Delete token permanently
51
51
 
52
- \u2699\uFE0F ${e("Setup")}
52
+ \u2699\uFE0F ${o("Setup")}
53
53
  ship config Create or update ~/.shiprc configuration
54
54
  ship whoami Get current account information
55
55
 
56
- \u{1F6E0}\uFE0F ${e("Completion")}
56
+ \u{1F6E0}\uFE0F ${o("Completion")}
57
57
  ship completion install Install shell completion script
58
58
  ship completion uninstall Uninstall shell completion script
59
59
 
60
- ${e("FLAGS")}
60
+ ${o("FLAGS")}
61
61
  --api-key <key> API key for authenticated deployments
62
62
  --deploy-token <token> Deploy token for single-use deployments
63
63
  --config <file> Custom config file path
@@ -68,8 +68,8 @@ ${e("FLAGS")}
68
68
  --json Output results in JSON format
69
69
  --version Show version information
70
70
 
71
- ${n("Please report any issues to https://github.com/shipstatic/ship/issues")}
72
- `;console.log(o)}function W(t,e=[]){return e.concat([t])}function Y(t,e){let n=t?.label?.length?t.label:e?.label;return n?.length?n:void 0}function X(t){return(...e)=>{let n=P(h),o=e[e.length-1];if(o?.args?.length){let i=o.args.find(s=>!t.includes(s));i&&T(`unknown command '${i}'`,n.json,n.noColor)}J(n.noColor),process.exit(1)}}function P(t){let e=t.optsWithGlobals();return e.color===!1&&(e.noColor=!0),e}function Dt(t,e){let n=P(h),o=ht(t),i=gt(o,e,{apiKey:n.apiKey,deployToken:n.deployToken});n.json?console.error(yt(i,o.details)+`
73
- `):(T(i,!1,n.noColor),o.isValidationError()&&i.includes("unknown command")&&J(n.noColor)),process.exit(1)}function D(t,e){return async function(...n){let o=P(this),i=e?{operation:e.operation,resourceType:e.resourceType,resourceId:e.getResourceId?.(...n)}:{};try{let s=Qt(),r=await t(s,o,...n);it(r,i,{json:o.json,noColor:o.noColor})}catch(s){Dt(s,i)}}}function Qt(){let{config:t,apiUrl:e,apiKey:n,deployToken:o}=h.opts();return new re({configFile:t,apiUrl:e,apiKey:n,deployToken:o})}async function bt(t,e,n,o,i){if(!(0,L.existsSync)(e))throw l.file(`${e} path does not exist`,e);let s=(0,L.statSync)(e);if(!s.isDirectory()&&!s.isFile())throw l.file(`${e} path must be a file or directory`,e);let r={via:"cli"};n&&(r.labels=n),o?.noPathDetect!==void 0&&(r.pathDetect=!o.noPathDetect),o?.noSpaDetect!==void 0&&(r.spaDetect=!o.noSpaDetect);let p=new AbortController;r.signal=p.signal;let a=null;if(process.stdout.isTTY&&!i.json&&!i.noColor){let{default:u}=await import("yocto-spinner");a=u({text:"uploading\u2026"}).start()}let c=()=>{p.abort(),a&&a.stop(),process.exit(130)};process.on("SIGINT",c);try{return await t.deployments.create(e,r)}finally{process.removeListener("SIGINT",c),a&&a.stop()}}h.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(Zt.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);h.hook("preAction",t=>{let e=P(t);e.help&&(J(e.noColor),process.exit(0))});h.hook("preAction",t=>{let e=P(t);try{e.apiKey&&typeof e.apiKey=="string"&&Q(e.apiKey),e.deployToken&&typeof e.deployToken=="string"&&ke(e.deployToken),e.apiUrl&&typeof e.apiUrl=="string"&&Re(e.apiUrl)}catch(n){throw A(n)&&(T(n.message,e.json,e.noColor),process.exit(1)),n}});h.command("ping").description("Check API connectivity").action(D((t,e)=>t.ping()));h.command("whoami").description("Get current account information").action(D((t,e)=>t.whoami(),{operation:"get",resourceType:"Account"}));var Z=h.command("deployments").description("Manage deployments").enablePositionalOptions().action(X(["list","create","get","set","remove"]));Z.command("list").description("List all deployments").action(D((t,e)=>t.deployments.list()));Z.command("create <path>").description("Create deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",W,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(D((t,e,n,o)=>bt(t,n,Y(o,h.opts()),o,e),{operation:"create"}));Z.command("get <deployment>").description("Show deployment information").action(D((t,e,n)=>t.deployments.get(n),{operation:"get",resourceType:"Deployment",getResourceId:t=>t}));Z.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",W,[]).action(D(async(t,e,n,o)=>{let i=Y(o,h.opts())||[];return t.deployments.set(n,{labels:i})},{operation:"set",resourceType:"Deployment",getResourceId:t=>t}));Z.command("remove <deployment>").description("Delete deployment permanently").action(D((t,e,n)=>t.deployments.remove(n),{operation:"remove",resourceType:"Deployment",getResourceId:t=>t}));var z=h.command("domains").description("Manage domains").enablePositionalOptions().action(X(["list","get","set","validate","verify","remove"]));z.command("list").description("List all domains").action(D((t,e)=>t.domains.list()));z.command("get <name>").description("Show domain information").action(D((t,e,n)=>t.domains.get(n),{operation:"get",resourceType:"Domain",getResourceId:t=>t}));z.command("validate <name>").description("Check if domain name is valid and available").action(D((t,e,n)=>t.domains.validate(n),{operation:"validate",resourceType:"Domain",getResourceId:t=>t}));z.command("verify <name>").description("Trigger DNS verification for external domain").action(D((t,e,n)=>t.domains.verify(n),{operation:"verify",resourceType:"Domain",getResourceId:t=>t}));z.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",W,[]).action(D(async(t,e,n,o,i)=>{let s=Y(i,h.opts()),r={};o&&(r.deployment=o),s&&s.length>0&&(r.labels=s);let p=await t.domains.set(n,r);if(p.isCreate&&n.includes("."))try{let[a,c]=await Promise.all([t.domains.records(n),t.domains.share(n)]);return{...p,_dnsRecords:a.records,_shareHash:c.hash}}catch{}return p},{operation:"set",resourceType:"Domain",getResourceId:t=>t}));z.command("remove <name>").description("Delete domain permanently").action(D((t,e,n)=>t.domains.remove(n),{operation:"remove",resourceType:"Domain",getResourceId:t=>t}));var xe=h.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(X(["list","create","remove"]));xe.command("list").description("List all tokens").action(D((t,e)=>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("--label <label>","Label to set (can be repeated)",W,[]).action(D((t,e,n)=>{let o={};n?.ttl!==void 0&&(o.ttl=n.ttl);let i=Y(n,h.opts());return i&&i.length>0&&(o.labels=i),t.tokens.create(o)},{operation:"create",resourceType:"Token"}));xe.command("remove <token>").description("Delete token permanently").action(D((t,e,n)=>t.tokens.remove(n),{operation:"remove",resourceType:"Token",getResourceId:t=>t}));var en=h.command("account").description("Manage account").action(X(["get"]));en.command("get").description("Show account information").action(D((t,e)=>t.whoami(),{operation:"get",resourceType:"Account"}));var Ct=h.command("completion").description("Setup shell completion").action(X(["install","uninstall"]));Ct.command("install").description("Install shell completion script").action(()=>{let t=P(h),e=ce.resolve(__dirname,"completions");at(e,{json:t.json,noColor:t.noColor})});Ct.command("uninstall").description("Uninstall shell completion script").action(()=>{let t=P(h);lt({json:t.json,noColor:t.noColor})});h.command("config").description("Create or update ~/.shiprc configuration").action(async()=>{let t=P(h);try{await ft({noColor:t.noColor,json:t.json})}catch(e){Dt(e)}});h.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",W,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(D(async(t,e,n,o)=>{if(n||(J(e.noColor),process.exit(0)),!(0,L.existsSync)(n)&&!n.includes("/")&&!n.includes("\\")&&!n.includes(".")&&!n.startsWith("~"))throw l.validation(`unknown command '${n}'`);return bt(t,n,Y(o,h.opts()),o,e)},{operation:"create"}));function tn(){let t=process.argv,e=t.includes("--compbash"),n=t.includes("--compzsh"),o=t.includes("--compfish");if(!e&&!n&&!o)return;console.log(["ping","whoami","deployments","domains","tokens","account","config","completion"].join(o?`
74
- `:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&tn();if(process.env.NODE_ENV!=="test")try{h.parse(process.argv)}catch(t){if(t instanceof Error&&"code"in t){let e=t.code,n=t.exitCode;e?.startsWith("commander.")&&process.exit(n||1)}throw t}
71
+ ${t("Please report any issues to https://github.com/shipstatic/ship/issues")}
72
+ `;console.log(n)}function W(e,o=[]){return o.concat([e])}function Y(e,o){let t=e?.label?.length?e.label:o?.label;return t?.length?t:void 0}function X(e){return(...o)=>{let t=P(h),n=o[o.length-1];if(n?.args?.length){let i=n.args.find(s=>!e.includes(s));i&&T(`unknown command '${i}'`,t.json,t.noColor)}J(t.noColor),process.exit(1)}}function P(e){let o=e.optsWithGlobals();return o.color===!1&&(o.noColor=!0),o}function Dt(e,o){let t=P(h),n=ht(e),i=gt(n,o,{apiKey:t.apiKey,deployToken:t.deployToken});t.json?console.error(yt(i,n.details)+`
73
+ `):(T(i,!1,t.noColor),n.isValidationError()&&i.includes("unknown command")&&J(t.noColor)),process.exit(1)}function D(e,o){return async function(...t){let n=P(this),i=o?{operation:o.operation,resourceType:o.resourceType,resourceId:o.getResourceId?.(...t)}:{};try{let s=Qt(),r=await e(s,n,...t);it(r,i,{json:n.json,noColor:n.noColor})}catch(s){Dt(s,i)}}}function Qt(){let{config:e,apiUrl:o,apiKey:t,deployToken:n}=h.opts();return new re({configFile:e,apiUrl:o,apiKey:t,deployToken:n})}async function bt(e,o,t,n,i){if(!(0,L.existsSync)(o))throw l.file(`${o} path does not exist`,o);let s=(0,L.statSync)(o);if(!s.isDirectory()&&!s.isFile())throw l.file(`${o} path must be a file or directory`,o);let r={via:"cli"};t&&(r.labels=t),n?.noPathDetect!==void 0&&(r.pathDetect=!n.noPathDetect),n?.noSpaDetect!==void 0&&(r.spaDetect=!n.noSpaDetect);let a=new AbortController;r.signal=a.signal;let p=null;if(process.stdout.isTTY&&!i.json&&!i.noColor){let{default:d}=await import("yocto-spinner");p=d({text:"uploading\u2026"}).start()}let c=()=>{a.abort(),p&&p.stop(),process.exit(130)};process.on("SIGINT",c);try{return await e.deployments.upload(o,r)}finally{process.removeListener("SIGINT",c),p&&p.stop()}}h.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(Zt.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);h.hook("preAction",e=>{let o=P(e);o.help&&(J(o.noColor),process.exit(0))});h.hook("preAction",e=>{let o=P(e);try{o.apiKey&&typeof o.apiKey=="string"&&Q(o.apiKey),o.deployToken&&typeof o.deployToken=="string"&&Re(o.deployToken),o.apiUrl&&typeof o.apiUrl=="string"&&ke(o.apiUrl)}catch(t){throw A(t)&&(T(t.message,o.json,o.noColor),process.exit(1)),t}});h.command("ping").description("Check API connectivity").action(D((e,o)=>e.ping()));h.command("whoami").description("Get current account information").action(D((e,o)=>e.whoami(),{operation:"get",resourceType:"Account"}));var Z=h.command("deployments").description("Manage deployments").enablePositionalOptions().action(X(["list","upload","get","set","remove"]));Z.command("list").description("List all deployments").action(D((e,o)=>e.deployments.list()));Z.command("upload <path>").description("Upload deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",W,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(D((e,o,t,n)=>bt(e,t,Y(n,h.opts()),n,o),{operation:"upload"}));Z.command("get <deployment>").description("Show deployment information").action(D((e,o,t)=>e.deployments.get(t),{operation:"get",resourceType:"Deployment",getResourceId:e=>e}));Z.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",W,[]).action(D(async(e,o,t,n)=>{let i=Y(n,h.opts())||[];return e.deployments.set(t,{labels:i})},{operation:"set",resourceType:"Deployment",getResourceId:e=>e}));Z.command("remove <deployment>").description("Delete deployment permanently").action(D((e,o,t)=>e.deployments.remove(t),{operation:"remove",resourceType:"Deployment",getResourceId:e=>e}));var z=h.command("domains").description("Manage domains").enablePositionalOptions().action(X(["list","get","set","validate","verify","remove"]));z.command("list").description("List all domains").action(D((e,o)=>e.domains.list()));z.command("get <name>").description("Show domain information").action(D((e,o,t)=>e.domains.get(t),{operation:"get",resourceType:"Domain",getResourceId:e=>e}));z.command("validate <name>").description("Check if domain name is valid and available").action(D((e,o,t)=>e.domains.validate(t),{operation:"validate",resourceType:"Domain",getResourceId:e=>e}));z.command("verify <name>").description("Trigger DNS verification for external domain").action(D((e,o,t)=>e.domains.verify(t),{operation:"verify",resourceType:"Domain",getResourceId:e=>e}));z.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",W,[]).action(D(async(e,o,t,n,i)=>{let s=Y(i,h.opts()),r={};n&&(r.deployment=n),s&&s.length>0&&(r.labels=s);let a=await e.domains.set(t,r);if(a.isCreate&&t.includes("."))try{let[p,c]=await Promise.all([e.domains.records(t),e.domains.share(t)]);return{...a,_dnsRecords:p.records,_shareHash:c.hash}}catch{}return a},{operation:"set",resourceType:"Domain",getResourceId:e=>e}));z.command("remove <name>").description("Delete domain permanently").action(D((e,o,t)=>e.domains.remove(t),{operation:"remove",resourceType:"Domain",getResourceId:e=>e}));var xe=h.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(X(["list","create","remove"]));xe.command("list").description("List all tokens").action(D((e,o)=>e.tokens.list()));xe.command("create").description("Create a new deploy token").option("--ttl <seconds>","Time to live in seconds (default: never expires)",parseInt).option("--label <label>","Label to set (can be repeated)",W,[]).action(D((e,o,t)=>{let n={};t?.ttl!==void 0&&(n.ttl=t.ttl);let i=Y(t,h.opts());return i&&i.length>0&&(n.labels=i),e.tokens.create(n)},{operation:"create",resourceType:"Token"}));xe.command("remove <token>").description("Delete token permanently").action(D((e,o,t)=>e.tokens.remove(t),{operation:"remove",resourceType:"Token",getResourceId:e=>e}));var eo=h.command("account").description("Manage account").action(X(["get"]));eo.command("get").description("Show account information").action(D((e,o)=>e.whoami(),{operation:"get",resourceType:"Account"}));var Ct=h.command("completion").description("Setup shell completion").action(X(["install","uninstall"]));Ct.command("install").description("Install shell completion script").action(()=>{let e=P(h),o=ce.resolve(__dirname,"completions");at(o,{json:e.json,noColor:e.noColor})});Ct.command("uninstall").description("Uninstall shell completion script").action(()=>{let e=P(h);lt({json:e.json,noColor:e.noColor})});h.command("config").description("Create or update ~/.shiprc configuration").action(async()=>{let e=P(h);try{await ft({noColor:e.noColor,json:e.json})}catch(o){Dt(o)}});h.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",W,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(D(async(e,o,t,n)=>{if(t||(J(o.noColor),process.exit(0)),!(0,L.existsSync)(t)&&!t.includes("/")&&!t.includes("\\")&&!t.includes(".")&&!t.startsWith("~"))throw l.validation(`unknown command '${t}'`);return bt(e,t,Y(n,h.opts()),n,o)},{operation:"upload"}));function to(){let e=process.argv,o=e.includes("--compbash"),t=e.includes("--compzsh"),n=e.includes("--compfish");if(!o&&!t&&!n)return;console.log(["ping","whoami","deployments","domains","tokens","account","config","completion"].join(n?`
74
+ `:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&to();if(process.env.NODE_ENV!=="test")try{h.parse(process.argv)}catch(e){if(e instanceof Error&&"code"in e){let o=e.code,t=e.exitCode;o?.startsWith("commander.")&&process.exit(t||1)}throw e}
75
75
  //# sourceMappingURL=cli.cjs.map