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