@shipstatic/ship 1.2.0 → 1.3.0

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,38 +1,39 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var $t=Object.create;var Se=Object.defineProperty;var Nt=Object.getOwnPropertyDescriptor;var _t=Object.getOwnPropertyNames;var Ut=Object.getPrototypeOf,Mt=Object.prototype.hasOwnProperty;var $=(e,t)=>()=>(e&&(t=e(e=0)),t);var jt=(e,t)=>{for(var o in t)Se(e,o,{get:t[o],enumerable:!0})},Gt=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of _t(t))!Mt.call(e,i)&&i!==o&&Se(e,i,{get:()=>t[i],enumerable:!(n=Nt(t,i))||n.enumerable});return e};var R=(e,t,o)=>(o=e!=null?$t(Ut(e)):{},Gt(t||!e||!e.__esModule?Se(o,"default",{value:e,enumerable:!0}):o,e));function O(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function be(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return!1;let o=e.slice(t+1).toLowerCase();return zt.has(o)}function $e(e){return Bt.test(e)}function we(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(o=>Ee.has(o))}function ne(e){if(!e.startsWith(N.PREFIX))throw l.validation(`API key must start with "${N.PREFIX}"`);if(e.length!==N.TOTAL_LENGTH)throw l.validation(`API key must be ${N.TOTAL_LENGTH} characters total (${N.PREFIX} + ${N.HEX_LENGTH} hex chars)`);let t=e.slice(N.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw l.validation(`API key must contain ${N.HEX_LENGTH} hexadecimal characters after "${N.PREFIX}" prefix`)}function _e(e){if(!e.startsWith(_.PREFIX))throw l.validation(`Deploy token must start with "${_.PREFIX}"`);if(e.length!==_.TOTAL_LENGTH)throw l.validation(`Deploy token must be ${_.TOTAL_LENGTH} characters total (${_.PREFIX} + ${_.HEX_LENGTH} hex chars)`);let t=e.slice(_.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw l.validation(`Deploy token must contain ${_.HEX_LENGTH} hexadecimal characters after "${_.PREFIX}" prefix`)}function Ue(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw l.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw l.validation("API URL must not contain a path");if(t.search||t.hash)throw l.validation("API URL must not contain query parameters or fragments")}catch(t){throw O(t)?t:l.validation("API URL must be a valid URL")}}function ve(e){if(e==null)return;if(typeof e!="string")throw l.validation("Password must be a string");let t=e.trim();if(t.length<oe.MIN_LENGTH||t.length>oe.MAX_LENGTH)throw l.validation(`Password must be between ${oe.MIN_LENGTH} and ${oe.MAX_LENGTH} characters`);return t}var m,Ht,De,Kt,l,zt,Bt,Ee,N,_,Te,Ne,z,j,Me,oe,E=$(()=>{"use strict";m={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},Ht=new Set([m.Network,m.Cancelled,m.File,m.Config]),De={client:new Set([m.Business,m.Config,m.File,m.Forbidden,m.Validation]),network:new Set([m.Network]),auth:new Set([m.Authentication])},Kt=new Set(Object.values(m).filter(e=>!Ht.has(e))),l=class e extends Error{type;status;details;constructor(t,o,n,i){super(o),this.type=t,this.status=n,this.details=i,this.name="ShipError"}toResponse(){let t=this.details,o=this.type===m.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:o}}static async fromHttpResponse(t,o){let n,i,s;try{if(t.headers.get("content-type")?.includes("application/json")){let c=await t.json();if(c&&typeof c=="object"){let a=c;typeof a.message=="string"?n=a.message:typeof a.error=="string"&&(n=a.error),i=a.details,typeof a.error=="string"&&Kt.has(a.error)&&(s=a.error)}}else{let c=await t.text();c&&(n=c)}}catch{}n=n||`${o||"Request"} failed with status ${t.status}`;let r=s??(t.status===401?m.Authentication:t.status===403?m.Forbidden:t.status===429?m.RateLimit:m.Api);return new e(r,n,t.status,i)}static fromFetchError(t,o){if(O(t))return t;let n=o||"Request";return t instanceof Error?t.name==="AbortError"?e.cancelled(`${n} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?e.network(`${n} failed: ${t.message}`,{cause:t}):new e(m.Api,`${n} failed: ${t.message}`):new e(m.Api,`${n} failed: Unknown error`)}static validation(t,o){return new e(m.Validation,t,400,o)}static notFound(t,o){let n=o?`${t} ${o} not found`:`${t} not found`;return new e(m.NotFound,n,404)}static forbidden(t,o){return new e(m.Forbidden,t,403,o)}static rateLimit(t="Too many requests",o){return new e(m.RateLimit,t,429,o)}static authentication(t="Authentication required",o){return new e(m.Authentication,t,401,o)}static business(t,o=400,n){return new e(m.Business,t,o,n)}static network(t,o){return new e(m.Network,t,void 0,o)}static cancelled(t,o){return new e(m.Cancelled,t,void 0,o)}static file(t,o){return new e(m.File,t,void 0,o)}static config(t,o){return new e(m.Config,t,void 0,o)}static api(t,o=500,n){return new e(m.Api,t,o,n)}isClientError(){return De.client.has(this.type)}isNetworkError(){return De.network.has(this.type)}isAuthError(){return De.auth.has(this.type)}isType(t){return this.type===t}};zt=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"]);Bt=/[\x00-\x1f\x7f#?%\\<>"]/;Ee=new Set(["node_modules","package.json"]);N={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},_={PREFIX:"token-",HEX_LENGTH:64,TOTAL_LENGTH:70},Te="ship.json",Ne={rewrites:[{source:"/(.*)",destination:"/index.html"}]};z="https://api.shipstatic.com",j={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},Me=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,oe={MIN_LENGTH:6,MAX_LENGTH:128}});async function ro(e){let t=(await import("spark-md5")).default,o=new t.ArrayBuffer,n=2097152;for(let i=0;i<e.size;i+=n){let s=Math.min(i+n,e.size);o.append(await e.slice(i,s).arrayBuffer())}return{md5:o.end()}}async function ao(e){let{createHash:t}=await import("crypto"),o=t("md5");return o.update(e),{md5:o.digest("hex")}}async function lo(e){let{createHash:t}=await import("crypto"),{createReadStream:o}=await import("fs");return new Promise((n,i)=>{let s=t("md5"),r=o(e);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",()=>n({md5:s.digest("hex")}))})}async function le(e){if(e instanceof Blob)return ro(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return ao(e);if(typeof e=="string")return lo(e);throw l.business("Invalid input for MD5 calculation")}var Oe=$(()=>{"use strict";E()});function co(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function V(){return rt||co()}var rt,ce=$(()=>{"use strict";rt=null});function pt(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(n=>n&&we(n)))throw l.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(o=>{if(!o)return!1;let n=o.replace(/\\/g,"/").split("/").filter(Boolean);if(n.length===0)return!0;let i=n[n.length-1];if((0,lt.isJunk)(i))return!1;for(let r of n)if(r!==".well-known"&&(r.startsWith(".")||r.length>255))return!1;let s=n.slice(0,-1);for(let r of s)if(fo.some(p=>r.toLowerCase()===p.toLowerCase()))return!1;return!0})}var lt,fo,ct=$(()=>{"use strict";lt=require("junk");E();fo=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function dt(e){if(!e||e.length===0)return"";let t=e.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let o=t.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(p=>p[s]===r))n.push(r);else break}return n.join("/")}function fe(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Ie=$(()=>{"use strict"});function mt(e,t={}){if(t.flatten===!1)return e.map(n=>({path:fe(n),name:ke(n)}));let o=ho(e);return e.map(n=>{let i=fe(n);if(o){let s=o.endsWith("/")?o:`${o}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=ke(n)),{path:i,name:ke(n)}})}function ho(e){if(!e.length)return"";let o=e.map(s=>fe(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(p=>p[s]===r))n.push(r);else break}return n.join("/")}function ke(e){return e.split(/[/\\]/).pop()||e}var ut=$(()=>{"use strict";Ie()});function ft(e){if($e(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,o=e.split("/").pop()||e;return t.test(o)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}var ht=$(()=>{"use strict";E()});function yt(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw l.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function gt(e,t){let o=ft(e);if(!o.valid)throw l.business(o.reason||"Invalid file name");if(be(e))throw l.business(`File extension not allowed: "${t}"`)}var St=$(()=>{"use strict";E();ht()});var bt={};jt(bt,{processFilesForNode:()=>yo});function Dt(e,t=new Set){let o=[],n=x.realpathSync(e);if(t.has(n))return o;t.add(n);let i=x.readdirSync(e);for(let s of i){let r=I.join(e,s),p=x.statSync(r);if(p.isDirectory()){let c=Dt(r,t);o.push(...c)}else p.isFile()&&o.push(r)}return o}async function yo(e,t={},o){if(V()!=="node")throw l.business("processFilesForNode can only be called in Node.js environment.");for(let u of e){let b=I.resolve(u);try{if(x.statSync(b).isDirectory()){let k=x.readdirSync(b).find(L=>Ee.has(L));if(k)throw l.business(`"${k}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(k){if(O(k))throw k}}let n=e.flatMap(u=>{let b=I.resolve(u);try{return x.statSync(b).isDirectory()?Dt(b):[b]}catch{throw l.file(`Path does not exist: ${u}`,{filePath:u})}}),i=[...new Set(n)],s=e.map(u=>I.resolve(u)),r=dt(s.map(u=>{try{return x.statSync(u).isDirectory()?u:I.dirname(u)}catch{return I.dirname(u)}})),p=i.map(u=>{if(r&&r.length>0){let b=I.relative(r,u);if(b&&typeof b=="string"&&!b.startsWith(".."))return b.replace(/\\/g,"/")}return I.basename(u)}),a=mt(p,{flatten:t.pathDetect!==!1}).map(u=>u.path),d=new Set(pt(a));if(d.size===0)return[];let y=[],A=[];for(let u=0;u<i.length;u++)d.has(a[u])&&(y.push(i[u]),A.push(a[u]));let F=[],v=0;if(!o)throw l.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let u=0;u<y.length;u++){let b=y[u],k=A[u];try{yt(k,b);let L=x.statSync(b);if(L.size===0)continue;if(gt(k,b),L.size>o.maxFileSize)throw l.business(`File ${b} is too large. Maximum allowed size is ${o.maxFileSize/(1024*1024)}MB.`);if(v+=L.size,v>o.maxTotalSize)throw l.business(`Total deploy size is too large. Maximum allowed is ${o.maxTotalSize/(1024*1024)}MB.`);let X=x.readFileSync(b),{md5:Ft}=await le(X);F.push({path:k,content:X,size:X.length,md5:Ft})}catch(L){if(O(L))throw L;let X=L instanceof Error?L.message:String(L);throw l.file(`Failed to read file "${b}": ${X}`,{filePath:b})}}if(F.length>o.maxFilesCount)throw l.business(`Too many files to deploy. Maximum allowed is ${o.maxFilesCount} files.`);return F}var x,I,Et=$(()=>{"use strict";ce();Oe();ct();St();E();ut();Ie();x=R(require("fs"),1),I=R(require("path"),1)});var xt=require("commander");E();var K=require("fs"),ye=R(require("path"),1);var Ce=R(require("columnify"),1),h=require("yoctocolors"),je=["isCreate","claim"],w=(e,t,o)=>o?t:e(t),T=(e,t,o)=>{console.log(t?JSON.stringify({success:e},null,2)+`
3
- `:`${w(h.green,e.toLowerCase().replace(/\.$/,""),o)}
2
+ "use strict";var Nt=Object.create;var De=Object.defineProperty;var _t=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var Mt=Object.getPrototypeOf,jt=Object.prototype.hasOwnProperty;var $=(e,t)=>()=>(e&&(t=e(e=0)),t);var Gt=(e,t)=>{for(var o in t)De(e,o,{get:t[o],enumerable:!0})},Ht=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ut(t))!jt.call(e,i)&&i!==o&&De(e,i,{get:()=>t[i],enumerable:!(n=_t(t,i))||n.enumerable});return e};var R=(e,t,o)=>(o=e!=null?Nt(Mt(e)):{},Ht(t||!e||!e.__esModule?De(o,"default",{value:e,enumerable:!0}):o,e));function O(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function Ee(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return!1;let o=e.slice(t+1).toLowerCase();return Bt.has(o)}function Ne(e){return qt.test(e)}function we(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(o=>Te.has(o))}function ne(e){if(!e.startsWith(N.PREFIX))throw l.validation(`API key must start with "${N.PREFIX}"`);if(e.length!==N.TOTAL_LENGTH)throw l.validation(`API key must be ${N.TOTAL_LENGTH} characters total (${N.PREFIX} + ${N.HEX_LENGTH} hex chars)`);let t=e.slice(N.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw l.validation(`API key must contain ${N.HEX_LENGTH} hexadecimal characters after "${N.PREFIX}" prefix`)}function Ue(e){if(!e.startsWith(_.PREFIX))throw l.validation(`Deploy token must start with "${_.PREFIX}"`);if(e.length!==_.TOTAL_LENGTH)throw l.validation(`Deploy token must be ${_.TOTAL_LENGTH} characters total (${_.PREFIX} + ${_.HEX_LENGTH} hex chars)`);let t=e.slice(_.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw l.validation(`Deploy token must contain ${_.HEX_LENGTH} hexadecimal characters after "${_.PREFIX}" prefix`)}function Me(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw l.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw l.validation("API URL must not contain a path");if(t.search||t.hash)throw l.validation("API URL must not contain query parameters or fragments")}catch(t){throw O(t)?t:l.validation("API URL must be a valid URL")}}function Ce(e){if(e==null)return;if(typeof e!="string")throw l.validation("Password must be a string");let t=e.trim();if(t.length<oe.MIN_LENGTH||t.length>oe.MAX_LENGTH)throw l.validation(`Password must be between ${oe.MIN_LENGTH} and ${oe.MAX_LENGTH} characters`);return t}var m,zt,be,Kt,l,Bt,qt,Te,N,_,ve,_e,K,j,je,oe,E=$(()=>{"use strict";m={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},zt=new Set([m.Network,m.Cancelled,m.File,m.Config]),be={client:new Set([m.Business,m.Config,m.File,m.Forbidden,m.Validation]),network:new Set([m.Network]),auth:new Set([m.Authentication])},Kt=new Set(Object.values(m).filter(e=>!zt.has(e))),l=class e extends Error{type;status;details;constructor(t,o,n,i){super(o),this.type=t,this.status=n,this.details=i,this.name="ShipError"}toResponse(){let t=this.details,o=this.type===m.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:o}}static async fromHttpResponse(t,o){let n,i,s;try{if(t.headers.get("content-type")?.includes("application/json")){let c=await t.json();if(c&&typeof c=="object"){let a=c;typeof a.message=="string"?n=a.message:typeof a.error=="string"&&(n=a.error),i=a.details,typeof a.error=="string"&&Kt.has(a.error)&&(s=a.error)}}else{let c=await t.text();c&&(n=c)}}catch{}n=n||`${o||"Request"} failed with status ${t.status}`;let r=s??(t.status===401?m.Authentication:t.status===403?m.Forbidden:t.status===429?m.RateLimit:m.Api);return new e(r,n,t.status,i)}static fromFetchError(t,o){if(O(t))return t;let n=o||"Request";return t instanceof Error?t.name==="AbortError"?e.cancelled(`${n} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?e.network(`${n} failed: ${t.message}`,{cause:t}):new e(m.Api,`${n} failed: ${t.message}`):new e(m.Api,`${n} failed: Unknown error`)}static validation(t,o){return new e(m.Validation,t,400,o)}static notFound(t,o){let n=o?`${t} ${o} not found`:`${t} not found`;return new e(m.NotFound,n,404)}static forbidden(t,o){return new e(m.Forbidden,t,403,o)}static rateLimit(t="Too many requests",o){return new e(m.RateLimit,t,429,o)}static authentication(t="Authentication required",o){return new e(m.Authentication,t,401,o)}static business(t,o=400,n){return new e(m.Business,t,o,n)}static network(t,o){return new e(m.Network,t,void 0,o)}static cancelled(t,o){return new e(m.Cancelled,t,void 0,o)}static file(t,o){return new e(m.File,t,void 0,o)}static config(t,o){return new e(m.Config,t,void 0,o)}static api(t,o=500,n){return new e(m.Api,t,o,n)}isClientError(){return be.client.has(this.type)}isNetworkError(){return be.network.has(this.type)}isAuthError(){return be.auth.has(this.type)}isType(t){return this.type===t}};Bt=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"]);qt=/[\x00-\x1f\x7f#?%\\<>"]/;Te=new Set(["node_modules","package.json"]);N={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},_={PREFIX:"token-",HEX_LENGTH:64,TOTAL_LENGTH:70},ve="ship.json",_e={rewrites:[{source:"/(.*)",destination:"/index.html"}]};K="https://api.shipstatic.com",j={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},je=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,oe={MIN_LENGTH:6,MAX_LENGTH:128}});async function lo(e){let t=(await import("spark-md5")).default,o=new t.ArrayBuffer,n=2097152;for(let i=0;i<e.size;i+=n){let s=Math.min(i+n,e.size);o.append(await e.slice(i,s).arrayBuffer())}return{md5:o.end()}}async function po(e){let{createHash:t}=await import("crypto"),o=t("md5");return o.update(e),{md5:o.digest("hex")}}async function co(e){let{createHash:t}=await import("crypto"),{createReadStream:o}=await import("fs");return new Promise((n,i)=>{let s=t("md5"),r=o(e);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",()=>n({md5:s.digest("hex")}))})}async function pe(e){if(e instanceof Blob)return lo(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return po(e);if(typeof e=="string")return co(e);throw l.business("Invalid input for MD5 calculation")}var xe=$(()=>{"use strict";E()});function uo(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function V(){return at||uo()}var at,de=$(()=>{"use strict";at=null});function ct(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(n=>n&&we(n)))throw l.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(o=>{if(!o)return!1;let n=o.replace(/\\/g,"/").split("/").filter(Boolean);if(n.length===0)return!0;let i=n[n.length-1];if((0,pt.isJunk)(i))return!1;for(let r of n)if(r!==".well-known"&&(r.startsWith(".")||r.length>255))return!1;let s=n.slice(0,-1);for(let r of s)if(yo.some(p=>r.toLowerCase()===p.toLowerCase()))return!1;return!0})}var pt,yo,dt=$(()=>{"use strict";pt=require("junk");E();yo=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function mt(e){if(!e||e.length===0)return"";let t=e.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let o=t.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(p=>p[s]===r))n.push(r);else break}return n.join("/")}function he(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ke=$(()=>{"use strict"});function ut(e,t={}){if(t.flatten===!1)return e.map(n=>({path:he(n),name:Le(n)}));let o=go(e);return e.map(n=>{let i=he(n);if(o){let s=o.endsWith("/")?o:`${o}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=Le(n)),{path:i,name:Le(n)}})}function go(e){if(!e.length)return"";let o=e.map(s=>he(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(p=>p[s]===r))n.push(r);else break}return n.join("/")}function Le(e){return e.split(/[/\\]/).pop()||e}var ft=$(()=>{"use strict";ke()});function ht(e){if(Ne(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,o=e.split("/").pop()||e;return t.test(o)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}var yt=$(()=>{"use strict";E()});function gt(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw l.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function St(e,t){let o=ht(e);if(!o.valid)throw l.business(o.reason||"Invalid file name");if(Ee(e))throw l.business(`File extension not allowed: "${t}"`)}var Dt=$(()=>{"use strict";E();yt()});var Et={};Gt(Et,{processFilesForNode:()=>So});function bt(e,t=new Set){let o=[],n=x.realpathSync(e);if(t.has(n))return o;t.add(n);let i=x.readdirSync(e);for(let s of i){let r=I.join(e,s),p=x.statSync(r);if(p.isDirectory()){let c=bt(r,t);o.push(...c)}else p.isFile()&&o.push(r)}return o}async function So(e,t={},o){if(V()!=="node")throw l.business("processFilesForNode can only be called in Node.js environment.");for(let u of e){let b=I.resolve(u);try{if(x.statSync(b).isDirectory()){let k=x.readdirSync(b).find(L=>Te.has(L));if(k)throw l.business(`"${k}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(k){if(O(k))throw k}}let n=e.flatMap(u=>{let b=I.resolve(u);try{return x.statSync(b).isDirectory()?bt(b):[b]}catch{throw l.file(`Path does not exist: ${u}`,{filePath:u})}}),i=[...new Set(n)],s=e.map(u=>I.resolve(u)),r=mt(s.map(u=>{try{return x.statSync(u).isDirectory()?u:I.dirname(u)}catch{return I.dirname(u)}})),p=i.map(u=>{if(r&&r.length>0){let b=I.relative(r,u);if(b&&typeof b=="string"&&!b.startsWith(".."))return b.replace(/\\/g,"/")}return I.basename(u)}),a=ut(p,{flatten:t.pathDetect!==!1}).map(u=>u.path),d=new Set(ct(a));if(d.size===0)return[];let y=[],A=[];for(let u=0;u<i.length;u++)d.has(a[u])&&(y.push(i[u]),A.push(a[u]));let F=[],v=0;if(!o)throw l.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let u=0;u<y.length;u++){let b=y[u],k=A[u];try{gt(k,b);let L=x.statSync(b);if(L.size===0)continue;if(St(k,b),L.size>o.maxFileSize)throw l.business(`File ${b} is too large. Maximum allowed size is ${o.maxFileSize/(1024*1024)}MB.`);if(v+=L.size,v>o.maxTotalSize)throw l.business(`Total deploy size is too large. Maximum allowed is ${o.maxTotalSize/(1024*1024)}MB.`);let X=x.readFileSync(b),{md5:$t}=await pe(X);F.push({path:k,content:X,size:X.length,md5:$t})}catch(L){if(O(L))throw L;let X=L instanceof Error?L.message:String(L);throw l.file(`Failed to read file "${b}": ${X}`,{filePath:b})}}if(F.length>o.maxFilesCount)throw l.business(`Too many files to deploy. Maximum allowed is ${o.maxFilesCount} files.`);return F}var x,I,Tt=$(()=>{"use strict";de();xe();dt();Dt();E();ft();ke();x=R(require("fs"),1),I=R(require("path"),1)});var It=require("commander");E();var z=require("fs"),ge=R(require("path"),1);var Re=R(require("columnify"),1),h=require("yoctocolors"),Ge=["isCreate","claim"],T=(e,t,o)=>o?t:e(t),Vt=e=>/^[A-Z][a-z]/.test(e)?e.charAt(0).toLowerCase()+e.slice(1):e,ie=e=>Vt(e).replace(/\.$/,""),w=(e,t,o)=>{console.log(t?JSON.stringify({success:e},null,2)+`
3
+ `:`${T(h.green,ie(e),o)}
4
4
  `)},C=(e,t,o)=>{if(t)console.error(JSON.stringify({error:e},null,2)+`
5
- `);else{let n=w(s=>(0,h.inverse)((0,h.red)(s)),`${w(h.hidden,"[",o)}error${w(h.hidden,"]",o)}`,o),i=w(h.red,e.toLowerCase().replace(/\.$/,""),o);console.error(`${n} ${i}
6
- `)}},ie=(e,t,o)=>{if(t)console.log(JSON.stringify({warning:e},null,2)+`
7
- `);else{let n=w(s=>(0,h.inverse)((0,h.yellow)(s)),`${w(h.hidden,"[",o)}warning${w(h.hidden,"]",o)}`,o),i=w(h.yellow,e.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${i}
5
+ `);else{let n=T(s=>(0,h.inverse)((0,h.red)(s)),`${T(h.hidden,"[",o)}error${T(h.hidden,"]",o)}`,o),i=T(h.red,ie(e),o);console.error(`${n} ${i}
6
+ `)}},se=(e,t,o)=>{if(t)console.log(JSON.stringify({warning:e},null,2)+`
7
+ `);else{let n=T(s=>(0,h.inverse)((0,h.yellow)(s)),`${T(h.hidden,"[",o)}warning${T(h.hidden,"]",o)}`,o),i=T(h.yellow,ie(e),o);console.log(`${n} ${i}
8
8
  `)}},G=(e,t,o)=>{if(t)console.log(JSON.stringify({info:e},null,2)+`
9
- `);else{let n=w(s=>(0,h.inverse)((0,h.blue)(s)),`${w(h.hidden,"[",o)}info${w(h.hidden,"]",o)}`,o),i=w(h.blue,e.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${i}
10
- `)}},qt=(e,t="details",o)=>{if(e==null||e===0)return"-";let n=new Date(e*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return t==="table"?n.replace(/T/,w(h.hidden,"T",o)).replace(/Z$/,w(h.hidden,"Z",o)):n},Ge=(e,t,o="details",n)=>{if(t===null||Array.isArray(t)&&t.length===0)return"-";if(typeof t=="number"&&(e==="created"||e==="activated"||e==="expires"||e==="linked"||e==="grace"))return qt(t,o,n);if(e==="size"&&typeof t=="number"){let i=t/1048576;return i>=1?`${i.toFixed(1)}Mb`:`${(t/1024).toFixed(1)}Kb`}if(e==="config"||e==="password"){if(typeof t=="boolean")return t?"yes":"no";if(typeof t=="number")return t===1?"yes":"no"}return String(t)},J=(e,t,o,n)=>{if(!e||e.length===0)return"";let i=e[0],s=t||Object.keys(i).filter(c=>i[c]!==void 0&&!je.includes(c)),r=e.map(c=>{let a=c,d={};return s.forEach(y=>{y in a&&a[y]!==void 0&&(d[y]=Ge(y,a[y],"table",o))}),d});return(0,Ce.default)(r,{columnSplitter:" ",columns:s,config:s.reduce((c,a)=>(c[a]={headingTransform:d=>w(h.dim,n?.[d]||d,o)},c),{})}).split(`
9
+ `);else{let n=T(s=>(0,h.inverse)((0,h.blue)(s)),`${T(h.hidden,"[",o)}info${T(h.hidden,"]",o)}`,o),i=T(h.blue,ie(e),o);console.log(`${n} ${i}
10
+ `)}},Xt=(e,t="details",o)=>{if(e==null||e===0)return"-";let n=new Date(e*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return t==="table"?n.replace(/T/,T(h.hidden,"T",o)).replace(/Z$/,T(h.hidden,"Z",o)):n},He=(e,t,o="details",n)=>{if(t===null||Array.isArray(t)&&t.length===0)return"-";if(typeof t=="number"&&(e==="created"||e==="activated"||e==="expires"||e==="linked"||e==="grace"))return Xt(t,o,n);if(e==="size"&&typeof t=="number"){let i=t/1048576;return i>=1?`${i.toFixed(1)}Mb`:`${(t/1024).toFixed(1)}Kb`}if(e==="config"||e==="password"){if(typeof t=="boolean")return t?"yes":"no";if(typeof t=="number")return t===1?"yes":"no"}return String(t)},J=(e,t,o,n)=>{if(!e||e.length===0)return"";let i=e[0],s=t||Object.keys(i).filter(c=>i[c]!==void 0&&!Ge.includes(c)),r=e.map(c=>{let a=c,d={};return s.forEach(y=>{y in a&&a[y]!==void 0&&(d[y]=He(y,a[y],"table",o))}),d});return(0,Re.default)(r,{columnSplitter:" ",columns:s,config:s.reduce((c,a)=>(c[a]={headingTransform:d=>T(h.dim,n?.[d]||d,o)},c),{})}).split(`
11
11
  `).map(c=>c.replace(/\0/g,"").replace(/\s+$/,"")).join(`
12
12
  `)+`
13
- `},B=(e,t)=>{let o=Object.entries(e).filter(([s,r])=>je.includes(s)?!1:r!==void 0);if(o.length===0)return"";let n=o.map(([s,r])=>({property:s+":",value:Ge(s,r,"details",t)}));return(0,Ce.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>w(h.dim,s,t)}}}).split(`
13
+ `},B=(e,t)=>{let o=Object.entries(e).filter(([s,r])=>Ge.includes(s)?!1:r!==void 0);if(o.length===0)return"";let n=o.map(([s,r])=>({property:s+":",value:He(s,r,"details",t)}));return(0,Re.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>T(h.dim,s,t)}}}).split(`
14
14
  `).map(s=>s.replace(/\0/g,"")).join(`
15
15
  `)+`
16
- `};var Re=(e,t)=>`https://setup.shipstatic.com/${e}/${t}`;function Vt(e,t,o){let{noColor:n}=o;if(e.deployments.length===0){console.log("no deployments found"),console.log();return}let i=["deployment","labels","files","size","created","via"];console.log(J(e.deployments,i,n))}function Xt(e,t,o){let{noColor:n}=o;if(e.domains.length===0){console.log("no domains found"),console.log();return}let i=["domain","deployment","labels","linked","links","created"];console.log(J(e.domains,i,n))}function Jt(e,t,o){let{noColor:n}=o,{_dnsRecords:i,_shareHash:s,isCreate:r,...p}=e;if(t.operation==="set"){let c=r?"created":"updated";T(`${e.url} domain ${c}`,!1,n)}i&&i.length>0&&(console.log(),G("DNS Records to configure:",!1,n),i.forEach(c=>{console.log(` ${c.type}: ${c.name} \u2192 ${c.value}`)})),s&&(console.log(),G(`Setup instructions: ${Re(s,e.domain)}`,!1,n)),console.log(B(p,n))}function Wt(e,t,o){let{noColor:n}=o;t.operation==="upload"&&T(`${e.url} deployment uploaded`,!1,n),console.log(B(e,n));let i=e.claim;if(i){let s=e.expires?Math.round((e.expires-e.created)/86400):null;console.log(`IMPORTANT: this deployment${s?` expires in ${s} day${s!==1?"s":""}`:" will expire"}, claim it to keep permanently:
16
+ `};var Ae=(e,t)=>`https://setup.shipstatic.com/${e}/${t}`;function Jt(e,t,o){let{noColor:n}=o;if(e.deployments.length===0){console.log("no deployments found"),console.log();return}let i=["deployment","labels","files","size","created","via"];console.log(J(e.deployments,i,n))}function Wt(e,t,o){let{noColor:n}=o;if(e.domains.length===0){console.log("no domains found"),console.log();return}let i=["domain","deployment","labels","linked","links","created"];console.log(J(e.domains,i,n))}function Yt(e,t,o){let{noColor:n}=o,{_dnsRecords:i,_shareHash:s,isCreate:r,...p}=e;if(t.operation==="set"){let c=r?"created":"updated";w(`${e.url} domain ${c}`,!1,n)}i&&i.length>0&&(console.log(),G("DNS Records to configure:",!1,n),i.forEach(c=>{console.log(` ${c.type}: ${c.name} \u2192 ${c.value}`)})),s&&(console.log(),G(`Setup instructions: ${Ae(s,e.domain)}`,!1,n)),console.log(B(p,n))}function Zt(e,t,o){let{noColor:n}=o;t.operation==="upload"&&w(`${e.url} deployment uploaded`,!1,n),console.log(B(e,n));let i=e.claim;if(i){let s=e.expires?Math.round((e.expires-e.created)/86400):null;console.log(`IMPORTANT: this deployment${s?` expires in ${s} day${s!==1?"s":""}`:" will expire"}, claim it to keep permanently:
17
17
  ${i}
18
- `),G("configure a free API key with 'ship config' to deploy to your own account",!1,n)}}function Yt(e,t,o){let{noColor:n}=o;console.log(B(e,n))}function Zt(e,t,o){let{noColor:n}=o;e.message&&T(e.message,!1,n)}function Qt(e,t,o){let{noColor:n}=o;if(e.valid){if(T("domain is valid",!1,n),console.log(),e.normalized&&console.log(` normalized: ${e.normalized}`),e.available!==null){let i=e.available?n?"available":"available \u2713":"already taken";console.log(` availability: ${i}`)}console.log()}else C(e.error||"domain is invalid",!1,n)}function eo(e,t,o){let{noColor:n}=o;if(e.records.length===0){console.log("no records found"),console.log();return}let i=["type","name","value"];console.log(J(e.records,i,n))}function to(e,t,o){let{noColor:n}=o,i=e.dns?.provider?.name||null;console.log(B({domain:e.domain,provider:i},n))}function oo(e,t,o){let{noColor:n}=o;T(Re(e.hash,e.domain),!1,n)}function no(e,t,o){let{noColor:n}=o;if(e.tokens.length===0){console.log("no tokens found"),console.log();return}let i=["token","labels","created","expires"];console.log(J(e.tokens,i,n))}function io(e,t,o){let{noColor:n}=o;t.operation==="create"&&e.token&&T(`token ${e.token} created`,!1,n),console.log(B(e,n))}function He(e,t,o){let{json:n,quiet:i,noColor:s}=o;if(i){if(e===void 0||typeof e=="boolean")return;if(e!==null&&typeof e=="object")if("deployments"in e)e.deployments.forEach(r=>console.log(r.deployment));else if("domains"in e)e.domains.forEach(r=>console.log(r.domain));else if("tokens"in e)e.tokens.forEach(r=>console.log(r.token));else if("records"in e)e.records.forEach(r=>console.log(`${r.type} ${r.name} ${r.value}`));else if("hash"in e){let r=e;console.log(Re(r.hash,r.domain))}else if("dns"in e){let r=e.dns?.provider?.name;r&&console.log(r)}else if("domain"in e)console.log(e.domain);else if("deployment"in e)console.log(e.deployment);else if("secret"in e)console.log(e.secret);else if("email"in e)console.log(e.email);else if("valid"in e){let r=e;r.valid&&r.normalized&&console.log(r.normalized)}else"message"in e&&console.log(e.message);return}if(e===void 0){t.operation==="remove"&&t.resourceType&&t.resourceId?T(`${t.resourceId} ${t.resourceType.toLowerCase()} removed`,n,s):T("removed successfully",n,s);return}if(typeof e=="boolean"){e?T("api reachable",n,s):C("api unreachable",n,s);return}if(n&&e!==null&&typeof e=="object"){let r={...e};delete r._dnsRecords,delete r._shareHash,delete r.isCreate,console.log(JSON.stringify(r,null,2)),console.log();return}e!==null&&typeof e=="object"?"deployments"in e?Vt(e,t,o):"domains"in e?Xt(e,t,o):"tokens"in e?no(e,t,o):"records"in e?eo(e,t,o):"hash"in e?oo(e,t,o):"dns"in e?to(e,t,o):"domain"in e?Jt(e,t,o):"deployment"in e?Wt(e,t,o):"token"in e?io(e,t,o):"email"in e?Yt(e,t,o):"valid"in e?Qt(e,t,o):"message"in e?Zt(e,t,o):T("success",n,s):T("success",n,s)}var g=R(require("fs"),1),U=R(require("path"),1),Ae=R(require("os"),1);function Ke(){let e=process.env.SHELL||"";return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":null}function ze(e,t){switch(e){case"bash":return{completionFile:U.join(t,".ship_completion.bash"),profileFile:U.join(t,".bash_profile"),scriptName:"ship.bash"};case"zsh":return{completionFile:U.join(t,".ship_completion.zsh"),profileFile:U.join(t,".zshrc"),scriptName:"ship.zsh"};case"fish":return{completionFile:U.join(t,".config/fish/completions/ship.fish"),profileFile:null,scriptName:"ship.fish"}}}function Be(e,t={}){let{json:o,noColor:n}=t,i=Ke(),s=Ae.homedir();if(!i){C(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,o,n);return}let r=ze(i,s),p=U.join(e,r.scriptName);try{if(i==="fish"){let a=U.dirname(r.completionFile);g.existsSync(a)||g.mkdirSync(a,{recursive:!0}),g.copyFileSync(p,r.completionFile),T("fish completion installed successfully",o,n),G("please restart your shell to apply the changes",o,n);return}g.copyFileSync(p,r.completionFile);let c=`# ship
18
+ `),G("configure a free API key with 'ship config' to deploy to your own account",!1,n)}}function Qt(e,t,o){let{noColor:n}=o;console.log(B(e,n))}function eo(e,t,o){let{noColor:n}=o;e.message&&w(e.message,!1,n)}function to(e,t,o){let{noColor:n}=o;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?n?"available":"available \u2713":"already taken";console.log(` availability: ${i}`)}console.log()}else C(e.error||"domain is invalid",!1,n)}function oo(e,t,o){let{noColor:n}=o;if(e.records.length===0){console.log("no records found"),console.log();return}let i=["type","name","value"];console.log(J(e.records,i,n))}function no(e,t,o){let{noColor:n}=o,i=e.dns?.provider?.name||null;console.log(B({domain:e.domain,provider:i},n))}function io(e,t,o){let{noColor:n}=o;w(Ae(e.hash,e.domain),!1,n)}function so(e,t,o){let{noColor:n}=o;if(e.tokens.length===0){console.log("no tokens found"),console.log();return}let i=["token","labels","created","expires"];console.log(J(e.tokens,i,n))}function ro(e,t,o){let{noColor:n}=o;t.operation==="create"&&e.token&&w(`token ${e.token} created`,!1,n),console.log(B(e,n))}function ze(e,t,o){let{json:n,quiet:i,noColor:s}=o;if(i){if(e===void 0||typeof e=="boolean")return;if(e!==null&&typeof e=="object")if("deployments"in e)e.deployments.forEach(r=>console.log(r.deployment));else if("domains"in e)e.domains.forEach(r=>console.log(r.domain));else if("tokens"in e)e.tokens.forEach(r=>console.log(r.token));else if("records"in e)e.records.forEach(r=>console.log(`${r.type} ${r.name} ${r.value}`));else if("hash"in e){let r=e;console.log(Ae(r.hash,r.domain))}else if("dns"in e){let r=e.dns?.provider?.name;r&&console.log(r)}else if("domain"in e)console.log(e.domain);else if("deployment"in e)console.log(e.deployment);else if("secret"in e)console.log(e.secret);else if("email"in e)console.log(e.email);else if("valid"in e){let r=e;r.valid&&r.normalized&&console.log(r.normalized)}else"message"in e&&console.log(e.message);return}if(e===void 0){t.operation==="remove"&&t.resourceType&&t.resourceId?w(`${t.resourceId} ${t.resourceType.toLowerCase()} removed`,n,s):w("removed successfully",n,s);return}if(typeof e=="boolean"){e?w("api reachable",n,s):C("api unreachable",n,s);return}if(n&&e!==null&&typeof e=="object"){let r={...e};delete r._dnsRecords,delete r._shareHash,delete r.isCreate,console.log(JSON.stringify(r,null,2)),console.log();return}e!==null&&typeof e=="object"?"deployments"in e?Jt(e,t,o):"domains"in e?Wt(e,t,o):"tokens"in e?so(e,t,o):"records"in e?oo(e,t,o):"hash"in e?io(e,t,o):"dns"in e?no(e,t,o):"domain"in e?Yt(e,t,o):"deployment"in e?Zt(e,t,o):"token"in e?ro(e,t,o):"email"in e?Qt(e,t,o):"valid"in e?to(e,t,o):"message"in e?eo(e,t,o):w("success",n,s):w("success",n,s)}var g=R(require("fs"),1),U=R(require("path"),1),Oe=R(require("os"),1);function Ke(){let e=process.env.SHELL||"";return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":null}function Be(e,t){switch(e){case"bash":return{completionFile:U.join(t,".ship_completion.bash"),profileFile:U.join(t,".bash_profile"),scriptName:"ship.bash"};case"zsh":return{completionFile:U.join(t,".ship_completion.zsh"),profileFile:U.join(t,".zshrc"),scriptName:"ship.zsh"};case"fish":return{completionFile:U.join(t,".config/fish/completions/ship.fish"),profileFile:null,scriptName:"ship.fish"}}}function qe(e,t={}){let{json:o,noColor:n}=t,i=Ke(),s=Oe.homedir();if(!i){C(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,o,n);return}let r=Be(i,s),p=U.join(e,r.scriptName);try{if(i==="fish"){let a=U.dirname(r.completionFile);g.existsSync(a)||g.mkdirSync(a,{recursive:!0}),g.copyFileSync(p,r.completionFile),w("fish completion installed successfully",o,n),G("please restart your shell to apply the changes",o,n);return}g.copyFileSync(p,r.completionFile);let c=`# ship
19
19
  source '${r.completionFile}'
20
20
  # ship end`;if(r.profileFile){if(g.existsSync(r.profileFile)){let a=g.readFileSync(r.profileFile,"utf-8");if(!a.includes("# ship")||!a.includes("# ship end")){let d=a.length>0&&!a.endsWith(`
21
21
  `)?`
22
- `:"";g.appendFileSync(r.profileFile,d+c)}}else g.writeFileSync(r.profileFile,c);T(`completion script installed for ${i}`,o,n),ie(`run "source ${r.profileFile}" or restart your shell`,o,n)}}catch(c){let a=c instanceof Error?c.message:String(c);C(`could not install completion script: ${a}`,o,n)}}function qe(e={}){let{json:t,noColor:o}=e,n=Ke(),i=Ae.homedir();if(!n){C(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,t,o);return}let s=ze(n,i);try{if(n==="fish"){g.existsSync(s.completionFile)?(g.unlinkSync(s.completionFile),T("fish completion uninstalled successfully",t,o)):ie("fish completion was not installed",t,o),G("please restart your shell to apply the changes",t,o);return}if(g.existsSync(s.completionFile)&&g.unlinkSync(s.completionFile),!s.profileFile)return;if(!g.existsSync(s.profileFile)){C("profile file not found",t,o);return}let r=g.readFileSync(s.profileFile,"utf-8"),p=r.split(`
22
+ `:"";g.appendFileSync(r.profileFile,d+c)}}else g.writeFileSync(r.profileFile,c);w(`completion script installed for ${i}`,o,n),se(`run "source ${r.profileFile}" or restart your shell`,o,n)}}catch(c){let a=c instanceof Error?c.message:String(c);C(`could not install completion script: ${a}`,o,n)}}function Ve(e={}){let{json:t,noColor:o}=e,n=Ke(),i=Oe.homedir();if(!n){C(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,t,o);return}let s=Be(n,i);try{if(n==="fish"){g.existsSync(s.completionFile)?(g.unlinkSync(s.completionFile),w("fish completion uninstalled successfully",t,o)):se("fish completion was not installed",t,o),G("please restart your shell to apply the changes",t,o);return}if(g.existsSync(s.completionFile)&&g.unlinkSync(s.completionFile),!s.profileFile)return;if(!g.existsSync(s.profileFile)){C("profile file not found",t,o);return}let r=g.readFileSync(s.profileFile,"utf-8"),p=r.split(`
23
23
  `),c=[],a=0,d=!1;for(;a<p.length;)if(p[a].trim()==="# ship"){for(d=!0,a++;a<p.length&&p[a].trim()!=="# ship end";)a++;a<p.length&&a++}else c.push(p[a]),a++;if(d){let y=r.endsWith(`
24
24
  `),A=c.length===0?"":c.join(`
25
25
  `)+(y?`
26
- `:"");g.writeFileSync(s.profileFile,A),T(`completion script uninstalled for ${n}`,t,o),ie(`run "source ${s.profileFile}" or restart your shell`,t,o)}else C("completion was not found in profile",t,o)}catch(r){let p=r instanceof Error?r.message:String(r);C(`could not uninstall completion script: ${p}`,t,o)}}var Je=require("readline/promises"),H=require("fs"),We=require("os"),Ye=require("path");E();var se=require("yoctocolors"),q=(0,Ye.join)((0,We.homedir)(),".shiprc");function Ve(e){return e.length<13?e:e.slice(0,9)+"..."+e.slice(-4)}function Xe(){try{return(0,H.existsSync)(q)?JSON.parse((0,H.readFileSync)(q,"utf-8")):{}}catch{return{}}}async function Ze(e={}){let{noColor:t,json:o}=e,n=d=>t?d:(0,se.dim)(d),i=d=>t?d:(0,se.green)(d);if(o){let d=Xe(),y=typeof d.apiKey=="string"?d.apiKey:void 0,A=typeof d.apiUrl=="string"?d.apiUrl:void 0;console.log(JSON.stringify({path:q,exists:(0,H.existsSync)(q),...y?{apiKey:Ve(y)}:{},...A&&A!==z?{apiUrl:A}:{}},null,2)+`
27
- `);return}let s=Xe(),r=typeof s.apiKey=="string"?s.apiKey:void 0,p=(0,Je.createInterface)({input:process.stdin,output:process.stdout});console.log(""),console.log(` ${n("Create a free API key at")} https://my.shipstatic.com/api-key`),console.log("");let c=r?` API Key (${n(Ve(r))}): `:" API Key: ",a;try{a=(await p.question(c)).trim()}finally{p.close()}a&&(ne(a),s.apiKey=a),(0,H.writeFileSync)(q,JSON.stringify(s,null,2)+`
26
+ `:"");g.writeFileSync(s.profileFile,A),w(`completion script uninstalled for ${n}`,t,o),se(`run "source ${s.profileFile}" or restart your shell`,t,o)}else C("completion was not found in profile",t,o)}catch(r){let p=r instanceof Error?r.message:String(r);C(`could not uninstall completion script: ${p}`,t,o)}}var We=require("readline/promises"),H=require("fs"),Ye=require("os"),Ze=require("path");E();var re=require("yoctocolors"),q=(0,Ze.join)((0,Ye.homedir)(),".shiprc");function Xe(e){return e.length<13?e:e.slice(0,9)+"..."+e.slice(-4)}function Je(){try{return(0,H.existsSync)(q)?JSON.parse((0,H.readFileSync)(q,"utf-8")):{}}catch{return{}}}async function Qe(e={}){let{noColor:t,json:o}=e,n=d=>t?d:(0,re.dim)(d),i=d=>t?d:(0,re.green)(d);if(o){let d=Je(),y=typeof d.apiKey=="string"?d.apiKey:void 0,A=typeof d.apiUrl=="string"?d.apiUrl:void 0;console.log(JSON.stringify({path:q,exists:(0,H.existsSync)(q),...y?{apiKey:Xe(y)}:{},...A&&A!==K?{apiUrl:A}:{}},null,2)+`
27
+ `);return}let s=Je(),r=typeof s.apiKey=="string"?s.apiKey:void 0,p=(0,We.createInterface)({input:process.stdin,output:process.stdout});console.log(""),console.log(` ${n("Create a free API key at")} https://my.shipstatic.com/api-key`),console.log("");let c=r?` API Key (${n(Xe(r))}): `:" API Key: ",a;try{a=(await p.question(c)).trim()}finally{p.close()}a&&(ne(a),s.apiKey=a),(0,H.writeFileSync)(q,JSON.stringify(s,null,2)+`
28
28
  `),console.log(`
29
29
  ${i("saved to")} ${n(q)}
30
- `)}E();E();var re=class{constructor(){this.handlers=new Map}on(t,o){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(o)}off(t,o){let n=this.handlers.get(t);n&&(n.delete(o),n.size===0&&this.handlers.delete(t))}emit(t,...o){let n=this.handlers.get(t);if(!n)return;let i=Array.from(n);for(let s of i)try{s(...o)}catch(r){n.delete(s),t!=="error"&&setTimeout(()=>{let p=r instanceof Error?r:new Error(String(r));this.emit("error",p,String(t))},0)}}};E();E();function W(e){if(e==null)return;if(e.length===0)return e;if(e.length>j.MAX_COUNT)throw l.validation(`Maximum ${j.MAX_COUNT} labels allowed`);let t=e.map((n,i)=>{if(typeof n!="string")throw l.validation(`Label at index ${i} must be a string`);let s=n.trim().toLowerCase();if(s.length<j.MIN_LENGTH)throw l.validation(`Labels must be at least ${j.MIN_LENGTH} characters long`);if(s.length>j.MAX_LENGTH)throw l.validation(`Labels must be no more than ${j.MAX_LENGTH} characters long`);if(!Me.test(s))throw l.validation(`Labels must start and end with alphanumeric characters, with optional separators (${j.SEPARATORS}) between segments`);return s}),o=[...new Set(t)];if(o.length!==t.length)throw l.validation("Duplicate labels are not allowed");return o}var S={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},so=3e4,ae=class extends re{constructor(o){super();this.globalHeaders={};this.apiUrl=o.apiUrl||z,this.getAuthHeadersCallback=o.getAuthHeaders,this.useCredentials=o.useCredentials??!1,this.timeout=o.timeout??so,this.fetch=o.fetch??globalThis.fetch.bind(globalThis),this.createDeployBody=o.createDeployBody,this.deployEndpoint=o.deployEndpoint||S.DEPLOYMENTS}setGlobalHeaders(o){this.globalHeaders=o}async executeRequest(o,n,i){let s=this.mergeHeaders(n.headers),{signal:r,cleanup:p}=this.createTimeoutSignal(n.signal),c={...n,headers:s,credentials:this.useCredentials&&!s.Authorization?"include":void 0,signal:r};this.emit("request",o,c);try{let a=await this.fetch(o,c);if(p(),!a.ok)throw await l.fromHttpResponse(a,i);return this.emit("response",this.safeClone(a),o),{data:await this.parseResponse(this.safeClone(a)),status:a.status}}catch(a){p();let d=l.fromFetchError(a,i);throw this.emit("error",d,o),d}}async request(o,n,i){let{data:s}=await this.executeRequest(o,n,i);return s}async requestWithStatus(o,n,i){return this.executeRequest(o,n,i)}mergeHeaders(o={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...o}}createTimeoutSignal(o){let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeout);if(o){let s=()=>n.abort();o.addEventListener("abort",s),o.aborted&&n.abort()}return{signal:n.signal,cleanup:()=>clearTimeout(i)}}safeClone(o){try{return o.clone()}catch{return o}}async parseResponse(o){if(!(o.headers.get("Content-Length")==="0"||o.status===204))return o.json()}async deploy(o,n={}){if(!o.length)throw l.business("No files to deploy");for(let a of o)if(!a.md5)throw l.file(`MD5 checksum missing for file: ${a.path}`,{filePath:a.path});ve(n.password);let i=W(n.labels),s=n.build||n.prerender||n.spa?{build:n.build,prerender:n.prerender,spa:n.spa}:void 0,{body:r,headers:p}=await this.createDeployBody(o,{labels:i,via:n.via,password:n.password,flags:s}),c={};return n.deployToken?c.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(c.Authorization=`Bearer ${n.apiKey}`),n.caller&&(c["X-Caller"]=n.caller),this.request(`${n.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:r,headers:{...p,...c},signal:n.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(o){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(o)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(o,n){let i=W(n);return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(o)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:i})},"Update deployment labels")}async removeDeployment(o){await this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(o)}`,{method:"DELETE"},"Remove deployment")}async setDomain(o,n,i){let s=W(i),r={};n&&(r.deployment=n),s!==void 0&&(r.labels=s);let{data:p,status:c}=await this.requestWithStatus(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(o)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"Set domain");return{...p,isCreate:c===201}}async listDomains(){return this.request(`${this.apiUrl}${S.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(o){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(o)}`,{method:"GET"},"Get domain")}async removeDomain(o){await this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(o)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(o){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(o)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(o){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(o)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(o){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(o)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(o){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(o)}/share`,{method:"GET"},"Get domain share")}async validateDomain(o){return this.request(`${this.apiUrl}${S.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:o})},"Validate domain")}async createToken(o,n){let i=W(n),s={};return o!==void 0&&(s.ttl=o),i!==void 0&&(s.labels=i),this.request(`${this.apiUrl}${S.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${S.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(o){await this.request(`${this.apiUrl}${S.TOKENS}/${encodeURIComponent(o)}`,{method:"DELETE"},"Remove token")}async fetchAgentToken(){return this.request(`${this.apiUrl}${S.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent token")}async getAccount(){return this.request(`${this.apiUrl}${S.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${S.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return(await this.request(`${this.apiUrl}${S.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(o,n={}){let i=o.find(a=>a.path==="index.html"||a.path==="/index.html");if(!i||i.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(i.content))s=i.content.toString("utf-8");else if(typeof Blob<"u"&&i.content instanceof Blob)s=await i.content.text();else if(typeof File<"u"&&i.content instanceof File)s=await i.content.text();else return!1;let r={"Content-Type":"application/json"};n.deployToken?r.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(r.Authorization=`Bearer ${n.apiKey}`);let p={files:o.map(a=>a.path),index:s};return(await this.request(`${this.apiUrl}${S.SPA_CHECK}`,{method:"POST",headers:r,body:JSON.stringify(p)},"SPA check")).isSPA}};E();function Qe(e={}){let t={apiUrl:e.apiUrl||z};return e.apiKey!==void 0&&(t.apiKey=e.apiKey),e.deployToken!==void 0&&(t.deployToken=e.deployToken),t}function et(e,t){let o={...e};return o.apiUrl===void 0&&t.apiUrl!==void 0&&(o.apiUrl=t.apiUrl),o.apiKey===void 0&&t.apiKey!==void 0&&(o.apiKey=t.apiKey),o.deployToken===void 0&&t.deployToken!==void 0&&(o.deployToken=t.deployToken),o.timeout===void 0&&t.timeout!==void 0&&(o.timeout=t.timeout),o.maxConcurrency===void 0&&t.maxConcurrency!==void 0&&(o.maxConcurrency=t.maxConcurrency),o.onProgress===void 0&&t.onProgress!==void 0&&(o.onProgress=t.onProgress),o.caller===void 0&&t.caller!==void 0&&(o.caller=t.caller),o}E();E();Oe();async function po(){let e=JSON.stringify(Ne,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:o}=await le(t);return{path:Te,content:t,size:e.length,md5:o}}async function tt(e,t,o){if(o.spaDetect===!1||o.spa||o.build||o.prerender||e.some(n=>n.path===Te))return e;try{if(await t.checkSPA(e,o)){let i=await po();return[...e,i]}}catch{}return e}function ot(e){let{getApi:t,ensureInit:o,processInput:n,clientDefaults:i,hasAuth:s}=e;return{upload:async(r,p={})=>{await o();let c=i?et(p,i):p;if(s&&!s()&&!c.deployToken&&!c.apiKey)try{let y=t(),{secret:A}=await y.fetchAgentToken();c.deployToken=A}catch(y){throw O(y)&&y.type===m.RateLimit?l.rateLimit("public deploy rate limit exceeded, try again later or run 'ship config' for a free account with higher limits"):y}if(!n)throw l.config("processInput function is not provided.");let a=t(),d=await n(r,c);return d=await tt(d,a,c),a.deploy(d,c)},list:async()=>(await o(),t().listDeployments()),get:async r=>(await o(),t().getDeployment(r)),set:async(r,p)=>(await o(),t().updateDeploymentLabels(r,p.labels)),remove:async r=>{await o(),await t().removeDeployment(r)}}}function nt(e){let{getApi:t,ensureInit:o}=e;return{set:async(n,i={})=>(await o(),t().setDomain(n,i.deployment,i.labels)),list:async()=>(await o(),t().listDomains()),get:async n=>(await o(),t().getDomain(n)),remove:async n=>{await o(),await t().removeDomain(n)},verify:async n=>(await o(),t().verifyDomain(n)),validate:async n=>(await o(),t().validateDomain(n)),dns:async n=>(await o(),t().getDomainDns(n)),records:async n=>(await o(),t().getDomainRecords(n)),share:async n=>(await o(),t().getDomainShare(n))}}function it(e){let{getApi:t,ensureInit:o}=e;return{get:async()=>(await o(),t().getAccount())}}function st(e){let{getApi:t,ensureInit:o}=e;return{create:async(n={})=>(await o(),t().createToken(n.ttl,n.labels)),list:async()=>(await o(),t().listTokens()),remove:async n=>{await o(),await t().removeToken(n)}}}var pe=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.auth=null;t={...t,apiUrl:t.apiUrl||void 0,apiKey:t.apiKey||void 0,deployToken:t.deployToken||void 0},this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.http=new ae({...t,...Qe(t),getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let o={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=ot({...o,processInput:(n,i)=>this.processInput(n,i),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this.domains=nt(o),this.account=it(o),this.tokens=st(o)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(t){throw this.initPromise=null,t}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,o){return this.deployments.upload(t,o)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,o){this.http.on(t,o)}off(t,o){this.http.off(t,o)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setDeployToken(t){if(!t||typeof t!="string")throw l.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:t}}setApiKey(t){if(!t||typeof t!="string")throw l.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:t}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};E();ce();var xe=require("zod");E();ce();var de=require("zod"),me={apiUrl:de.z.string().url().optional(),apiKey:de.z.string().min(1).optional(),deployToken:de.z.string().min(1).optional()};var mo=xe.z.object(me).strict(),uo={apiUrl:"SHIP_API_URL",apiKey:"SHIP_API_KEY",deployToken:"SHIP_DEPLOY_TOKEN"};function ue(){if(V()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL||void 0,apiKey:process.env.SHIP_API_KEY||void 0,deployToken:process.env.SHIP_DEPLOY_TOKEN||void 0};try{return mo.parse(e)}catch(t){if(t instanceof xe.z.ZodError){let o=t.issues[0],n=o.path[0],i=(n&&uo[n])??"SHIP environment configuration";throw l.config(`Invalid ${i}: ${o.message}`)}throw l.config("Invalid environment configuration")}}E();async function at(e,t={}){let{FormData:o,File:n}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),{labels:s,via:r,password:p,flags:c}=t,a=new o,d=[];for(let v of e){if(!Buffer.isBuffer(v.content)&&!(typeof Blob<"u"&&v.content instanceof Blob))throw l.file(`Unsupported file.content type for Node.js: ${v.path}`,{filePath:v.path});if(!v.md5)throw l.file(`File missing md5 checksum: ${v.path}`,{filePath:v.path});let u=new n([v.content],v.path,{type:"application/octet-stream"});a.append("files[]",u),d.push(v.md5)}a.append("checksums",JSON.stringify(d)),s&&s.length>0&&a.append("labels",JSON.stringify(s)),r&&a.append("via",r),p&&a.append("password",p),c?.build&&a.append("build","true"),c?.prerender&&a.append("prerender","true"),c?.spa&&a.append("spa","true");let y=new i(a),A=[];for await(let v of y.encode())A.push(Buffer.from(v));let F=Buffer.concat(A);return{body:F.buffer.slice(F.byteOffset,F.byteOffset+F.byteLength),headers:{"Content-Type":y.contentType,"Content-Length":Buffer.byteLength(F).toString()}}}var he=class extends pe{constructor(t={}){if(V()!=="node")throw l.business("Node.js Ship class can only be used in Node.js environment.");let o=ue();super({...t,apiUrl:t.apiUrl||o.apiUrl,apiKey:t.apiKey||o.apiKey,deployToken:t.deployToken||o.deployToken})}async deploy(t,o){return super.deploy(t,o)}async processInput(t,o){let n=typeof t=="string"?[t]:t;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(()=>(Et(),bt));return i(n,o,this.platformLimits??void 0)}getDeployBodyCreator(){return at}};var Pe=require("zod"),wt=require("os"),Tt=require("cosmiconfig");E();var go=Pe.z.object(me).strict(),Le="ship";function vt(e){let t=e||void 0,o=(0,wt.homedir)(),n=(0,Tt.cosmiconfigSync)(Le,{searchPlaces:[`.${Le}rc`,"package.json",`${o}/.${Le}rc`],stopDir:o}),i;try{i=t?n.load(t):n.search()}catch(s){if(O(s))throw s;let r=s instanceof Error?s.message:String(s),p=t?` (${t})`:"";throw l.config(`Failed to read ship config${p}: ${r}`)}if(!i||!i.config)return{};try{return go.parse(i.config)}catch(s){if(s instanceof Pe.z.ZodError){let r=s.issues[0],p=r.path.length>0?` at ${r.path.join(".")}`:"";throw l.config(`Invalid config in ${i.filepath}${p}: ${r.message}`)}throw l.config(`Invalid config in ${i.filepath}`)}}function So(e,t,o){return{apiUrl:e.apiUrl||t.apiUrl||o.apiUrl,apiKey:e.apiKey||t.apiKey||o.apiKey,deployToken:e.deployToken||t.deployToken||o.deployToken}}function Ct(e={}){return new he(So(e,ue(),vt(e.config)))}E();function Rt(e){return O(e)?e:e instanceof Error?l.business(e.message):l.business(String(e??"Unknown error"))}function At(e,t,o){if(e.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(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.isClientError()||e.status&&e.status>=400&&e.status<500?e.message:"server error: please try again or check https://status.shipstatic.com"}function Ot(e,t){return JSON.stringify({error:e,...t?{details:t}:{}},null,2)}var ge=require("yoctocolors");function Do(){let e=[ye.resolve(__dirname,"../package.json"),ye.resolve(__dirname,"../../package.json")];for(let t of e)try{return JSON.parse((0,K.readFileSync)(t,"utf-8"))}catch{}return{version:"0.0.0"}}var bo=Do(),f=new xt.Command;f.exitOverride(e=>{(e.code==="commander.help"||e.code==="commander.version"||e.exitCode===0)&&process.exit(e.exitCode||0),process.argv.includes("--help")&&(Y(P(f).noColor),process.exit(0));let t=P(f),o=e.message||"unknown command error";o=o.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),C(o,t.json,t.noColor),t.json||Y(t.noColor),process.exit(e.exitCode||1)}).configureOutput({writeErr:e=>{e.startsWith("error:")||process.stderr.write(e)},writeOut:e=>process.stdout.write(e)});function Y(e){let t=s=>e?s:(0,ge.bold)(s),o=s=>e?s:(0,ge.dim)(s),n=s=>e?"":`${s} `,i=`${t("USAGE")}
30
+ `)}E();E();var ae=class{constructor(){this.handlers=new Map}on(t,o){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(o)}off(t,o){let n=this.handlers.get(t);n&&(n.delete(o),n.size===0&&this.handlers.delete(t))}emit(t,...o){let n=this.handlers.get(t);if(!n)return;let i=Array.from(n);for(let s of i)try{s(...o)}catch(r){n.delete(s),t!=="error"&&setTimeout(()=>{let p=r instanceof Error?r:new Error(String(r));this.emit("error",p,String(t))},0)}}};E();E();function W(e){if(e==null)return;if(e.length===0)return e;if(e.length>j.MAX_COUNT)throw l.validation(`Maximum ${j.MAX_COUNT} labels allowed`);let t=e.map((n,i)=>{if(typeof n!="string")throw l.validation(`Label at index ${i} must be a string`);let s=n.trim().toLowerCase();if(s.length<j.MIN_LENGTH)throw l.validation(`Labels must be at least ${j.MIN_LENGTH} characters long`);if(s.length>j.MAX_LENGTH)throw l.validation(`Labels must be no more than ${j.MAX_LENGTH} characters long`);if(!je.test(s))throw l.validation(`Labels must start and end with alphanumeric characters, with optional separators (${j.SEPARATORS}) between segments`);return s}),o=[...new Set(t)];if(o.length!==t.length)throw l.validation("Duplicate labels are not allowed");return o}var S={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},ao=3e4,le=class extends ae{constructor(o){super();this.globalHeaders={};this.apiUrl=o.apiUrl||K,this.getAuthHeadersCallback=o.getAuthHeaders,this.useCredentials=o.useCredentials??!1,this.timeout=o.timeout??ao,this.fetch=o.fetch??globalThis.fetch.bind(globalThis),this.createDeployBody=o.createDeployBody,this.deployEndpoint=o.deployEndpoint||S.DEPLOYMENTS}setGlobalHeaders(o){this.globalHeaders=o}async executeRequest(o,n,i){let s=this.mergeHeaders(n.headers),{signal:r,cleanup:p}=this.createTimeoutSignal(n.signal),c={...n,headers:s,credentials:this.useCredentials&&!s.Authorization?"include":void 0,signal:r};this.emit("request",o,c);try{let a=await this.fetch(o,c);if(p(),!a.ok)throw await l.fromHttpResponse(a,i);return this.emit("response",this.safeClone(a),o),{data:await this.parseResponse(this.safeClone(a)),status:a.status}}catch(a){p();let d=l.fromFetchError(a,i);throw this.emit("error",d,o),d}}async request(o,n,i){let{data:s}=await this.executeRequest(o,n,i);return s}async requestWithStatus(o,n,i){return this.executeRequest(o,n,i)}mergeHeaders(o={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...o}}createTimeoutSignal(o){let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeout);if(o){let s=()=>n.abort();o.addEventListener("abort",s),o.aborted&&n.abort()}return{signal:n.signal,cleanup:()=>clearTimeout(i)}}safeClone(o){try{return o.clone()}catch{return o}}async parseResponse(o){if(!(o.headers.get("Content-Length")==="0"||o.status===204))return o.json()}async deploy(o,n={}){if(!o.length)throw l.business("No files to deploy");for(let a of o)if(!a.md5)throw l.file(`MD5 checksum missing for file: ${a.path}`,{filePath:a.path});Ce(n.password);let i=W(n.labels),s=n.build||n.prerender||n.spa?{build:n.build,prerender:n.prerender,spa:n.spa}:void 0,{body:r,headers:p}=await this.createDeployBody(o,{labels:i,via:n.via,password:n.password,flags:s}),c={};return n.deployToken?c.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(c.Authorization=`Bearer ${n.apiKey}`),n.caller&&(c["X-Caller"]=n.caller),this.request(`${n.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:r,headers:{...p,...c},signal:n.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(o){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(o)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(o,n){let i=W(n);return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(o)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:i})},"Update deployment labels")}async removeDeployment(o){await this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(o)}`,{method:"DELETE"},"Remove deployment")}async setDomain(o,n,i){let s=W(i),r={};n&&(r.deployment=n),s!==void 0&&(r.labels=s);let{data:p,status:c}=await this.requestWithStatus(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(o)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"Set domain");return{...p,isCreate:c===201}}async listDomains(){return this.request(`${this.apiUrl}${S.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(o){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(o)}`,{method:"GET"},"Get domain")}async removeDomain(o){await this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(o)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(o){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(o)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(o){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(o)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(o){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(o)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(o){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(o)}/share`,{method:"GET"},"Get domain share")}async validateDomain(o){return this.request(`${this.apiUrl}${S.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:o})},"Validate domain")}async createToken(o,n){let i=W(n),s={};return o!==void 0&&(s.ttl=o),i!==void 0&&(s.labels=i),this.request(`${this.apiUrl}${S.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${S.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(o){await this.request(`${this.apiUrl}${S.TOKENS}/${encodeURIComponent(o)}`,{method:"DELETE"},"Remove token")}async fetchAgentToken(){return this.request(`${this.apiUrl}${S.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent token")}async getAccount(){return this.request(`${this.apiUrl}${S.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${S.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return(await this.request(`${this.apiUrl}${S.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(o,n={}){let i=o.find(a=>a.path==="index.html"||a.path==="/index.html");if(!i||i.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(i.content))s=i.content.toString("utf-8");else if(typeof Blob<"u"&&i.content instanceof Blob)s=await i.content.text();else if(typeof File<"u"&&i.content instanceof File)s=await i.content.text();else return!1;let r={"Content-Type":"application/json"};n.deployToken?r.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(r.Authorization=`Bearer ${n.apiKey}`);let p={files:o.map(a=>a.path),index:s};return(await this.request(`${this.apiUrl}${S.SPA_CHECK}`,{method:"POST",headers:r,body:JSON.stringify(p)},"SPA check")).isSPA}};E();function et(e={}){let t={apiUrl:e.apiUrl||K};return e.apiKey!==void 0&&(t.apiKey=e.apiKey),e.deployToken!==void 0&&(t.deployToken=e.deployToken),t}function tt(e,t){let o={...e};return o.apiUrl===void 0&&t.apiUrl!==void 0&&(o.apiUrl=t.apiUrl),o.apiKey===void 0&&t.apiKey!==void 0&&(o.apiKey=t.apiKey),o.deployToken===void 0&&t.deployToken!==void 0&&(o.deployToken=t.deployToken),o.timeout===void 0&&t.timeout!==void 0&&(o.timeout=t.timeout),o.maxConcurrency===void 0&&t.maxConcurrency!==void 0&&(o.maxConcurrency=t.maxConcurrency),o.onProgress===void 0&&t.onProgress!==void 0&&(o.onProgress=t.onProgress),o.caller===void 0&&t.caller!==void 0&&(o.caller=t.caller),o}E();E();xe();async function mo(){let e=JSON.stringify(_e,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:o}=await pe(t);return{path:ve,content:t,size:e.length,md5:o}}async function ot(e,t,o){if(o.spaDetect===!1||o.spa||o.build||o.prerender||e.some(n=>n.path===ve))return e;try{if(await t.checkSPA(e,o)){let i=await mo();return[...e,i]}}catch{}return e}function nt(e){let{getApi:t,ensureInit:o,processInput:n,clientDefaults:i,hasAuth:s}=e;return{upload:async(r,p={})=>{await o();let c=i?tt(p,i):p;if(s&&!s()&&!c.deployToken&&!c.apiKey)try{let y=t(),{secret:A}=await y.fetchAgentToken();c.deployToken=A}catch(y){throw O(y)&&y.type===m.RateLimit?l.rateLimit("public deploy rate limit exceeded, try again later or run 'ship config' for a free account with higher limits"):y}if(!n)throw l.config("processInput function is not provided.");let a=t(),d=await n(r,c);return d=await ot(d,a,c),a.deploy(d,c)},list:async()=>(await o(),t().listDeployments()),get:async r=>(await o(),t().getDeployment(r)),set:async(r,p)=>(await o(),t().updateDeploymentLabels(r,p.labels)),remove:async r=>{await o(),await t().removeDeployment(r)}}}function it(e){let{getApi:t,ensureInit:o}=e;return{set:async(n,i={})=>(await o(),t().setDomain(n,i.deployment,i.labels)),list:async()=>(await o(),t().listDomains()),get:async n=>(await o(),t().getDomain(n)),remove:async n=>{await o(),await t().removeDomain(n)},verify:async n=>(await o(),t().verifyDomain(n)),validate:async n=>(await o(),t().validateDomain(n)),dns:async n=>(await o(),t().getDomainDns(n)),records:async n=>(await o(),t().getDomainRecords(n)),share:async n=>(await o(),t().getDomainShare(n))}}function st(e){let{getApi:t,ensureInit:o}=e;return{get:async()=>(await o(),t().getAccount())}}function rt(e){let{getApi:t,ensureInit:o}=e;return{create:async(n={})=>(await o(),t().createToken(n.ttl,n.labels)),list:async()=>(await o(),t().listTokens()),remove:async n=>{await o(),await t().removeToken(n)}}}var ce=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.auth=null;t={...t,apiUrl:t.apiUrl||void 0,apiKey:t.apiKey||void 0,deployToken:t.deployToken||void 0},this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.http=new le({...t,...et(t),getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let o={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=nt({...o,processInput:(n,i)=>this.processInput(n,i),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this.domains=it(o),this.account=st(o),this.tokens=rt(o)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(t){throw this.initPromise=null,t}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,o){return this.deployments.upload(t,o)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,o){this.http.on(t,o)}off(t,o){this.http.off(t,o)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setDeployToken(t){if(!t||typeof t!="string")throw l.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:t}}setApiKey(t){if(!t||typeof t!="string")throw l.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:t}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};E();de();var Ie=require("zod");E();de();var me=require("zod"),ue={apiUrl:me.z.string().url().optional(),apiKey:me.z.string().min(1).optional(),deployToken:me.z.string().min(1).optional()};var fo=Ie.z.object(ue).strict(),ho={apiUrl:"SHIP_API_URL",apiKey:"SHIP_API_KEY",deployToken:"SHIP_DEPLOY_TOKEN"};function fe(){if(V()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL||void 0,apiKey:process.env.SHIP_API_KEY||void 0,deployToken:process.env.SHIP_DEPLOY_TOKEN||void 0};try{return fo.parse(e)}catch(t){if(t instanceof Ie.z.ZodError){let o=t.issues[0],n=o.path[0],i=(n&&ho[n])??"SHIP environment configuration";throw l.config(`Invalid ${i}: ${o.message}`)}throw l.config("Invalid environment configuration")}}E();async function lt(e,t={}){let{FormData:o,File:n}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),{labels:s,via:r,password:p,flags:c}=t,a=new o,d=[];for(let v of e){if(!Buffer.isBuffer(v.content)&&!(typeof Blob<"u"&&v.content instanceof Blob))throw l.file(`Unsupported file.content type for Node.js: ${v.path}`,{filePath:v.path});if(!v.md5)throw l.file(`File missing md5 checksum: ${v.path}`,{filePath:v.path});let u=new n([v.content],v.path,{type:"application/octet-stream"});a.append("files[]",u),d.push(v.md5)}a.append("checksums",JSON.stringify(d)),s&&s.length>0&&a.append("labels",JSON.stringify(s)),r&&a.append("via",r),p&&a.append("password",p),c?.build&&a.append("build","true"),c?.prerender&&a.append("prerender","true"),c?.spa&&a.append("spa","true");let y=new i(a),A=[];for await(let v of y.encode())A.push(Buffer.from(v));let F=Buffer.concat(A);return{body:F.buffer.slice(F.byteOffset,F.byteOffset+F.byteLength),headers:{"Content-Type":y.contentType,"Content-Length":Buffer.byteLength(F).toString()}}}var ye=class extends ce{constructor(t={}){if(V()!=="node")throw l.business("Node.js Ship class can only be used in Node.js environment.");let o=fe();super({...t,apiUrl:t.apiUrl||o.apiUrl,apiKey:t.apiKey||o.apiKey,deployToken:t.deployToken||o.deployToken})}async deploy(t,o){return super.deploy(t,o)}async processInput(t,o){let n=typeof t=="string"?[t]:t;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,o,this.platformLimits??void 0)}getDeployBodyCreator(){return lt}};var Fe=require("zod"),wt=require("os"),vt=require("cosmiconfig");E();var Do=Fe.z.object(ue).strict(),Pe="ship";function Ct(e){let t=e||void 0,o=(0,wt.homedir)(),n=(0,vt.cosmiconfigSync)(Pe,{searchPlaces:[`.${Pe}rc`,"package.json",`${o}/.${Pe}rc`],stopDir:o}),i;try{i=t?n.load(t):n.search()}catch(s){if(O(s))throw s;let r=s instanceof Error?s.message:String(s),p=t?` (${t})`:"";throw l.config(`Failed to read ship config${p}: ${r}`)}if(!i||!i.config)return{};try{return Do.parse(i.config)}catch(s){if(s instanceof Fe.z.ZodError){let r=s.issues[0],p=r.path.length>0?` at ${r.path.join(".")}`:"";throw l.config(`Invalid config in ${i.filepath}${p}: ${r.message}`)}throw l.config(`Invalid config in ${i.filepath}`)}}function bo(e,t,o){return{apiUrl:e.apiUrl||t.apiUrl||o.apiUrl,apiKey:e.apiKey||t.apiKey||o.apiKey,deployToken:e.deployToken||t.deployToken||o.deployToken}}function Rt(e={}){return new ye(bo(e,fe(),Ct(e.config)))}E();function At(e){return O(e)?e:e instanceof Error?l.business(e.message):l.business(String(e??"Unknown error"))}function Ot(e,t,o){if(e.isAuthError())return o?.apiKey?"authentication failed: invalid API key":o?.deployToken?"authentication failed: invalid or expired deploy token":"authentication required for this command \u2014 deploying needs none: 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.isClientError()||e.status&&e.status>=400&&e.status<500?e.message:"server error: please try again or check https://status.shipstatic.com"}function xt(e,t){return JSON.stringify({error:e,...t?{details:t}:{}},null,2)}var Se=require("yoctocolors");function Eo(){let e=[ge.resolve(__dirname,"../package.json"),ge.resolve(__dirname,"../../package.json")];for(let t of e)try{return JSON.parse((0,z.readFileSync)(t,"utf-8"))}catch{}return{version:"0.0.0"}}var To=Eo(),f=new It.Command;f.exitOverride(e=>{(e.code==="commander.help"||e.code==="commander.version"||e.exitCode===0)&&process.exit(e.exitCode||0),process.argv.includes("--help")&&(Y(P(f).noColor),process.exit(0));let t=P(f),o=e.message||"unknown command error";o=o.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),C(o,t.json,t.noColor),t.json||Y(t.noColor),process.exit(e.exitCode||1)}).configureOutput({writeErr:e=>{e.startsWith("error:")||process.stderr.write(e)},writeOut:e=>process.stdout.write(e)});function Y(e){let t=s=>e?s:(0,Se.bold)(s),o=s=>e?s:(0,Se.dim)(s),n=s=>e?"":`${s} `,i=`${t("USAGE")}
31
31
  ship <path> ${n("\u{1F680}")}Deploy static sites with simplicity
32
32
 
33
33
  ${t("AUTH")}
34
- ship <path> No account, API key or login. Deploying is anonymous
35
- every other command Needs an API key: run \`ship config\`
34
+ deploying No account, API key or login \u2014 it is anonymous.
35
+ Both \`ship <path>\` and \`ship deployments upload <path>\`
36
+ everything else Needs an API key: run \`ship config\`
36
37
 
37
38
  An auth error from another command says nothing about deploying, which never
38
39
  needs credentials. \`ship whoami\` failing is normal and expected until you
@@ -89,8 +90,8 @@ ${t("EXAMPLES")}
89
90
  ship ./dist -q | ship domains set www.example.com
90
91
 
91
92
  ${o("Please report any issues to https://github.com/shipstatic/ship/issues")}
92
- `;console.log(i)}function Z(e,t=[]){return t.concat([e])}function Q(e,t){let o=e?.label?.length?e.label:t?.label;if(!o?.length)return;let n=o.filter(i=>i!=="");return n.length?n:[]}function It(e,t){return e?.password??t?.password??(process.env.SHIP_PASSWORD||void 0)}function ee(e,t){return(...o)=>{let n=P(f),i=o[o.length-1];if(i?.args?.length){let s=i.args.find(r=>!t.includes(r));s&&C(`unknown command '${s}'`,n.json,n.noColor)}n.json||console.log(`usage: ship ${e} <${t.join("|")}>
93
- `),process.exit(1)}}function P(e){let t=e.optsWithGlobals();t.color===!1&&(t.noColor=!0);let o=!!process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0";return!t.noColor&&!o&&(!process.stdout.isTTY||process.env.NO_COLOR!==void 0)&&(t.noColor=!0),t}function kt(e,t){let o=P(f),n=Rt(e),i=At(n,t,{apiKey:o.apiKey,deployToken:o.deployToken});o.json?console.error(Ot(i,n.details)+`
94
- `):(C(i,!1,o.noColor),n.type===m.Validation&&i.includes("unknown command")&&Y(o.noColor)),process.exit(1)}function D(e,t){return async function(...o){let n=P(this),i=t?{operation:t.operation,resourceType:t.resourceType,resourceId:t.getResourceId?.(...o)}:{};try{let{config:s,apiUrl:r,apiKey:p,deployToken:c}=f.opts(),a=Ct({config:s,apiUrl:r,apiKey:p,deployToken:c}),d=await e(a,n,...o);He(d,i,{json:n.json,quiet:n.quiet,noColor:n.noColor})}catch(s){kt(s,i)}}}async function Lt(e,t,o,n,i,s){if(!(0,K.existsSync)(t))throw l.file(`${t} path does not exist`,{filePath:t});let r=(0,K.statSync)(t);if(!r.isDirectory()&&!r.isFile())throw l.file(`${t} path must be a file or directory`,{filePath:t});let p={via:process.env.SHIP_VIA||"cli"};o!==void 0&&(p.labels=o),n!==void 0&&(p.password=n),i?.noPathDetect!==void 0&&(p.pathDetect=!i.noPathDetect),i?.noSpaDetect!==void 0&&(p.spaDetect=!i.noSpaDetect);let c=new AbortController;p.signal=c.signal;let a=null;if(process.stdout.isTTY&&!s.json&&!s.quiet&&!s.noColor){let{default:y}=await import("yocto-spinner");a=y({text:"uploading\u2026"}).start()}let d=()=>{c.abort(),a&&a.stop(),process.exit(130)};process.on("SIGINT",d);try{return await e.deployments.upload(t,p)}finally{process.removeListener("SIGINT",d),a&&a.stop()}}f.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(bo.version,"--version","Show version information").option("--api-key <key>","API key for authenticated deployments").option("--deploy-token <token>","Deploy token for authenticated deployments").option("--config <file>","Custom config file path").option("--api-url <url>","API URL (for development)").option("--json","Output results in JSON format").option("-q, --quiet","Output only the resource identifier").option("--no-color","Disable colored output").option("--help","Display help for command").helpOption(!1);f.hook("preAction",e=>{let t=P(e);t.help&&(Y(t.noColor),process.exit(0))});f.hook("preAction",e=>{let t=P(e);try{t.apiKey&&typeof t.apiKey=="string"&&ne(t.apiKey),t.deployToken&&typeof t.deployToken=="string"&&_e(t.deployToken),t.apiUrl&&typeof t.apiUrl=="string"&&Ue(t.apiUrl)}catch(o){throw O(o)&&(C(o.message,t.json,t.noColor),process.exit(1)),o}});f.command("ping").description("Check API connectivity").action(D((e,t)=>e.ping()));f.command("whoami").description("Get current account information").action(D((e,t)=>e.whoami(),{operation:"get",resourceType:"Account"}));var te=f.command("deployments").description("Manage deployments").enablePositionalOptions().action(ee("deployments",["list","upload","get","set","remove"]));te.command("list").description("List all deployments").action(D((e,t)=>e.deployments.list()));te.command("upload <path>").description("Upload deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",Z,[]).option("--password <password>","Password-protect this deployment").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(D((e,t,o,n)=>Lt(e,o,Q(n,f.opts()),It(n,f.opts()),n,t),{operation:"upload"}));te.command("get <deployment>").description("Show deployment information").action(D((e,t,o)=>e.deployments.get(o),{operation:"get",resourceType:"Deployment",getResourceId:e=>e}));te.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",Z,[]).action(D(async(e,t,o,n)=>{let i=Q(n,f.opts())||[];return e.deployments.set(o,{labels:i})},{operation:"set",resourceType:"Deployment",getResourceId:e=>e}));te.command("remove <deployment>").description("Delete deployment permanently").action(D((e,t,o)=>e.deployments.remove(o),{operation:"remove",resourceType:"Deployment",getResourceId:e=>e}));var M=f.command("domains").description("Manage domains").enablePositionalOptions().action(ee("domains",["list","get","set","validate","records","dns","share","verify","remove"]));M.command("list").description("List all domains").action(D((e,t)=>e.domains.list()));M.command("get <name>").description("Show domain information").action(D((e,t,o)=>e.domains.get(o),{operation:"get",resourceType:"Domain",getResourceId:e=>e}));M.command("validate <name>").description("Check if domain name is valid and available").action(D(async(e,t,o)=>{let n=await e.domains.validate(o);return n.valid||(process.exitCode=1),n},{operation:"validate",resourceType:"Domain",getResourceId:e=>e}));M.command("verify <name>").description("Trigger DNS verification for external domain").action(D((e,t,o)=>e.domains.verify(o),{operation:"verify",resourceType:"Domain",getResourceId:e=>e}));M.command("records <name>").description("Show required DNS records for domain setup").action(D((e,t,o)=>e.domains.records(o),{operation:"records",resourceType:"Domain",getResourceId:e=>e}));M.command("dns <name>").description("Look up DNS provider for a domain").action(D((e,t,o)=>e.domains.dns(o),{operation:"dns",resourceType:"Domain",getResourceId:e=>e}));M.command("share <name>").description("Get shareable DNS setup link").action(D((e,t,o)=>e.domains.share(o),{operation:"share",resourceType:"Domain",getResourceId:e=>e}));M.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",Z,[]).action(D(async(e,t,o,n,i)=>{!n&&!process.stdin.isTTY&&(n=await new Promise(c=>{let a="";process.stdin.on("data",d=>a+=d),process.stdin.on("end",()=>c(a.trim()||void 0))}));let s=Q(i,f.opts()),r={};n&&(r.deployment=n),s!==void 0&&(r.labels=s);let p=await e.domains.set(o,r);if(p.isCreate&&o.includes("."))try{let[c,a]=await Promise.all([e.domains.records(o),e.domains.share(o)]);return{...p,_dnsRecords:c.records,_shareHash:a.hash}}catch{}return p},{operation:"set",resourceType:"Domain",getResourceId:e=>e}));M.command("remove <name>").description("Delete domain permanently").action(D((e,t,o)=>e.domains.remove(o),{operation:"remove",resourceType:"Domain",getResourceId:e=>e}));var Fe=f.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(ee("tokens",["list","create","remove"]));Fe.command("list").description("List all tokens").action(D((e,t)=>e.tokens.list()));Fe.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)",Z,[]).action(D((e,t,o)=>{let n={};o?.ttl!==void 0&&(n.ttl=o.ttl);let i=Q(o,f.opts());return i!==void 0&&(n.labels=i),e.tokens.create(n)},{operation:"create",resourceType:"Token"}));Fe.command("remove <token>").description("Delete token permanently").action(D((e,t,o)=>e.tokens.remove(o),{operation:"remove",resourceType:"Token",getResourceId:e=>e}));var Eo=f.command("account").description("Manage account").action(ee("account",["get"]));Eo.command("get").description("Show account information").action(D((e,t)=>e.whoami(),{operation:"get",resourceType:"Account"}));var Pt=f.command("completion").description("Setup shell completion").action(ee("completion",["install","uninstall"]));Pt.command("install").description("Install shell completion script").action(()=>{let e=P(f),t=ye.resolve(__dirname,"completions");Be(t,{json:e.json,noColor:e.noColor})});Pt.command("uninstall").description("Uninstall shell completion script").action(()=>{let e=P(f);qe({json:e.json,noColor:e.noColor})});f.command("config").description("Save your API key").action(async()=>{let e=P(f);try{await Ze({noColor:e.noColor,json:e.json})}catch(t){kt(t)}});f.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",Z,[]).option("--password <password>","Password-protect this deployment").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(D(async(e,t,o,n)=>{if(o||(Y(t.noColor),process.exit(0)),!(0,K.existsSync)(o)&&!o.includes("/")&&!o.includes("\\")&&!o.includes(".")&&!o.startsWith("~"))throw l.validation(`unknown command '${o}'`);return Lt(e,o,Q(n,f.opts()),It(n,f.opts()),n,t)},{operation:"upload"}));function wo(){let e=process.argv,t=e.includes("--compbash"),o=e.includes("--compzsh"),n=e.includes("--compfish");if(!t&&!o&&!n)return;console.log(["ping","whoami","deployments","domains","tokens","account","config","completion"].join(n?`
95
- `:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&wo();if(process.env.NODE_ENV!=="test")try{f.parse(process.argv)}catch(e){if(e instanceof Error&&"code"in e){let t=e.code,o=e.exitCode;t?.startsWith("commander.")&&process.exit(o||1)}throw e}
93
+ `;console.log(i)}function Z(e,t=[]){return t.concat([e])}function Q(e,t){let o=e?.label?.length?e.label:t?.label;if(!o?.length)return;let n=o.filter(i=>i!=="");return n.length?n:[]}function kt(e,t){return e?.password??t?.password??(process.env.SHIP_PASSWORD||void 0)}function ee(e,t){return(...o)=>{let n=P(f),i=o[o.length-1];if(i?.args?.length){let s=i.args.find(r=>!t.includes(r));s&&C(`unknown command '${s}'`,n.json,n.noColor)}n.json||console.log(`usage: ship ${e} <${t.join("|")}>
94
+ `),process.exit(1)}}function P(e){let t=e.optsWithGlobals();t.color===!1&&(t.noColor=!0);let o=!!process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0";return!t.noColor&&!o&&(!process.stdout.isTTY||process.env.NO_COLOR!==void 0)&&(t.noColor=!0),t}function Lt(e,t){let o=P(f),n=At(e),i=Ot(n,t,{apiKey:o.apiKey,deployToken:o.deployToken});o.json?console.error(xt(i,n.details)+`
95
+ `):(C(i,!1,o.noColor),n.type===m.Validation&&i.includes("unknown command")&&Y(o.noColor)),process.exit(1)}function D(e,t){return async function(...o){let n=P(this),i=t?{operation:t.operation,resourceType:t.resourceType,resourceId:t.getResourceId?.(...o)}:{};try{let{config:s,apiUrl:r,apiKey:p,deployToken:c}=f.opts(),a=Rt({config:s,apiUrl:r,apiKey:p,deployToken:c}),d=await e(a,n,...o);ze(d,i,{json:n.json,quiet:n.quiet,noColor:n.noColor})}catch(s){Lt(s,i)}}}async function Pt(e,t,o,n,i,s){if(!(0,z.existsSync)(t))throw l.file(`${t} path does not exist`,{filePath:t});let r=(0,z.statSync)(t);if(!r.isDirectory()&&!r.isFile())throw l.file(`${t} path must be a file or directory`,{filePath:t});let p={via:process.env.SHIP_VIA||"cli"};o!==void 0&&(p.labels=o),n!==void 0&&(p.password=n),i?.noPathDetect!==void 0&&(p.pathDetect=!i.noPathDetect),i?.noSpaDetect!==void 0&&(p.spaDetect=!i.noSpaDetect);let c=new AbortController;p.signal=c.signal;let a=null;if(process.stdout.isTTY&&!s.json&&!s.quiet&&!s.noColor){let{default:y}=await import("yocto-spinner");a=y({text:"uploading\u2026"}).start()}let d=()=>{c.abort(),a&&a.stop(),process.exit(130)};process.on("SIGINT",d);try{return await e.deployments.upload(t,p)}finally{process.removeListener("SIGINT",d),a&&a.stop()}}f.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(To.version,"--version","Show version information").option("--api-key <key>","API key for authenticated deployments").option("--deploy-token <token>","Deploy token for authenticated deployments").option("--config <file>","Custom config file path").option("--api-url <url>","API URL (for development)").option("--json","Output results in JSON format").option("-q, --quiet","Output only the resource identifier").option("--no-color","Disable colored output").option("--help","Display help for command").helpOption(!1);f.hook("preAction",e=>{let t=P(e);t.help&&(Y(t.noColor),process.exit(0))});f.hook("preAction",e=>{let t=P(e);try{t.apiKey&&typeof t.apiKey=="string"&&ne(t.apiKey),t.deployToken&&typeof t.deployToken=="string"&&Ue(t.deployToken),t.apiUrl&&typeof t.apiUrl=="string"&&Me(t.apiUrl)}catch(o){throw O(o)&&(C(o.message,t.json,t.noColor),process.exit(1)),o}});f.command("ping").description("Check API connectivity").action(D((e,t)=>e.ping()));f.command("whoami").description("Get current account information").action(D((e,t)=>e.whoami(),{operation:"get",resourceType:"Account"}));var te=f.command("deployments").description("Manage deployments").enablePositionalOptions().action(ee("deployments",["list","upload","get","set","remove"]));te.command("list").description("List all deployments").action(D((e,t)=>e.deployments.list()));te.command("upload <path>").description("Upload deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",Z,[]).option("--password <password>","Password-protect this deployment").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(D((e,t,o,n)=>Pt(e,o,Q(n,f.opts()),kt(n,f.opts()),n,t),{operation:"upload"}));te.command("get <deployment>").description("Show deployment information").action(D((e,t,o)=>e.deployments.get(o),{operation:"get",resourceType:"Deployment",getResourceId:e=>e}));te.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",Z,[]).action(D(async(e,t,o,n)=>{let i=Q(n,f.opts())||[];return e.deployments.set(o,{labels:i})},{operation:"set",resourceType:"Deployment",getResourceId:e=>e}));te.command("remove <deployment>").description("Delete deployment permanently").action(D((e,t,o)=>e.deployments.remove(o),{operation:"remove",resourceType:"Deployment",getResourceId:e=>e}));var M=f.command("domains").description("Manage domains").enablePositionalOptions().action(ee("domains",["list","get","set","validate","records","dns","share","verify","remove"]));M.command("list").description("List all domains").action(D((e,t)=>e.domains.list()));M.command("get <name>").description("Show domain information").action(D((e,t,o)=>e.domains.get(o),{operation:"get",resourceType:"Domain",getResourceId:e=>e}));M.command("validate <name>").description("Check if domain name is valid and available").action(D(async(e,t,o)=>{let n=await e.domains.validate(o);return n.valid||(process.exitCode=1),n},{operation:"validate",resourceType:"Domain",getResourceId:e=>e}));M.command("verify <name>").description("Trigger DNS verification for external domain").action(D((e,t,o)=>e.domains.verify(o),{operation:"verify",resourceType:"Domain",getResourceId:e=>e}));M.command("records <name>").description("Show required DNS records for domain setup").action(D((e,t,o)=>e.domains.records(o),{operation:"records",resourceType:"Domain",getResourceId:e=>e}));M.command("dns <name>").description("Look up DNS provider for a domain").action(D((e,t,o)=>e.domains.dns(o),{operation:"dns",resourceType:"Domain",getResourceId:e=>e}));M.command("share <name>").description("Get shareable DNS setup link").action(D((e,t,o)=>e.domains.share(o),{operation:"share",resourceType:"Domain",getResourceId:e=>e}));M.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",Z,[]).action(D(async(e,t,o,n,i)=>{!n&&!process.stdin.isTTY&&(n=await new Promise(c=>{let a="";process.stdin.on("data",d=>a+=d),process.stdin.on("end",()=>c(a.trim()||void 0))}));let s=Q(i,f.opts()),r={};n&&(r.deployment=n),s!==void 0&&(r.labels=s);let p=await e.domains.set(o,r);if(p.isCreate&&o.includes("."))try{let[c,a]=await Promise.all([e.domains.records(o),e.domains.share(o)]);return{...p,_dnsRecords:c.records,_shareHash:a.hash}}catch{}return p},{operation:"set",resourceType:"Domain",getResourceId:e=>e}));M.command("remove <name>").description("Delete domain permanently").action(D((e,t,o)=>e.domains.remove(o),{operation:"remove",resourceType:"Domain",getResourceId:e=>e}));var $e=f.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(ee("tokens",["list","create","remove"]));$e.command("list").description("List all tokens").action(D((e,t)=>e.tokens.list()));$e.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)",Z,[]).action(D((e,t,o)=>{let n={};o?.ttl!==void 0&&(n.ttl=o.ttl);let i=Q(o,f.opts());return i!==void 0&&(n.labels=i),e.tokens.create(n)},{operation:"create",resourceType:"Token"}));$e.command("remove <token>").description("Delete token permanently").action(D((e,t,o)=>e.tokens.remove(o),{operation:"remove",resourceType:"Token",getResourceId:e=>e}));var wo=f.command("account").description("Manage account").action(ee("account",["get"]));wo.command("get").description("Show account information").action(D((e,t)=>e.whoami(),{operation:"get",resourceType:"Account"}));var Ft=f.command("completion").description("Setup shell completion").action(ee("completion",["install","uninstall"]));Ft.command("install").description("Install shell completion script").action(()=>{let e=P(f),t=ge.resolve(__dirname,"completions");qe(t,{json:e.json,noColor:e.noColor})});Ft.command("uninstall").description("Uninstall shell completion script").action(()=>{let e=P(f);Ve({json:e.json,noColor:e.noColor})});f.command("config").description("Save your API key").action(async()=>{let e=P(f);try{await Qe({noColor:e.noColor,json:e.json})}catch(t){Lt(t)}});f.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",Z,[]).option("--password <password>","Password-protect this deployment").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(D(async(e,t,o,n)=>{if(o||(Y(t.noColor),process.exit(0)),!(0,z.existsSync)(o)&&!o.includes("/")&&!o.includes("\\")&&!o.includes(".")&&!o.startsWith("~"))throw l.validation(`unknown command '${o}'`);return Pt(e,o,Q(n,f.opts()),kt(n,f.opts()),n,t)},{operation:"upload"}));function vo(){let e=process.argv,t=e.includes("--compbash"),o=e.includes("--compzsh"),n=e.includes("--compfish");if(!t&&!o&&!n)return;console.log(["ping","whoami","deployments","domains","tokens","account","config","completion"].join(n?`
96
+ `:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&vo();if(process.env.NODE_ENV!=="test")try{f.parse(process.argv)}catch(e){if(e instanceof Error&&"code"in e){let t=e.code,o=e.exitCode;t?.startsWith("commander.")&&process.exit(o||1)}throw e}
96
97
  //# sourceMappingURL=cli.cjs.map