@shipstatic/ship 0.4.25 → 0.5.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,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Dt=Object.create;var me=Object.defineProperty;var vt=Object.getOwnPropertyDescriptor;var wt=Object.getOwnPropertyNames;var Tt=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var Rt=(t,e)=>{for(var o in e)me(t,o,{get:e[o],enumerable:!0})},bt=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of wt(e))!Et.call(t,i)&&i!==o&&me(t,i,{get:()=>e[i],enumerable:!(n=vt(e,i))||n.enumerable});return t};var v=(t,e,o)=>(o=t!=null?Dt(Tt(t)):{},bt(e||!t||!t.__esModule?me(o,"default",{value:t,enumerable:!0}):o,t));function b(t){return t!==null&&typeof t=="object"&&"name"in t&&t.name==="ShipError"&&"status"in t}function X(t){if(!t.startsWith(L))throw p.validation(`API key must start with "${L}"`);if(t.length!==ke)throw p.validation(`API key must be ${ke} characters total (${L} + ${fe} hex chars)`);let e=t.slice(L.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`API key must contain ${fe} hexadecimal characters after "${L}" prefix`)}function Ae(t){if(!t.startsWith(U))throw p.validation(`Deploy token must start with "${U}"`);if(t.length!==Oe)throw p.validation(`Deploy token must be ${Oe} characters total (${U} + ${he} hex chars)`);let e=t.slice(U.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`Deploy token must contain ${he} hexadecimal characters after "${U}" prefix`)}function Pe(t){try{let e=new URL(t);if(!["http:","https:"].includes(e.protocol))throw p.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw p.validation("API URL must not contain a path");if(e.search||e.hash)throw p.validation("API URL must not contain query parameters or fragments")}catch(e){throw b(e)?e:p.validation("API URL must be a valid URL")}}var g,ue,p,L,fe,ke,U,he,Oe,ge,_,T=P(()=>{"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={}));ue={client:new Set([g.Business,g.Config,g.File,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},p=class t extends Error{type;status;details;constructor(e,o,n,i){super(o),this.type=e,this.status=n,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,o){return new t(g.Validation,e,400,o)}static notFound(e,o){let n=o?`${e} ${o} not found`:`${e} not found`;return new t(g.NotFound,n,404)}static rateLimit(e="Too many requests"){return new t(g.RateLimit,e,429)}static authentication(e="Authentication required",o){return new t(g.Authentication,e,401,o)}static business(e,o=400){return new t(g.Business,e,o)}static network(e,o){return new t(g.Network,e,void 0,{cause:o})}static cancelled(e){return new t(g.Cancelled,e)}static file(e,o){return new t(g.File,e,void 0,{filePath:o})}static config(e,o){return new t(g.Config,e,void 0,o)}static api(e,o=500){return new t(g.Api,e,o)}static database(e,o=500){return new t(g.Api,e,o)}static storage(e,o=500){return new t(g.Api,e,o)}get filePath(){return this.details?.filePath}isClientError(){return ue.client.has(this.type)}isNetworkError(){return ue.network.has(this.type)}isAuthError(){return ue.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}};L="ship-",fe=64,ke=L.length+fe,U="token-",he=64,Oe=U.length+he,ge="ship.json";_="https://api.shipstatic.com"});function Ie(t){ye=t}function Q(){if(ye===null)throw p.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ye}var ye,ee=P(()=>{"use strict";T();ye=null});function Ot(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function I(){return $e||Ot()}var $e,G=P(()=>{"use strict";$e=null});async function At(t){let e=(await import("spark-md5")).default;return new Promise((o,n)=>{let s=Math.ceil(t.size/2097152),r=0,c=new e.ArrayBuffer,a=new FileReader,l=()=>{let m=r*2097152,d=Math.min(m+2097152,t.size);a.readAsArrayBuffer(t.slice(m,d))};a.onload=m=>{let d=m.target?.result;if(!d){n(p.business("Failed to read file chunk"));return}c.append(d),r++,r<s?l():o({md5:c.end()})},a.onerror=()=>{n(p.business("Failed to calculate MD5: FileReader error"))},l()})}async function Pt(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",c=>i(p.business(`Failed to read file for MD5: ${c.message}`))),r.on("data",c=>s.update(c)),r.on("end",()=>n({md5:s.digest("hex")}))})}async function te(t){let e=I();if(e==="browser"){if(!(t instanceof Blob))throw p.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return At(t)}if(e==="node"){if(!(Buffer.isBuffer(t)||typeof t=="string"))throw p.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Pt(t)}throw p.business("Unknown or unsupported execution environment for MD5 calculation.")}var Ce=P(()=>{"use strict";G();T()});function Ke(t){try{return $t.parse(t)}catch(e){if(e instanceof K.z.ZodError){let o=e.issues[0],n=o.path.length>0?` at ${o.path.join(".")}`:"";throw p.config(`Configuration validation failed${n}: ${o.message}`)}throw p.config("Configuration validation failed")}}async function Ft(t){try{if(I()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),o=await import("os"),n=e(xe,{searchPlaces:[`.${xe}rc`,"package.json",`${o.homedir()}/.${xe}rc`],stopDir:o.homedir()}),i;if(t?i=n.load(t):i=n.search(),i&&i.config)return Ke(i.config)}catch(e){if(b(e))throw e}return{}}async function Me(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},o=await Ft(t),n={apiUrl:e.apiUrl??o.apiUrl,apiKey:e.apiKey??o.apiKey,deployToken:e.deployToken??o.deployToken};return Ke(n)}var K,xe,$t,Be=P(()=>{"use strict";K=require("zod");T();G();xe="ship",$t=K.z.object({apiUrl:K.z.string().url().optional(),apiKey:K.z.string().optional(),deployToken:K.z.string().optional()}).strict()});function Je(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,Ge.isJunk)(n))return!1;for(let s of o)if(s.startsWith(".")||s.length>255)return!1;let i=o.slice(0,-1);for(let s of i)if(Nt.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var Ge,Nt,qe=P(()=>{"use strict";Ge=require("junk"),Nt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ve(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(c=>c[s]===r))n.push(r);else break}return n.join("/")}function ne(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var we=P(()=>{"use strict"});function We(t,e={}){if(e.flatten===!1)return t.map(n=>({path:ne(n),name:Te(n)}));let o=Lt(t);return t.map(n=>{let i=ne(n);if(o){let s=o.endsWith("/")?o:`${o}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=Te(n)),{path:i,name:Te(n)}})}function Lt(t){if(!t.length)return"";let o=t.map(s=>ne(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(c=>c[s]===r))n.push(r);else break}return n.join("/")}function Te(t){return t.split(/[/\\]/).pop()||t}var Ye=P(()=>{"use strict";we()});var Ze={};Rt(Ze,{processFilesForNode:()=>Ut});function Xe(t,e=new Set){let o=[],n=k.realpathSync(t);if(e.has(n))return o;e.add(n);let i=k.readdirSync(t);for(let s of i){let r=R.join(t,s),c=k.statSync(r);if(c.isDirectory()){let a=Xe(r,e);o.push(...a)}else c.isFile()&&o.push(r)}return o}async function Ut(t,e={}){if(I()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");let o=t.flatMap(u=>{let C=R.resolve(u);try{return k.statSync(C).isDirectory()?Xe(C):[C]}catch{throw p.file(`Path does not exist: ${u}`,u)}}),n=[...new Set(o)],i=Je(n);if(i.length===0)return[];let s=t.map(u=>R.resolve(u)),r=Ve(s.map(u=>{try{return k.statSync(u).isDirectory()?u:R.dirname(u)}catch{return R.dirname(u)}})),c=i.map(u=>{if(r&&r.length>0){let C=R.relative(r,u);if(C&&typeof C=="string"&&!C.startsWith(".."))return C.replace(/\\/g,"/")}return R.basename(u)}),a=We(c,{flatten:e.pathDetect!==!1}),l=[],m=0,d=Q();for(let u=0;u<i.length;u++){let C=i[u],O=a[u].path;try{let A=k.statSync(C);if(A.size===0)continue;if(A.size>d.maxFileSize)throw p.business(`File ${C} is too large. Maximum allowed size is ${d.maxFileSize/(1024*1024)}MB.`);if(m+=A.size,m>d.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${d.maxTotalSize/(1024*1024)}MB.`);let H=k.readFileSync(C),{md5:xt}=await te(H);if(O.includes("\0")||O.includes("/../")||O.startsWith("../")||O.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${O}" for file: ${C}`);l.push({path:O,content:H,size:H.length,md5:xt})}catch(A){if(b(A))throw A;let H=A instanceof Error?A.message:String(A);throw p.file(`Failed to read file "${C}": ${H}`,C)}}if(l.length>d.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return l}var k,R,Qe=P(()=>{"use strict";G();Ce();qe();T();ee();Ye();we();k=v(require("fs"),1),R=v(require("path"),1)});var gt=require("commander");T();var Z=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()}};var y={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},kt=3e4,j=class extends Z{constructor(e){super(),this.apiUrl=e.apiUrl||_,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??kt,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,o,n){let i=this.mergeHeaders(o.headers),{signal:s,cleanup:r}=this.createTimeoutSignal(o.signal),c={...o,headers:i,credentials:i.Authorization?void 0:"include",signal:s};this.emit("request",e,c);try{let a=await fetch(e,c);return r(),a.ok||await this.handleResponseError(a,n),this.emit("response",this.safeClone(a),e),{data:await this.parseResponse(this.safeClone(a)),status:a.status}}catch(a){r();let l=a instanceof Error?a:new Error(String(a));this.emit("error",l,e),this.handleFetchError(a,n)}}async request(e,o,n){let{data:i}=await this.executeRequest(e,o,n);return i}async requestWithStatus(e,o,n){return this.executeRequest(e,o,n)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let o=new AbortController,n=setTimeout(()=>o.abort(),this.timeout);if(e){let i=()=>o.abort();e.addEventListener("abort",i),e.aborted&&o.abort()}return{signal:o.signal,cleanup:()=>clearTimeout(n)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,o){let n={};try{if(e.headers.get("content-type")?.includes("application/json")){let r=await e.json();if(r&&typeof r=="object"){let c=r;typeof c.message=="string"&&(n.message=c.message),typeof c.error=="string"&&(n.error=c.error)}}else n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let i=n.message||n.error||`${o} failed`;throw e.status===401?p.authentication(i):p.api(i,e.status)}handleFetchError(e,o){throw b(e)?e:e instanceof Error&&e.name==="AbortError"?p.cancelled(`${o} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?p.network(`${o} failed: ${e.message}`,e):e instanceof Error?p.business(`${o} failed: ${e.message}`):p.business(`${o} failed: Unknown error`)}async deploy(e,o={}){if(!e.length)throw p.business("No files to deploy");for(let r of e)if(!r.md5)throw p.file(`MD5 checksum missing for file: ${r.path}`,r.path);let{body:n,headers:i}=await this.createDeployBody(e,o.tags,o.via),s={};return o.deployToken?s.Authorization=`Bearer ${o.deployToken}`:o.apiKey&&(s.Authorization=`Bearer ${o.apiKey}`),o.caller&&(s["X-Caller"]=o.caller),this.request(`${o.apiUrl||this.apiUrl}${y.DEPLOYMENTS}`,{method:"POST",body:n,headers:{...i,...s},signal:o.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentTags(e,o){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:o})},"Update deployment tags")}async removeDeployment(e){await this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,o,n){let i={};o&&(i.deployment=o),n!==void 0&&(i.tags=n);let{data:s,status:r}=await this.requestWithStatus(`${this.apiUrl}${y.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}${y.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async updateDomainTags(e,o){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:o})},"Update domain tags")}async removeDomain(e){await this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,o){let n={};return e!==void 0&&(n.ttl=e),o!==void 0&&(n.tags=o),this.request(`${this.apiUrl}${y.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${y.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${y.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${y.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${y.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${y.PING}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return this.request(`${this.apiUrl}${y.PING}`,{method:"GET"},"Ping")}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}${y.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA check")).isSPA}};T();ee();T();T();function Se(t={},e={}){let o={apiUrl:t.apiUrl||e.apiUrl||_,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 Fe(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.caller===void 0&&e.caller!==void 0&&(o.caller=e.caller),o}T();Ce();async function It(){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 te(o);return{path:ge,content:o,size:e.length,md5:n}}async function Ne(t,e,o){if(o.spaDetect===!1||t.some(n=>n.path===ge))return t;try{if(await e.checkSPA(t)){let i=await It();return[...t,i]}}catch{}return t}function Le(t){let{getApi:e,ensureInit:o,processInput:n,clientDefaults:i,hasAuth:s}=t;return{create:async(r,c={})=>{await o();let a=i?Fe(c,i):c;if(s&&!s()&&!a.deployToken&&!a.apiKey)throw p.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw p.config("processInput function is not provided.");let l=e(),m=await n(r,a);return m=await Ne(m,l,a),l.deploy(m,a)},list:async()=>(await o(),e().listDeployments()),get:async r=>(await o(),e().getDeployment(r)),set:async(r,c)=>(await o(),e().updateDeploymentTags(r,c.tags)),remove:async r=>{await o(),await e().removeDeployment(r)}}}function Ue(t){let{getApi:e,ensureInit:o}=t;return{set:async(n,i={})=>{await o();let{deployment:s,tags:r}=i;return s===void 0&&r&&r.length>0?e().updateDomainTags(n,r):e().setDomain(n,s,r)},list:async()=>(await o(),e().listDomains()),get:async n=>(await o(),e().getDomain(n)),remove:async n=>{await o(),await e().removeDomain(n)},verify:async n=>(await o(),e().verifyDomain(n)),validate:async n=>(await o(),e().validateDomain(n)),dns:async n=>(await o(),e().getDomainDns(n)),records:async n=>(await o(),e().getDomainRecords(n)),share:async n=>(await o(),e().getDomainShare(n))}}function _e(t){let{getApi:e,ensureInit:o}=t;return{get:async()=>(await o(),e().getAccount())}}function je(t){let{getApi:e,ensureInit:o}=t;return{create:async(n={})=>(await o(),e().createToken(n.ttl,n.tags)),list:async()=>(await o(),e().listTokens()),remove:async n=>{await o(),await e().removeToken(n)}}}var oe=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 o=this.resolveInitialConfig(e);this.http=new j({...e,...o,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=Ue(n),this._account=_e(n),this._tokens=je(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=Q(),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}setDeployToken(e){if(!e||typeof e!="string")throw p.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 p.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}};T();G();Be();ee();T();var De=v(require("mime-db"),1),ve={};for(let t in De.default){let e=De.default[t];e&&e.extensions&&e.extensions.forEach(o=>{ve[o]||(ve[o]=t)})}function ze(t){let e=t.includes(".")?t.substring(t.lastIndexOf(".")+1).toLowerCase():"";return ve[e]||"application/octet-stream"}async function He(t,e,o){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new n,c=[];for(let d of t){let u=ze(d.path),C;if(Buffer.isBuffer(d.content))C=new i([d.content],d.path,{type:u});else if(typeof Blob<"u"&&d.content instanceof Blob)C=new i([d.content],d.path,{type:u});else throw p.file(`Unsupported file.content type for Node.js: ${d.path}`,d.path);if(!d.md5)throw p.file(`File missing md5 checksum: ${d.path}`,d.path);let O=d.path.startsWith("/")?d.path:"/"+d.path;r.append("files[]",C,O),c.push(d.md5)}r.append("checksums",JSON.stringify(c)),e&&e.length>0&&r.append("tags",JSON.stringify(e)),o&&r.append("via",o);let a=new s(r),l=[];for await(let d of a.encode())l.push(Buffer.from(d));let m=Buffer.concat(l);return{body:m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength),headers:{"Content-Type":a.contentType,"Content-Length":Buffer.byteLength(m).toString()}}}var ie=class extends oe{constructor(e={}){if(I()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return Se(e,{})}async loadFullConfig(){try{let e=await Me(this.clientOptions.configFile),o=Se(this.clientOptions,e);o.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(o.deployToken):o.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(o.apiKey);let n=new j({...this.clientOptions,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();Ie(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,o){let n=typeof e=="string"?[e]:e;if(!Array.isArray(n)||!n.every(s=>typeof s=="string"))throw p.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw p.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(Qe(),Ze));return i(n,o)}getDeployBodyCreator(){return He}};T();var N=require("fs"),pe=v(require("path"),1);var Ee=v(require("columnify"),1),f=require("yoctocolors"),et=["isCreate"],D=(t,e,o)=>o?e:t(e),w=(t,e,o)=>{console.log(e?JSON.stringify({success:t},null,2)+`
2
+ "use strict";var Dt=Object.create;var me=Object.defineProperty;var bt=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var wt=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var Tt=(t,e)=>{for(var o in e)me(t,o,{get:e[o],enumerable:!0})},Rt=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of vt(e))!Et.call(t,i)&&i!==o&&me(t,i,{get:()=>e[i],enumerable:!(n=bt(e,i))||n.enumerable});return t};var b=(t,e,o)=>(o=t!=null?Dt(wt(t)):{},Rt(e||!t||!t.__esModule?me(o,"default",{value:t,enumerable:!0}):o,t));function R(t){return t!==null&&typeof t=="object"&&"name"in t&&t.name==="ShipError"&&"status"in t}function X(t){if(!t.startsWith(L))throw p.validation(`API key must start with "${L}"`);if(t.length!==ke)throw p.validation(`API key must be ${ke} characters total (${L} + ${fe} hex chars)`);let e=t.slice(L.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`API key must contain ${fe} hexadecimal characters after "${L}" prefix`)}function Ae(t){if(!t.startsWith(U))throw p.validation(`Deploy token must start with "${U}"`);if(t.length!==Oe)throw p.validation(`Deploy token must be ${Oe} characters total (${U} + ${he} hex chars)`);let e=t.slice(U.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`Deploy token must contain ${he} hexadecimal characters after "${U}" prefix`)}function Pe(t){try{let e=new URL(t);if(!["http:","https:"].includes(e.protocol))throw p.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw p.validation("API URL must not contain a path");if(e.search||e.hash)throw p.validation("API URL must not contain query parameters or fragments")}catch(e){throw R(e)?e:p.validation("API URL must be a valid URL")}}var g,ue,p,L,fe,ke,U,he,Oe,ge,_,w=P(()=>{"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={}));ue={client:new Set([g.Business,g.Config,g.File,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},p=class t extends Error{type;status;details;constructor(e,o,n,i){super(o),this.type=e,this.status=n,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,o){return new t(g.Validation,e,400,o)}static notFound(e,o){let n=o?`${e} ${o} not found`:`${e} not found`;return new t(g.NotFound,n,404)}static rateLimit(e="Too many requests"){return new t(g.RateLimit,e,429)}static authentication(e="Authentication required",o){return new t(g.Authentication,e,401,o)}static business(e,o=400){return new t(g.Business,e,o)}static network(e,o){return new t(g.Network,e,void 0,{cause:o})}static cancelled(e){return new t(g.Cancelled,e)}static file(e,o){return new t(g.File,e,void 0,{filePath:o})}static config(e,o){return new t(g.Config,e,void 0,o)}static api(e,o=500){return new t(g.Api,e,o)}static database(e,o=500){return new t(g.Api,e,o)}static storage(e,o=500){return new t(g.Api,e,o)}get filePath(){return this.details?.filePath}isClientError(){return ue.client.has(this.type)}isNetworkError(){return ue.network.has(this.type)}isAuthError(){return ue.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}};L="ship-",fe=64,ke=L.length+fe,U="token-",he=64,Oe=U.length+he,ge="ship.json";_="https://api.shipstatic.com"});function Ie(t){ye=t}function Q(){if(ye===null)throw p.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ye}var ye,ee=P(()=>{"use strict";w();ye=null});function Ot(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function I(){return $e||Ot()}var $e,G=P(()=>{"use strict";$e=null});async function At(t){let e=(await import("spark-md5")).default;return new Promise((o,n)=>{let s=Math.ceil(t.size/2097152),r=0,l=new e.ArrayBuffer,a=new FileReader,c=()=>{let m=r*2097152,d=Math.min(m+2097152,t.size);a.readAsArrayBuffer(t.slice(m,d))};a.onload=m=>{let d=m.target?.result;if(!d){n(p.business("Failed to read file chunk"));return}l.append(d),r++,r<s?c():o({md5:l.end()})},a.onerror=()=>{n(p.business("Failed to calculate MD5: FileReader error"))},c()})}async function Pt(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",l=>i(p.business(`Failed to read file for MD5: ${l.message}`))),r.on("data",l=>s.update(l)),r.on("end",()=>n({md5:s.digest("hex")}))})}async function te(t){let e=I();if(e==="browser"){if(!(t instanceof Blob))throw p.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return At(t)}if(e==="node"){if(!(Buffer.isBuffer(t)||typeof t=="string"))throw p.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Pt(t)}throw p.business("Unknown or unsupported execution environment for MD5 calculation.")}var Ce=P(()=>{"use strict";G();w()});function Ke(t){try{return $t.parse(t)}catch(e){if(e instanceof K.z.ZodError){let o=e.issues[0],n=o.path.length>0?` at ${o.path.join(".")}`:"";throw p.config(`Configuration validation failed${n}: ${o.message}`)}throw p.config("Configuration validation failed")}}async function Ft(t){try{if(I()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),o=await import("os"),n=e(xe,{searchPlaces:[`.${xe}rc`,"package.json",`${o.homedir()}/.${xe}rc`],stopDir:o.homedir()}),i;if(t?i=n.load(t):i=n.search(),i&&i.config)return Ke(i.config)}catch(e){if(R(e))throw e}return{}}async function Me(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},o=await Ft(t),n={apiUrl:e.apiUrl??o.apiUrl,apiKey:e.apiKey??o.apiKey,deployToken:e.deployToken??o.deployToken};return Ke(n)}var K,xe,$t,Be=P(()=>{"use strict";K=require("zod");w();G();xe="ship",$t=K.z.object({apiUrl:K.z.string().url().optional(),apiKey:K.z.string().optional(),deployToken:K.z.string().optional()}).strict()});function Je(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,Ge.isJunk)(n))return!1;for(let s of o)if(s.startsWith(".")||s.length>255)return!1;let i=o.slice(0,-1);for(let s of i)if(Nt.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var Ge,Nt,qe=P(()=>{"use strict";Ge=require("junk"),Nt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ve(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(l=>l[s]===r))n.push(r);else break}return n.join("/")}function ne(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ve=P(()=>{"use strict"});function We(t,e={}){if(e.flatten===!1)return t.map(n=>({path:ne(n),name:we(n)}));let o=Lt(t);return t.map(n=>{let i=ne(n);if(o){let s=o.endsWith("/")?o:`${o}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=we(n)),{path:i,name:we(n)}})}function Lt(t){if(!t.length)return"";let o=t.map(s=>ne(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(l=>l[s]===r))n.push(r);else break}return n.join("/")}function we(t){return t.split(/[/\\]/).pop()||t}var Ye=P(()=>{"use strict";ve()});var Ze={};Tt(Ze,{processFilesForNode:()=>Ut});function Xe(t,e=new Set){let o=[],n=k.realpathSync(t);if(e.has(n))return o;e.add(n);let i=k.readdirSync(t);for(let s of i){let r=T.join(t,s),l=k.statSync(r);if(l.isDirectory()){let a=Xe(r,e);o.push(...a)}else l.isFile()&&o.push(r)}return o}async function Ut(t,e={}){if(I()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");let o=t.flatMap(u=>{let C=T.resolve(u);try{return k.statSync(C).isDirectory()?Xe(C):[C]}catch{throw p.file(`Path does not exist: ${u}`,u)}}),n=[...new Set(o)],i=Je(n);if(i.length===0)return[];let s=t.map(u=>T.resolve(u)),r=Ve(s.map(u=>{try{return k.statSync(u).isDirectory()?u:T.dirname(u)}catch{return T.dirname(u)}})),l=i.map(u=>{if(r&&r.length>0){let C=T.relative(r,u);if(C&&typeof C=="string"&&!C.startsWith(".."))return C.replace(/\\/g,"/")}return T.basename(u)}),a=We(l,{flatten:e.pathDetect!==!1}),c=[],m=0,d=Q();for(let u=0;u<i.length;u++){let C=i[u],O=a[u].path;try{let A=k.statSync(C);if(A.size===0)continue;if(A.size>d.maxFileSize)throw p.business(`File ${C} is too large. Maximum allowed size is ${d.maxFileSize/(1024*1024)}MB.`);if(m+=A.size,m>d.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${d.maxTotalSize/(1024*1024)}MB.`);let H=k.readFileSync(C),{md5:xt}=await te(H);if(O.includes("\0")||O.includes("/../")||O.startsWith("../")||O.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${O}" for file: ${C}`);c.push({path:O,content:H,size:H.length,md5:xt})}catch(A){if(R(A))throw A;let H=A instanceof Error?A.message:String(A);throw p.file(`Failed to read file "${C}": ${H}`,C)}}if(c.length>d.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return c}var k,T,Qe=P(()=>{"use strict";G();Ce();qe();w();ee();Ye();ve();k=b(require("fs"),1),T=b(require("path"),1)});var gt=require("commander");w();var Z=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()}};var y={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},kt=3e4,j=class extends Z{constructor(e){super(),this.apiUrl=e.apiUrl||_,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??kt,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,o,n){let i=this.mergeHeaders(o.headers),{signal:s,cleanup:r}=this.createTimeoutSignal(o.signal),l={...o,headers:i,credentials:i.Authorization?void 0:"include",signal:s};this.emit("request",e,l);try{let a=await fetch(e,l);return r(),a.ok||await this.handleResponseError(a,n),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,n)}}async request(e,o,n){let{data:i}=await this.executeRequest(e,o,n);return i}async requestWithStatus(e,o,n){return this.executeRequest(e,o,n)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let o=new AbortController,n=setTimeout(()=>o.abort(),this.timeout);if(e){let i=()=>o.abort();e.addEventListener("abort",i),e.aborted&&o.abort()}return{signal:o.signal,cleanup:()=>clearTimeout(n)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,o){let n={};try{if(e.headers.get("content-type")?.includes("application/json")){let r=await e.json();if(r&&typeof r=="object"){let l=r;typeof l.message=="string"&&(n.message=l.message),typeof l.error=="string"&&(n.error=l.error)}}else n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let i=n.message||n.error||`${o} failed`;throw e.status===401?p.authentication(i):p.api(i,e.status)}handleFetchError(e,o){throw R(e)?e:e instanceof Error&&e.name==="AbortError"?p.cancelled(`${o} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?p.network(`${o} failed: ${e.message}`,e):e instanceof Error?p.business(`${o} failed: ${e.message}`):p.business(`${o} failed: Unknown error`)}async deploy(e,o={}){if(!e.length)throw p.business("No files to deploy");for(let r of e)if(!r.md5)throw p.file(`MD5 checksum missing for file: ${r.path}`,r.path);let{body:n,headers:i}=await this.createDeployBody(e,o.labels,o.via),s={};return o.deployToken?s.Authorization=`Bearer ${o.deployToken}`:o.apiKey&&(s.Authorization=`Bearer ${o.apiKey}`),o.caller&&(s["X-Caller"]=o.caller),this.request(`${o.apiUrl||this.apiUrl}${y.DEPLOYMENTS}`,{method:"POST",body:n,headers:{...i,...s},signal:o.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,o){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:o})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,o,n){let i={};o&&(i.deployment=o),n!==void 0&&(i.labels=n);let{data:s,status:r}=await this.requestWithStatus(`${this.apiUrl}${y.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}${y.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async updateDomainLabels(e,o){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:o})},"Update domain labels")}async removeDomain(e){await this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,o){let n={};return e!==void 0&&(n.ttl=e),o!==void 0&&(n.labels=o),this.request(`${this.apiUrl}${y.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${y.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${y.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${y.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${y.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${y.PING}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return this.request(`${this.apiUrl}${y.PING}`,{method:"GET"},"Ping")}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}${y.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA check")).isSPA}};w();ee();w();w();function Se(t={},e={}){let o={apiUrl:t.apiUrl||e.apiUrl||_,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 Fe(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.caller===void 0&&e.caller!==void 0&&(o.caller=e.caller),o}w();Ce();async function It(){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 te(o);return{path:ge,content:o,size:e.length,md5:n}}async function Ne(t,e,o){if(o.spaDetect===!1||t.some(n=>n.path===ge))return t;try{if(await e.checkSPA(t)){let i=await It();return[...t,i]}}catch{}return t}function Le(t){let{getApi:e,ensureInit:o,processInput:n,clientDefaults:i,hasAuth:s}=t;return{create:async(r,l={})=>{await o();let a=i?Fe(l,i):l;if(s&&!s()&&!a.deployToken&&!a.apiKey)throw p.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw p.config("processInput function is not provided.");let c=e(),m=await n(r,a);return m=await Ne(m,c,a),c.deploy(m,a)},list:async()=>(await o(),e().listDeployments()),get:async r=>(await o(),e().getDeployment(r)),set:async(r,l)=>(await o(),e().updateDeploymentLabels(r,l.labels)),remove:async r=>{await o(),await e().removeDeployment(r)}}}function Ue(t){let{getApi:e,ensureInit:o}=t;return{set:async(n,i={})=>{await o();let{deployment:s,labels:r}=i;return s===void 0&&r&&r.length>0?e().updateDomainLabels(n,r):e().setDomain(n,s,r)},list:async()=>(await o(),e().listDomains()),get:async n=>(await o(),e().getDomain(n)),remove:async n=>{await o(),await e().removeDomain(n)},verify:async n=>(await o(),e().verifyDomain(n)),validate:async n=>(await o(),e().validateDomain(n)),dns:async n=>(await o(),e().getDomainDns(n)),records:async n=>(await o(),e().getDomainRecords(n)),share:async n=>(await o(),e().getDomainShare(n))}}function _e(t){let{getApi:e,ensureInit:o}=t;return{get:async()=>(await o(),e().getAccount())}}function je(t){let{getApi:e,ensureInit:o}=t;return{create:async(n={})=>(await o(),e().createToken(n.ttl,n.labels)),list:async()=>(await o(),e().listTokens()),remove:async n=>{await o(),await e().removeToken(n)}}}var oe=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 o=this.resolveInitialConfig(e);this.http=new j({...e,...o,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=Ue(n),this._account=_e(n),this._tokens=je(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=Q(),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}setDeployToken(e){if(!e||typeof e!="string")throw p.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 p.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}};w();G();Be();ee();w();var De=b(require("mime-db"),1),be={};for(let t in De.default){let e=De.default[t];e&&e.extensions&&e.extensions.forEach(o=>{be[o]||(be[o]=t)})}function ze(t){let e=t.includes(".")?t.substring(t.lastIndexOf(".")+1).toLowerCase():"";return be[e]||"application/octet-stream"}async function He(t,e,o){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new n,l=[];for(let d of t){let u=ze(d.path),C;if(Buffer.isBuffer(d.content))C=new i([d.content],d.path,{type:u});else if(typeof Blob<"u"&&d.content instanceof Blob)C=new i([d.content],d.path,{type:u});else throw p.file(`Unsupported file.content type for Node.js: ${d.path}`,d.path);if(!d.md5)throw p.file(`File missing md5 checksum: ${d.path}`,d.path);let O=d.path.startsWith("/")?d.path:"/"+d.path;r.append("files[]",C,O),l.push(d.md5)}r.append("checksums",JSON.stringify(l)),e&&e.length>0&&r.append("labels",JSON.stringify(e)),o&&r.append("via",o);let a=new s(r),c=[];for await(let d of a.encode())c.push(Buffer.from(d));let m=Buffer.concat(c);return{body:m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength),headers:{"Content-Type":a.contentType,"Content-Length":Buffer.byteLength(m).toString()}}}var ie=class extends oe{constructor(e={}){if(I()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return Se(e,{})}async loadFullConfig(){try{let e=await Me(this.clientOptions.configFile),o=Se(this.clientOptions,e);o.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(o.deployToken):o.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(o.apiKey);let n=new j({...this.clientOptions,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();Ie(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,o){let n=typeof e=="string"?[e]:e;if(!Array.isArray(n)||!n.every(s=>typeof s=="string"))throw p.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw p.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(Qe(),Ze));return i(n,o)}getDeployBodyCreator(){return He}};w();var N=require("fs"),pe=b(require("path"),1);var Ee=b(require("columnify"),1),f=require("yoctocolors"),et=["isCreate"],D=(t,e,o)=>o?e:t(e),v=(t,e,o)=>{console.log(e?JSON.stringify({success:t},null,2)+`
3
3
  `:`${D(f.green,t.toLowerCase().replace(/\.$/,""),o)}
4
4
  `)},E=(t,e,o)=>{if(e)console.error(JSON.stringify({error:t},null,2)+`
5
5
  `);else{let n=D(s=>(0,f.inverse)((0,f.red)(s)),`${D(f.hidden,"[",o)}error${D(f.hidden,"]",o)}`,o),i=D(f.red,t.toLowerCase().replace(/\.$/,""),o);console.error(`${n} ${i}
@@ -7,25 +7,25 @@
7
7
  `);else{let n=D(s=>(0,f.inverse)((0,f.yellow)(s)),`${D(f.hidden,"[",o)}warning${D(f.hidden,"]",o)}`,o),i=D(f.yellow,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${i}
8
8
  `)}},M=(t,e,o)=>{if(e)console.log(JSON.stringify({info:t},null,2)+`
9
9
  `);else{let n=D(s=>(0,f.inverse)((0,f.blue)(s)),`${D(f.hidden,"[",o)}info${D(f.hidden,"]",o)}`,o),i=D(f.blue,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${i}
10
- `)}},_t=(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/,D(f.hidden,"T",o)).replace(/Z$/,D(f.hidden,"Z",o)):n},tt=(t,e,o="details",n)=>{if(typeof e=="number"&&(t==="created"||t==="expires"||t==="linked"))return _t(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)},re=(t,e,o,n)=>{if(!t||t.length===0)return"";let i=t[0],s=e||Object.keys(i).filter(a=>i[a]!==void 0&&!et.includes(a)),r=t.map(a=>{let l=a,m={};return s.forEach(d=>{d in l&&l[d]!==void 0&&(m[d]=tt(d,l[d],"table",o))}),m});return(0,Ee.default)(r,{columnSplitter:" ",columns:s,config:s.reduce((a,l)=>(a[l]={headingTransform:m=>D(f.dim,n?.[m]||m,o)},a),{})}).split(`
10
+ `)}},_t=(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/,D(f.hidden,"T",o)).replace(/Z$/,D(f.hidden,"Z",o)):n},tt=(t,e,o="details",n)=>{if(typeof e=="number"&&(t==="created"||t==="expires"||t==="linked"))return _t(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)},re=(t,e,o,n)=>{if(!t||t.length===0)return"";let i=t[0],s=e||Object.keys(i).filter(a=>i[a]!==void 0&&!et.includes(a)),r=t.map(a=>{let c=a,m={};return s.forEach(d=>{d in c&&c[d]!==void 0&&(m[d]=tt(d,c[d],"table",o))}),m});return(0,Ee.default)(r,{columnSplitter:" ",columns:s,config:s.reduce((a,c)=>(a[c]={headingTransform:m=>D(f.dim,n?.[m]||m,o)},a),{})}).split(`
11
11
  `).map(a=>a.replace(/\0/g,"").replace(/\s+$/,"")).join(`
12
12
  `)+`
13
13
  `},J=(t,e)=>{let o=Object.entries(t).filter(([s,r])=>et.includes(s)?!1:r!==void 0);if(o.length===0)return"";let n=o.map(([s,r])=>({property:s+":",value:tt(s,r,"details",e)}));return(0,Ee.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>D(f.dim,s,e)}}}).split(`
14
14
  `).map(s=>s.replace(/\0/g,"")).join(`
15
15
  `)+`
16
- `};function jt(t,e,o){let{isJson:n,noColor:i}=o;if(!t.deployments||t.deployments.length===0){n?console.log(JSON.stringify({deployments:[]},null,2)):(console.log("no deployments found"),console.log());return}let s=["url","tags","created"];console.log(re(t.deployments,s,i,{url:"deployment"}))}function Kt(t,e,o){let{isJson:n,noColor:i}=o;if(!t.domains||t.domains.length===0){n?console.log(JSON.stringify({domains:[]},null,2)):(console.log("no domains found"),console.log());return}let s=["url","deployment","tags","linked","created"];console.log(re(t.domains,s,i,{url:"domain"}))}function Mt(t,e,o){let{isJson:n,noColor:i}=o;if(t.domain&&(e.operation==="set"||e.operation==="update")){let a=e.operation==="update"?"updated":t.isCreate?"created":"updated";w(`${t.domain} domain ${a}`,n,i)}!n&&t._dnsRecords&&t._dnsRecords.length>0&&(console.log(),M("DNS Records to configure:",n,i),t._dnsRecords.forEach(a=>{console.log(` ${a.type}: ${a.name} \u2192 ${a.value}`)})),!n&&t._shareHash&&(console.log(),M(`Setup instructions: https://setup.shipstatic.com/${t._shareHash}/${t.domain}`,n,i));let{_dnsRecords:s,_shareHash:r,...c}=t;console.log(),console.log(J(c,i))}function Bt(t,e,o){let{isJson:n,noColor:i}=o;t.status&&e.operation==="create"&&w(`${t.deployment} deployment created`,n,i),console.log(J(t,i))}function zt(t,e,o){let{noColor:n}=o;console.log(J(t,n))}function Ht(t,e,o){let{isJson:n,noColor:i}=o;t.message&&w(t.message,n,i)}function Gt(t,e,o){let{isJson:n,noColor:i}=o;if(n){console.log(JSON.stringify(t,null,2)),console.log();return}if(t.valid){if(w("domain is valid",n,i),console.log(),t.normalized&&console.log(` normalized: ${t.normalized}`),t.available!==void 0){let s=t.available?"available \u2713":"already taken";console.log(` availability: ${s}`)}console.log()}else E(t.error||"domain is invalid",n,i)}function Jt(t,e,o){let{isJson:n,noColor:i}=o;if(!t.tokens||t.tokens.length===0){n?console.log(JSON.stringify({tokens:[]},null,2)):(console.log("no tokens found"),console.log());return}let s=["token","tags","created","expires"];console.log(re(t.tokens,s,i))}function qt(t,e,o){let{isJson:n,noColor:i}=o;e.operation==="create"&&t.token&&w("token created",n,i),console.log(J(t,i))}function ot(t,e,o){let{isJson:n,noColor:i}=o;if(t===void 0){e.operation==="remove"&&e.resourceType&&e.resourceId?w(`${e.resourceId} ${e.resourceType.toLowerCase()} removed`,n,i):w("removed successfully",n,i);return}if(t===!0||t!==null&&typeof t=="object"&&"success"in t){t===!0||t.success?w("api reachable",n,i):E("api unreachable",n,i);return}if(n&&t!==null&&typeof t=="object"){let s={...t};delete s._dnsRecords,delete s._shareHash,console.log(JSON.stringify(s,null,2)),console.log();return}t!==null&&typeof t=="object"?"deployments"in t?jt(t,e,o):"domains"in t?Kt(t,e,o):"tokens"in t?Jt(t,e,o):"domain"in t?Mt(t,e,o):"deployment"in t?Bt(t,e,o):"token"in t?qt(t,e,o):"email"in t?zt(t,e,o):"valid"in t?Gt(t,e,o):"message"in t?Ht(t,e,o):w("success",n,i):w("success",n,i)}var S=v(require("fs"),1),$=v(require("path"),1),Re=v(require("os"),1);function nt(){let t=process.env.SHELL||"";return t.includes("bash")?"bash":t.includes("zsh")?"zsh":t.includes("fish")?"fish":null}function it(t,e){switch(t){case"bash":return{completionFile:$.join(e,".ship_completion.bash"),profileFile:$.join(e,".bash_profile"),scriptName:"ship.bash"};case"zsh":return{completionFile:$.join(e,".ship_completion.zsh"),profileFile:$.join(e,".zshrc"),scriptName:"ship.zsh"};case"fish":return{completionFile:$.join(e,".config/fish/completions/ship.fish"),profileFile:null,scriptName:"ship.fish"}}}function st(t,e={}){let{isJson:o,noColor:n}=e,i=nt(),s=Re.homedir();if(!i){E(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,o,n);return}let r=it(i,s),c=$.join(t,r.scriptName);try{if(i==="fish"){let l=$.dirname(r.completionFile);S.existsSync(l)||S.mkdirSync(l,{recursive:!0}),S.copyFileSync(c,r.completionFile),w("fish completion installed successfully",o,n),M("please restart your shell to apply the changes",o,n);return}S.copyFileSync(c,r.completionFile);let a=`# ship
16
+ `};function jt(t,e,o){let{isJson:n,noColor:i}=o;if(!t.deployments||t.deployments.length===0){n?console.log(JSON.stringify({deployments:[]},null,2)):(console.log("no deployments found"),console.log());return}let s=["url","labels","created"];console.log(re(t.deployments,s,i,{url:"deployment"}))}function Kt(t,e,o){let{isJson:n,noColor:i}=o;if(!t.domains||t.domains.length===0){n?console.log(JSON.stringify({domains:[]},null,2)):(console.log("no domains found"),console.log());return}let s=["url","deployment","labels","linked","created"];console.log(re(t.domains,s,i,{url:"domain"}))}function Mt(t,e,o){let{isJson:n,noColor:i}=o;if(t.domain&&(e.operation==="set"||e.operation==="update")){let a=e.operation==="update"?"updated":t.isCreate?"created":"updated";v(`${t.domain} domain ${a}`,n,i)}!n&&t._dnsRecords&&t._dnsRecords.length>0&&(console.log(),M("DNS Records to configure:",n,i),t._dnsRecords.forEach(a=>{console.log(` ${a.type}: ${a.name} \u2192 ${a.value}`)})),!n&&t._shareHash&&(console.log(),M(`Setup instructions: https://setup.shipstatic.com/${t._shareHash}/${t.domain}`,n,i));let{_dnsRecords:s,_shareHash:r,...l}=t;console.log(),console.log(J(l,i))}function Bt(t,e,o){let{isJson:n,noColor:i}=o;t.status&&e.operation==="create"&&v(`${t.deployment} deployment created`,n,i),console.log(J(t,i))}function zt(t,e,o){let{noColor:n}=o;console.log(J(t,n))}function Ht(t,e,o){let{isJson:n,noColor:i}=o;t.message&&v(t.message,n,i)}function Gt(t,e,o){let{isJson:n,noColor:i}=o;if(n){console.log(JSON.stringify(t,null,2)),console.log();return}if(t.valid){if(v("domain is valid",n,i),console.log(),t.normalized&&console.log(` normalized: ${t.normalized}`),t.available!==void 0){let s=t.available?"available \u2713":"already taken";console.log(` availability: ${s}`)}console.log()}else E(t.error||"domain is invalid",n,i)}function Jt(t,e,o){let{isJson:n,noColor:i}=o;if(!t.tokens||t.tokens.length===0){n?console.log(JSON.stringify({tokens:[]},null,2)):(console.log("no tokens found"),console.log());return}let s=["token","labels","created","expires"];console.log(re(t.tokens,s,i))}function qt(t,e,o){let{isJson:n,noColor:i}=o;e.operation==="create"&&t.token&&v("token created",n,i),console.log(J(t,i))}function ot(t,e,o){let{isJson:n,noColor:i}=o;if(t===void 0){e.operation==="remove"&&e.resourceType&&e.resourceId?v(`${e.resourceId} ${e.resourceType.toLowerCase()} removed`,n,i):v("removed successfully",n,i);return}if(t===!0||t!==null&&typeof t=="object"&&"success"in t){t===!0||t.success?v("api reachable",n,i):E("api unreachable",n,i);return}if(n&&t!==null&&typeof t=="object"){let s={...t};delete s._dnsRecords,delete s._shareHash,console.log(JSON.stringify(s,null,2)),console.log();return}t!==null&&typeof t=="object"?"deployments"in t?jt(t,e,o):"domains"in t?Kt(t,e,o):"tokens"in t?Jt(t,e,o):"domain"in t?Mt(t,e,o):"deployment"in t?Bt(t,e,o):"token"in t?qt(t,e,o):"email"in t?zt(t,e,o):"valid"in t?Gt(t,e,o):"message"in t?Ht(t,e,o):v("success",n,i):v("success",n,i)}var S=b(require("fs"),1),$=b(require("path"),1),Te=b(require("os"),1);function nt(){let t=process.env.SHELL||"";return t.includes("bash")?"bash":t.includes("zsh")?"zsh":t.includes("fish")?"fish":null}function it(t,e){switch(t){case"bash":return{completionFile:$.join(e,".ship_completion.bash"),profileFile:$.join(e,".bash_profile"),scriptName:"ship.bash"};case"zsh":return{completionFile:$.join(e,".ship_completion.zsh"),profileFile:$.join(e,".zshrc"),scriptName:"ship.zsh"};case"fish":return{completionFile:$.join(e,".config/fish/completions/ship.fish"),profileFile:null,scriptName:"ship.fish"}}}function st(t,e={}){let{isJson:o,noColor:n}=e,i=nt(),s=Te.homedir();if(!i){E(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,o,n);return}let r=it(i,s),l=$.join(t,r.scriptName);try{if(i==="fish"){let c=$.dirname(r.completionFile);S.existsSync(c)||S.mkdirSync(c,{recursive:!0}),S.copyFileSync(l,r.completionFile),v("fish completion installed successfully",o,n),M("please restart your shell to apply the changes",o,n);return}S.copyFileSync(l,r.completionFile);let a=`# ship
17
17
  source '${r.completionFile}'
18
- # ship end`;if(r.profileFile){if(S.existsSync(r.profileFile)){let l=S.readFileSync(r.profileFile,"utf-8");if(!l.includes("# ship")||!l.includes("# ship end")){let m=l.length>0&&!l.endsWith(`
18
+ # ship end`;if(r.profileFile){if(S.existsSync(r.profileFile)){let c=S.readFileSync(r.profileFile,"utf-8");if(!c.includes("# ship")||!c.includes("# ship end")){let m=c.length>0&&!c.endsWith(`
19
19
  `)?`
20
- `:"";S.appendFileSync(r.profileFile,m+a)}}else S.writeFileSync(r.profileFile,a);w(`completion script installed for ${i}`,o,n),se(`run "source ${r.profileFile}" or restart your shell`,o,n)}}catch(a){let l=a instanceof Error?a.message:String(a);E(`could not install completion script: ${l}`,o,n)}}function rt(t={}){let{isJson:e,noColor:o}=t,n=nt(),i=Re.homedir();if(!n){E(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,e,o);return}let s=it(n,i);try{if(n==="fish"){S.existsSync(s.completionFile)?(S.unlinkSync(s.completionFile),w("fish completion uninstalled successfully",e,o)):se("fish completion was not installed",e,o),M("please restart your shell to apply the changes",e,o);return}if(S.existsSync(s.completionFile)&&S.unlinkSync(s.completionFile),!s.profileFile)return;if(!S.existsSync(s.profileFile)){E("profile file not found",e,o);return}let r=S.readFileSync(s.profileFile,"utf-8"),c=r.split(`
21
- `),a=[],l=0,m=!1;for(;l<c.length;)if(c[l].trim()==="# ship"){for(m=!0,l++;l<c.length&&c[l].trim()!=="# ship end";)l++;l<c.length&&l++}else a.push(c[l]),l++;if(m){let d=r.endsWith(`
20
+ `:"";S.appendFileSync(r.profileFile,m+a)}}else S.writeFileSync(r.profileFile,a);v(`completion script installed for ${i}`,o,n),se(`run "source ${r.profileFile}" or restart your shell`,o,n)}}catch(a){let c=a instanceof Error?a.message:String(a);E(`could not install completion script: ${c}`,o,n)}}function rt(t={}){let{isJson:e,noColor:o}=t,n=nt(),i=Te.homedir();if(!n){E(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,e,o);return}let s=it(n,i);try{if(n==="fish"){S.existsSync(s.completionFile)?(S.unlinkSync(s.completionFile),v("fish completion uninstalled successfully",e,o)):se("fish completion was not installed",e,o),M("please restart your shell to apply the changes",e,o);return}if(S.existsSync(s.completionFile)&&S.unlinkSync(s.completionFile),!s.profileFile)return;if(!S.existsSync(s.profileFile)){E("profile file not found",e,o);return}let r=S.readFileSync(s.profileFile,"utf-8"),l=r.split(`
21
+ `),a=[],c=0,m=!1;for(;c<l.length;)if(l[c].trim()==="# ship"){for(m=!0,c++;c<l.length&&l[c].trim()!=="# ship end";)c++;c<l.length&&c++}else a.push(l[c]),c++;if(m){let d=r.endsWith(`
22
22
  `),u=a.length===0?"":a.join(`
23
23
  `)+(d?`
24
- `:"");S.writeFileSync(s.profileFile,u),w(`completion script uninstalled for ${n}`,e,o),se(`run "source ${s.profileFile}" or restart your shell`,e,o)}else E("completion was not found in profile",e,o)}catch(r){let c=r instanceof Error?r.message:String(r);E(`could not uninstall completion script: ${c}`,e,o)}}var ct=require("readline/promises"),F=require("fs"),lt=require("os"),dt=require("path");T();var ae=require("yoctocolors"),B=(0,dt.join)((0,lt.homedir)(),".shiprc");function at(t){return t.length<13?t:t.slice(0,9)+"..."+t.slice(-4)}function pt(){try{return(0,F.existsSync)(B)?JSON.parse((0,F.readFileSync)(B,"utf-8")):{}}catch{return{}}}async function mt(t={}){let{noColor:e,json:o}=t,n=m=>e?m:(0,ae.dim)(m),i=m=>e?m:(0,ae.green)(m);if(o){let m=pt(),d=typeof m.apiKey=="string"?m.apiKey:void 0,u=typeof m.apiUrl=="string"?m.apiUrl:void 0;console.log(JSON.stringify({path:B,exists:(0,F.existsSync)(B),...d?{apiKey:at(d)}:{},...u&&u!==_?{apiUrl:u}:{}},null,2)+`
25
- `);return}let s=pt(),r=typeof s.apiKey=="string"?s.apiKey:void 0,c=(0,ct.createInterface)({input:process.stdin,output:process.stdout});console.log("");let a=r?` API Key (${n(at(r))}): `:" API Key: ",l;try{l=(await c.question(a)).trim()}finally{c.close()}l&&(X(l),s.apiKey=l),(0,F.writeFileSync)(B,JSON.stringify(s,null,2)+`
24
+ `:"");S.writeFileSync(s.profileFile,u),v(`completion script uninstalled for ${n}`,e,o),se(`run "source ${s.profileFile}" or restart your shell`,e,o)}else E("completion was not found in profile",e,o)}catch(r){let l=r instanceof Error?r.message:String(r);E(`could not uninstall completion script: ${l}`,e,o)}}var lt=require("readline/promises"),F=require("fs"),ct=require("os"),dt=require("path");w();var ae=require("yoctocolors"),B=(0,dt.join)((0,ct.homedir)(),".shiprc");function at(t){return t.length<13?t:t.slice(0,9)+"..."+t.slice(-4)}function pt(){try{return(0,F.existsSync)(B)?JSON.parse((0,F.readFileSync)(B,"utf-8")):{}}catch{return{}}}async function mt(t={}){let{noColor:e,json:o}=t,n=m=>e?m:(0,ae.dim)(m),i=m=>e?m:(0,ae.green)(m);if(o){let m=pt(),d=typeof m.apiKey=="string"?m.apiKey:void 0,u=typeof m.apiUrl=="string"?m.apiUrl:void 0;console.log(JSON.stringify({path:B,exists:(0,F.existsSync)(B),...d?{apiKey:at(d)}:{},...u&&u!==_?{apiUrl:u}:{}},null,2)+`
25
+ `);return}let s=pt(),r=typeof s.apiKey=="string"?s.apiKey:void 0,l=(0,lt.createInterface)({input:process.stdin,output:process.stdout});console.log("");let a=r?` API Key (${n(at(r))}): `:" API Key: ",c;try{c=(await l.question(a)).trim()}finally{l.close()}c&&(X(c),s.apiKey=c),(0,F.writeFileSync)(B,JSON.stringify(s,null,2)+`
26
26
  `),console.log(`
27
27
  ${i("saved to")} ${n(B)}
28
- `)}T();function ut(t){return b(t)?t:t instanceof Error?p.business(t.message):p.business(String(t??"Unknown error"))}function ft(t,e,o){if(t.isAuthError())return o?.apiKey?"authentication failed: invalid API key":o?.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 n=t.details?.url;return n?`network error: could not reach ${n}`:"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 ht(t,e){return JSON.stringify({error:t,...e?{details:e}:{}},null,2)}var ce=require("yoctocolors");function Vt(){let t=[pe.resolve(__dirname,"../package.json"),pe.resolve(__dirname,"../../package.json")];for(let e of t)try{return JSON.parse((0,N.readFileSync)(e,"utf-8"))}catch{}return{version:"0.0.0"}}var Wt=Vt(),h=new gt.Command;h.exitOverride(t=>{(t.code==="commander.help"||t.code==="commander.version"||t.exitCode===0)&&process.exit(t.exitCode||0);let e=h.opts(),o=t.message||"unknown command error";o=o.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),E(o,e.json,e.noColor),e.json||q(e.noColor),process.exit(t.exitCode||1)}).configureOutput({writeErr:t=>{t.startsWith("error:")||process.stderr.write(t)},writeOut:t=>process.stdout.write(t)});function q(t){let e=i=>t?i:(0,ce.bold)(i),o=i=>t?i:(0,ce.dim)(i),n=`${e("USAGE")}
28
+ `)}w();function ut(t){return R(t)?t:t instanceof Error?p.business(t.message):p.business(String(t??"Unknown error"))}function ft(t,e,o){if(t.isAuthError())return o?.apiKey?"authentication failed: invalid API key":o?.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 n=t.details?.url;return n?`network error: could not reach ${n}`:"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 ht(t,e){return JSON.stringify({error:t,...e?{details:e}:{}},null,2)}var le=require("yoctocolors");function Vt(){let t=[pe.resolve(__dirname,"../package.json"),pe.resolve(__dirname,"../../package.json")];for(let e of t)try{return JSON.parse((0,N.readFileSync)(e,"utf-8"))}catch{}return{version:"0.0.0"}}var Wt=Vt(),h=new gt.Command;h.exitOverride(t=>{(t.code==="commander.help"||t.code==="commander.version"||t.exitCode===0)&&process.exit(t.exitCode||0);let e=h.opts(),o=t.message||"unknown command error";o=o.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),E(o,e.json,e.noColor),e.json||q(e.noColor),process.exit(t.exitCode||1)}).configureOutput({writeErr:t=>{t.startsWith("error:")||process.stderr.write(t)},writeOut:t=>process.stdout.write(t)});function q(t){let e=i=>t?i:(0,le.bold)(i),o=i=>t?i:(0,le.dim)(i),n=`${e("USAGE")}
29
29
  ship <path> \u{1F680} Deploy static sites with simplicity
30
30
 
31
31
  ${e("COMMANDS")}
@@ -33,12 +33,12 @@ ${e("COMMANDS")}
33
33
  ship deployments list List all deployments
34
34
  ship deployments create <path> Create deployment from directory
35
35
  ship deployments get <id> Show deployment information
36
- ship deployments set <id> Set deployment tags
36
+ ship deployments set <id> Set deployment labels
37
37
  ship deployments remove <id> Delete deployment permanently
38
38
 
39
39
  \u{1F30E} ${e("Domains")}
40
40
  ship domains list List all domains
41
- ship domains set <name> [deployment] Point domain to deployment, or update tags
41
+ ship domains set <name> [deployment] Create domain, link to deployment, or update labels
42
42
  ship domains get <name> Show domain information
43
43
  ship domains validate <name> Check if domain name is valid and available
44
44
  ship domains verify <name> Trigger DNS verification for external domain
@@ -68,7 +68,7 @@ ${e("FLAGS")}
68
68
  --version Show version information
69
69
 
70
70
  ${o("Please report any issues to https://github.com/shipstatic/ship/issues")}
71
- `;console.log(n)}function V(t,e=[]){return e.concat([t])}function le(t,e){let o=t?.tag?.length?t.tag:e?.tag;return o?.length?o:void 0}function W(t){return(...e)=>{let o=de(h),n=e[e.length-1];if(n?.args?.length){let i=n.args.find(s=>!t.includes(s));i&&E(`unknown command '${i}'`,o.json,o.noColor)}q(o.noColor),process.exit(1)}}function de(t){let e=t.optsWithGlobals?t.optsWithGlobals():t.opts();return e.color===!1&&(e.noColor=!0),e}function yt(t,e){let o=h.opts(),n=ut(t),i=ft(n,e,{apiKey:o.apiKey,deployToken:o.deployToken});o.json?console.error(ht(i,n.details)+`
72
- `):(E(i,o.json,o.noColor),n.isValidationError()&&i.includes("unknown command")&&q(o.noColor)),process.exit(1)}function x(t,e){return async function(...o){let n=de(this);try{let i=Yt(),s=await t(i,...o),r=e?{operation:e.operation,resourceType:e.resourceType,resourceId:e.getResourceId?e.getResourceId(...o):void 0}:{};Xt(s,r,n)}catch(i){let s=e?{operation:e.operation,resourceType:e.resourceType,resourceId:e.getResourceId?e.getResourceId(...o):void 0}:void 0;yt(i,s)}}}function Yt(){let{config:t,apiUrl:e,apiKey:o,deployToken:n}=h.opts();return new ie({configFile:t,apiUrl:e,apiKey:o,deployToken:n})}async function St(t,e,o,n){if(!(0,N.existsSync)(e))throw p.file(`${e} path does not exist`,e);let i=(0,N.statSync)(e);if(!i.isDirectory()&&!i.isFile())throw p.file(`${e} path must be a file or directory`,e);let s={via:"cli"},r=le(o,h.opts());r&&(s.tags=r),o?.noPathDetect!==void 0&&(s.pathDetect=!o.noPathDetect),o?.noSpaDetect!==void 0&&(s.spaDetect=!o.noSpaDetect);let c=new AbortController;s.signal=c.signal;let a=null,l=n?de(n):{};if(process.stdout.isTTY&&!l.json&&!l.noColor){let{default:d}=await import("yocto-spinner");a=d({text:"uploading\u2026"}).start()}let m=()=>{c.abort(),a&&a.stop(),process.exit(130)};process.on("SIGINT",m);try{let d=await t.deployments.create(e,s);return process.removeListener("SIGINT",m),a&&a.stop(),d}catch(d){throw process.removeListener("SIGINT",m),a&&a.stop(),d}}function Xt(t,e,o){let n=o||h.opts();ot(t,e,{isJson:n.json,noColor:n.noColor})}h.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(Wt.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,e)=>{let o=t.opts();if(o.help){let n=o.color===!1||o.noColor;q(n),process.exit(0)}});h.hook("preAction",(t,e)=>{let o=t.opts();try{o.apiKey&&typeof o.apiKey=="string"&&X(o.apiKey),o.deployToken&&typeof o.deployToken=="string"&&Ae(o.deployToken),o.apiUrl&&typeof o.apiUrl=="string"&&Pe(o.apiUrl)}catch(n){if(b(n)){let i=o.color===!1||o.noColor;E(n.message,o.json,i),process.exit(1)}throw n}});h.command("ping").description("Check API connectivity").action(x(t=>t.ping()));h.command("whoami").description("Get current account information").action(x(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var Y=h.command("deployments").description("Manage deployments").enablePositionalOptions().action(W(["list","create","get","set","remove"]));Y.command("list").description("List all deployments").action(x(t=>t.deployments.list()));Y.command("create <path>").description("Create deployment from file or directory").passThroughOptions().option("--tag <tag>","Tag to add (can be repeated)",V,[]).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 St(t,e,o,this)},{operation:"create"}));Y.command("get <deployment>").description("Show deployment information").action(x((t,e)=>t.deployments.get(e),{operation:"get",resourceType:"Deployment",getResourceId:t=>t}));Y.command("set <deployment>").description("Set deployment tags").passThroughOptions().option("--tag <tag>","Tag to set (can be repeated)",V,[]).action(x(async(t,e,o)=>{let n=le(o,h.opts())||[];return t.deployments.set(e,{tags:n})},{operation:"set",resourceType:"Deployment",getResourceId:t=>t}));Y.command("remove <deployment>").description("Delete deployment permanently").action(x((t,e)=>t.deployments.remove(e),{operation:"remove",resourceType:"Deployment",getResourceId:t=>t}));var z=h.command("domains").description("Manage domains").enablePositionalOptions().action(W(["list","get","set","validate","verify","remove"]));z.command("list").description("List all domains").action(x(t=>t.domains.list()));z.command("get <name>").description("Show domain information").action(x((t,e)=>t.domains.get(e),{operation:"get",resourceType:"Domain",getResourceId:t=>t}));z.command("validate <name>").description("Check if domain name is valid and available").action(x((t,e)=>t.domains.validate(e),{operation:"validate",resourceType:"Domain",getResourceId:t=>t}));z.command("verify <name>").description("Trigger DNS verification for external domain").action(x((t,e)=>t.domains.verify(e),{operation:"verify",resourceType:"Domain",getResourceId:t=>t}));z.command("set <name> [deployment]").description("Point domain to deployment, or update tags").passThroughOptions().option("--tag <tag>","Tag to set (can be repeated)",V,[]).action(x(async(t,e,o,n)=>{let i=le(n,h.opts());if(!o&&(!i||i.length===0))throw p.validation("Must provide deployment or --tag");let s={};o&&(s.deployment=o),i&&i.length>0&&(s.tags=i);let r=await t.domains.set(e,s);if(r.isCreate&&e.includes("."))try{let[c,a]=await Promise.all([t.domains.records(e),t.domains.share(e)]);return{...r,_dnsRecords:c.records,_shareHash:a.hash}}catch{}return r},{operation:"set",resourceType:"Domain",getResourceId:t=>t}));z.command("remove <name>").description("Delete domain permanently").action(x((t,e)=>t.domains.remove(e),{operation:"remove",resourceType:"Domain",getResourceId:t=>t}));var be=h.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(W(["list","create","remove"]));be.command("list").description("List all tokens").action(x(t=>t.tokens.list()));be.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 set (can be repeated)",V,[]).action(x((t,e)=>{let o={};e?.ttl!==void 0&&(o.ttl=e.ttl);let n=le(e,h.opts());return n&&n.length>0&&(o.tags=n),t.tokens.create(o)},{operation:"create",resourceType:"Token"}));be.command("remove <token>").description("Delete token permanently").action(x((t,e)=>t.tokens.remove(e),{operation:"remove",resourceType:"Token",getResourceId:t=>t}));var Zt=h.command("account").description("Manage account").action(W(["get"]));Zt.command("get").description("Show account information").action(x(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var Ct=h.command("completion").description("Setup shell completion").action(W(["install","uninstall"]));Ct.command("install").description("Install shell completion script").action(()=>{let t=h.opts(),e=pe.resolve(__dirname,"completions");st(e,{isJson:t.json,noColor:t.noColor})});Ct.command("uninstall").description("Uninstall shell completion script").action(()=>{let t=h.opts();rt({isJson:t.json,noColor:t.noColor})});h.command("config").description("Create or update ~/.shiprc configuration").action(async()=>{let t=de(h);try{await mt({noColor:t.noColor,json:t.json})}catch(e){yt(e)}});h.argument("[path]","Path to deploy").option("--tag <tag>","Tag to add (can be repeated)",V,[]).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=h.opts(),i=n.color===!1||n.noColor;q(i),process.exit(0)}if(!(0,N.existsSync)(e)&&!e.includes("/")&&!e.includes("\\")&&!e.includes(".")&&!e.startsWith("~"))throw p.validation(`unknown command '${e}'`);return St(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","config","completion"].join(n?`
71
+ `;console.log(n)}function V(t,e=[]){return e.concat([t])}function ce(t,e){let o=t?.label?.length?t.label:e?.label;return o?.length?o:void 0}function W(t){return(...e)=>{let o=de(h),n=e[e.length-1];if(n?.args?.length){let i=n.args.find(s=>!t.includes(s));i&&E(`unknown command '${i}'`,o.json,o.noColor)}q(o.noColor),process.exit(1)}}function de(t){let e=t.optsWithGlobals?t.optsWithGlobals():t.opts();return e.color===!1&&(e.noColor=!0),e}function yt(t,e){let o=h.opts(),n=ut(t),i=ft(n,e,{apiKey:o.apiKey,deployToken:o.deployToken});o.json?console.error(ht(i,n.details)+`
72
+ `):(E(i,o.json,o.noColor),n.isValidationError()&&i.includes("unknown command")&&q(o.noColor)),process.exit(1)}function x(t,e){return async function(...o){let n=de(this);try{let i=Yt(),s=await t(i,...o),r=e?{operation:e.operation,resourceType:e.resourceType,resourceId:e.getResourceId?e.getResourceId(...o):void 0}:{};Xt(s,r,n)}catch(i){let s=e?{operation:e.operation,resourceType:e.resourceType,resourceId:e.getResourceId?e.getResourceId(...o):void 0}:void 0;yt(i,s)}}}function Yt(){let{config:t,apiUrl:e,apiKey:o,deployToken:n}=h.opts();return new ie({configFile:t,apiUrl:e,apiKey:o,deployToken:n})}async function St(t,e,o,n){if(!(0,N.existsSync)(e))throw p.file(`${e} path does not exist`,e);let i=(0,N.statSync)(e);if(!i.isDirectory()&&!i.isFile())throw p.file(`${e} path must be a file or directory`,e);let s={via:"cli"},r=ce(o,h.opts());r&&(s.labels=r),o?.noPathDetect!==void 0&&(s.pathDetect=!o.noPathDetect),o?.noSpaDetect!==void 0&&(s.spaDetect=!o.noSpaDetect);let l=new AbortController;s.signal=l.signal;let a=null,c=n?de(n):{};if(process.stdout.isTTY&&!c.json&&!c.noColor){let{default:d}=await import("yocto-spinner");a=d({text:"uploading\u2026"}).start()}let m=()=>{l.abort(),a&&a.stop(),process.exit(130)};process.on("SIGINT",m);try{let d=await t.deployments.create(e,s);return process.removeListener("SIGINT",m),a&&a.stop(),d}catch(d){throw process.removeListener("SIGINT",m),a&&a.stop(),d}}function Xt(t,e,o){let n=o||h.opts();ot(t,e,{isJson:n.json,noColor:n.noColor})}h.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(Wt.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,e)=>{let o=t.opts();if(o.help){let n=o.color===!1||o.noColor;q(n),process.exit(0)}});h.hook("preAction",(t,e)=>{let o=t.opts();try{o.apiKey&&typeof o.apiKey=="string"&&X(o.apiKey),o.deployToken&&typeof o.deployToken=="string"&&Ae(o.deployToken),o.apiUrl&&typeof o.apiUrl=="string"&&Pe(o.apiUrl)}catch(n){if(R(n)){let i=o.color===!1||o.noColor;E(n.message,o.json,i),process.exit(1)}throw n}});h.command("ping").description("Check API connectivity").action(x(t=>t.ping()));h.command("whoami").description("Get current account information").action(x(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var Y=h.command("deployments").description("Manage deployments").enablePositionalOptions().action(W(["list","create","get","set","remove"]));Y.command("list").description("List all deployments").action(x(t=>t.deployments.list()));Y.command("create <path>").description("Create deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",V,[]).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 St(t,e,o,this)},{operation:"create"}));Y.command("get <deployment>").description("Show deployment information").action(x((t,e)=>t.deployments.get(e),{operation:"get",resourceType:"Deployment",getResourceId:t=>t}));Y.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",V,[]).action(x(async(t,e,o)=>{let n=ce(o,h.opts())||[];return t.deployments.set(e,{labels:n})},{operation:"set",resourceType:"Deployment",getResourceId:t=>t}));Y.command("remove <deployment>").description("Delete deployment permanently").action(x((t,e)=>t.deployments.remove(e),{operation:"remove",resourceType:"Deployment",getResourceId:t=>t}));var z=h.command("domains").description("Manage domains").enablePositionalOptions().action(W(["list","get","set","validate","verify","remove"]));z.command("list").description("List all domains").action(x(t=>t.domains.list()));z.command("get <name>").description("Show domain information").action(x((t,e)=>t.domains.get(e),{operation:"get",resourceType:"Domain",getResourceId:t=>t}));z.command("validate <name>").description("Check if domain name is valid and available").action(x((t,e)=>t.domains.validate(e),{operation:"validate",resourceType:"Domain",getResourceId:t=>t}));z.command("verify <name>").description("Trigger DNS verification for external domain").action(x((t,e)=>t.domains.verify(e),{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)",V,[]).action(x(async(t,e,o,n)=>{let i=ce(n,h.opts()),s={};o&&(s.deployment=o),i&&i.length>0&&(s.labels=i);let r=await t.domains.set(e,s);if(r.isCreate&&e.includes("."))try{let[l,a]=await Promise.all([t.domains.records(e),t.domains.share(e)]);return{...r,_dnsRecords:l.records,_shareHash:a.hash}}catch{}return r},{operation:"set",resourceType:"Domain",getResourceId:t=>t}));z.command("remove <name>").description("Delete domain permanently").action(x((t,e)=>t.domains.remove(e),{operation:"remove",resourceType:"Domain",getResourceId:t=>t}));var Re=h.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(W(["list","create","remove"]));Re.command("list").description("List all tokens").action(x(t=>t.tokens.list()));Re.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)",V,[]).action(x((t,e)=>{let o={};e?.ttl!==void 0&&(o.ttl=e.ttl);let n=ce(e,h.opts());return n&&n.length>0&&(o.labels=n),t.tokens.create(o)},{operation:"create",resourceType:"Token"}));Re.command("remove <token>").description("Delete token permanently").action(x((t,e)=>t.tokens.remove(e),{operation:"remove",resourceType:"Token",getResourceId:t=>t}));var Zt=h.command("account").description("Manage account").action(W(["get"]));Zt.command("get").description("Show account information").action(x(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var Ct=h.command("completion").description("Setup shell completion").action(W(["install","uninstall"]));Ct.command("install").description("Install shell completion script").action(()=>{let t=h.opts(),e=pe.resolve(__dirname,"completions");st(e,{isJson:t.json,noColor:t.noColor})});Ct.command("uninstall").description("Uninstall shell completion script").action(()=>{let t=h.opts();rt({isJson:t.json,noColor:t.noColor})});h.command("config").description("Create or update ~/.shiprc configuration").action(async()=>{let t=de(h);try{await mt({noColor:t.noColor,json:t.json})}catch(e){yt(e)}});h.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",V,[]).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=h.opts(),i=n.color===!1||n.noColor;q(i),process.exit(0)}if(!(0,N.existsSync)(e)&&!e.includes("/")&&!e.includes("\\")&&!e.includes(".")&&!e.startsWith("~"))throw p.validation(`unknown command '${e}'`);return St(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","tokens","account","config","completion"].join(n?`
73
73
  `:" ")),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{h.parse(process.argv)}catch(t){if(t instanceof Error&&"code"in t){let e=t.code,o=t.exitCode;e?.startsWith("commander.")&&process.exit(o||1)}throw t}
74
74
  //# sourceMappingURL=cli.cjs.map