@shipstatic/ship 0.1.24 → 0.1.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Me=Object.create;var ye=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Je=Object.getPrototypeOf,Ge=Object.prototype.hasOwnProperty;var ne=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of He(t))!Ge.call(e,i)&&i!==o&&ye(e,i,{get:()=>t[i],enumerable:!(n=Ke(t,i))||n.enumerable});return e},ge=(e,t,o)=>(ne(e,t,"default"),o&&ne(o,t,"default")),b=(e,t,o)=>(o=e!=null?Me(Je(e)):{},ne(t||!e||!e.__esModule?ye(o,"default",{value:e,enumerable:!0}):o,e));var ze=require("commander");var we=null;function We(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function w(){return we||We()}var z=require("zod");var E={};ge(E,require("@shipstatic/types"));var G="https://api.shipstatic.com";var ie="ship",qe=z.z.object({apiUrl:z.z.string().url().optional(),apiKey:z.z.string().optional(),deployToken:z.z.string().optional()}).strict();function Se(e){try{return qe.parse(e)}catch(t){if(t instanceof z.z.ZodError){let o=t.issues[0],n=o.path.length>0?` at ${o.path.join(".")}`:"";throw E.ShipError.config(`Configuration validation failed${n}: ${o.message}`)}throw E.ShipError.config("Configuration validation failed")}}async function Ve(e){try{if(w()!=="node")return{};let{cosmiconfigSync:t}=await import("cosmiconfig"),o=await import("os"),n=t(ie,{searchPlaces:[`.${ie}rc`,"package.json",`${o.homedir()}/.${ie}rc`],stopDir:o.homedir()}),i;if(e?i=n.load(e):i=n.search(),i&&i.config)return Se(i.config)}catch(t){if(t instanceof E.ShipError)throw t}return{}}async function be(e){if(w()!=="node")return{};let t={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},o=await Ve(e),n={apiUrl:t.apiUrl??o.apiUrl,apiKey:t.apiKey??o.apiKey,deployToken:t.deployToken??o.deployToken};return Se(n)}function se(e={},t={}){let o={apiUrl:e.apiUrl||t.apiUrl||G,apiKey:e.apiKey||t.apiKey,deployToken:e.deployToken||t.deployToken},n={apiUrl:o.apiUrl};return o.apiKey!==void 0&&(n.apiKey=o.apiKey),o.deployToken!==void 0&&(n.deployToken=o.deployToken),n}function Pe(e={},t){return{onProgress:t.onProgress,onProgressStats:t.onProgressStats,maxConcurrency:t.maxConcurrentDeploys,timeout:t.timeout,apiKey:t.apiKey,deployToken:t.deployToken,apiUrl:t.apiUrl,...e}}var q=b(require("mime-types"),1),C=require("@shipstatic/types");var W="/deployments",Ce="/ping",M="/aliases",Ze="/config",Ye="/account",Xe="/spa-check";function Qe(e){return typeof e=="string"?q.lookup(e)||"application/octet-stream":q.lookup(e.name)||e.type||"application/octet-stream"}async function et(e){let t=[];for await(let o of e)t.push(o);return t}var K=class{constructor(t){this.apiUrl=t.apiUrl||G,this.apiKey=t.apiKey??"",this.deployToken=t.deployToken??""}#i(t={}){let o={...t};return this.deployToken?o.Authorization=`Bearer ${this.deployToken}`:this.apiKey&&(o.Authorization=`Bearer ${this.apiKey}`),o}async#o(t,o={},n){let i=this.#i(o.headers),s={...o,headers:i,credentials:w()==="browser"?"include":"same-origin"};try{return await fetch(t,s)}catch(r){throw this.#t(r,n),r}}async#e(t,o={},n){try{let i=await this.#o(t,o,n);return i.ok||await this.#n(i,n),i.headers.get("Content-Length")==="0"||i.status===204?void 0:await i.json()}catch(i){throw i instanceof C.ShipError||this.#t(i,n),i}}async ping(){return(await this.#e(`${this.apiUrl}${Ce}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.#e(`${this.apiUrl}${Ce}`,{method:"GET"},"Ping")}async getConfig(){return await this.#e(`${this.apiUrl}${Ze}`,{method:"GET"},"Config")}async deploy(t,o={}){this.#s(t);let{apiUrl:n=this.apiUrl,signal:i,apiKey:s,deployToken:r}=o,{requestBody:a,requestHeaders:p}=await this.#r(t),c={};r?c={Authorization:`Bearer ${r}`}:s&&(c={Authorization:`Bearer ${s}`});let l={method:"POST",body:a,headers:{...p,...c},signal:i||null};return await this.#e(`${n}${W}`,l,"Deploy")}#s(t){if(!t.length)throw C.ShipError.business("No files to deploy.");for(let o of t)if(!o.md5)throw C.ShipError.file(`MD5 checksum missing for file: ${o.path}`,o.path)}async#r(t){let o,n={};if(w()==="browser")o=this.#a(t);else if(w()==="node"){let{body:i,headers:s}=await this.#l(t);o=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),n=s}else throw C.ShipError.business("Unknown or unsupported execution environment");return{requestBody:o,requestHeaders:n}}#a(t){let o=new FormData,n=[];for(let i=0;i<t.length;i++){let s=t[i],r;if(s.content instanceof File||s.content instanceof Blob)r=s.content;else throw C.ShipError.file(`Unsupported file.content type for browser FormData: ${s.path}`,s.path);let a=Qe(r instanceof File?r:s.path),p=new File([r],s.path,{type:a});o.append("files[]",p),n.push(s.md5)}return o.append("checksums",JSON.stringify(n)),o}async#l(t){let{FormData:o,File:n}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),s=await import("path"),r=new o,a=[];for(let d=0;d<t.length;d++){let h=t[d],$=q.lookup(h.path)||"application/octet-stream",v;if(Buffer.isBuffer(h.content))v=new n([h.content],h.path,{type:$});else if(typeof Blob<"u"&&h.content instanceof Blob)v=new n([h.content],h.path,{type:$});else throw C.ShipError.file(`Unsupported file.content type for Node.js FormData: ${h.path}`,h.path);let L=h.path.startsWith("/")?h.path:"/"+h.path;r.append("files[]",v,L),a.push(h.md5)}r.append("checksums",JSON.stringify(a));let p=new i(r),c=await et(p.encode()),l=Buffer.concat(c.map(d=>Buffer.from(d))),u={"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(l).toString()};return{body:l,headers:u}}async#n(t,o){let n={};try{let i=t.headers.get("content-type");i&&i.includes("application/json")?n=await t.json():n={message:await t.text()}}catch{n={message:"Failed to parse error response"}}if(n.error||n.code||n.message){let i=n.message||n.error||`${o} failed due to API error`;throw t.status===401?C.ShipError.authentication(i):C.ShipError.api(i,t.status,n.code,n)}throw t.status===401?C.ShipError.authentication(`Authentication failed for ${o}`):C.ShipError.api(`${o} failed due to API error`,t.status,void 0,n)}#t(t,o){throw t.name==="AbortError"?C.ShipError.cancelled(`${o} operation was cancelled.`):t instanceof TypeError&&t.message.includes("fetch")?C.ShipError.network(`${o} failed due to network error: ${t.message}`,t):t instanceof C.ShipError?t:C.ShipError.business(`An unexpected error occurred during ${o}: ${t.message||"Unknown error"}`)}async listDeployments(){return await this.#e(`${this.apiUrl}${W}`,{method:"GET"},"List Deployments")}async getDeployment(t){return await this.#e(`${this.apiUrl}${W}/${t}`,{method:"GET"},"Get Deployment")}async removeDeployment(t){await this.#e(`${this.apiUrl}${W}/${t}`,{method:"DELETE"},"Remove Deployment")}async setAlias(t,o){try{let n=await this.#o(`${this.apiUrl}${M}/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({deployment:o})},"Set Alias");return n.ok||await this.#n(n,"Set Alias"),{...await n.json(),isCreate:n.status===201}}catch(n){this.#t(n,"Set Alias")}}async getAlias(t){return await this.#e(`${this.apiUrl}${M}/${encodeURIComponent(t)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.#e(`${this.apiUrl}${M}`,{method:"GET"},"List Aliases")}async removeAlias(t){await this.#e(`${this.apiUrl}${M}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove Alias")}async checkAlias(t){return await this.#e(`${this.apiUrl}${M}/${encodeURIComponent(t)}/dns-check`,{method:"POST"},"Check Alias")}async getAccount(){return await this.#e(`${this.apiUrl}${Ye}`,{method:"GET"},"Get Account")}async createApiKey(){return await this.#e(`${this.apiUrl}/key`,{method:"POST"},"Create API Key")}async checkSPA(t){let o=t.find(p=>p.path==="index.html"||p.path==="/index.html");if(!o)return!1;let n=100*1024;if(o.size>n)return!1;let i;if(Buffer.isBuffer(o.content))i=o.content.toString("utf-8");else if(typeof Blob<"u"&&o.content instanceof Blob)i=await o.content.text();else if(typeof File<"u"&&o.content instanceof File)i=await o.content.text();else return!1;let r={files:t.map(p=>p.path),index:i};return(await this.#e(`${this.apiUrl}${Xe}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"SPA Check")).isSPA}};var Ne=require("@shipstatic/types");var De=require("@shipstatic/types"),re=null;function ve(e){re=e}function H(){if(re===null)throw De.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return re}var P=require("@shipstatic/types");var O=require("@shipstatic/types");async function tt(e){let t=(await import("spark-md5")).default;return new Promise((o,n)=>{let s=Math.ceil(e.size/2097152),r=0,a=new t.ArrayBuffer,p=new FileReader,c=()=>{let l=r*2097152,u=Math.min(l+2097152,e.size);p.readAsArrayBuffer(e.slice(l,u))};p.onload=l=>{let u=l.target?.result;if(!u){n(O.ShipError.business("Failed to read file chunk"));return}a.append(u),r++,r<s?c():o({md5:a.end()})},p.onerror=()=>{n(O.ShipError.business("Failed to calculate MD5: FileReader error"))},c()})}async function ot(e){let t=await import("crypto");if(Buffer.isBuffer(e)){let n=t.createHash("md5");return n.update(e),{md5:n.digest("hex")}}let o=await import("fs");return new Promise((n,i)=>{let s=t.createHash("md5"),r=o.createReadStream(e);r.on("error",a=>i(O.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 U(e){let t=w();if(t==="browser"){if(!(e instanceof Blob))throw O.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return tt(e)}if(t==="node"){if(!(Buffer.isBuffer(e)||typeof e=="string"))throw O.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return ot(e)}throw O.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var Ae=require("junk"),nt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"];function V(e){return!e||e.length===0?[]:e.filter(t=>{if(!t)return!1;let o=t.replace(/\\/g,"/").split("/").filter(Boolean);if(o.length===0)return!0;let n=o[o.length-1];if((0,Ae.isJunk)(n))return!1;let i=o.slice(0,-1);for(let s of i)if(nt.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var R=require("@shipstatic/types");function Z(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}function Y(e,t={}){if(t.flatten===!1)return e.map(n=>({path:Z(n),name:ae(n)}));let o=it(e);return e.map(n=>{let i=Z(n);if(o){let s=o.endsWith("/")?o:`${o}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=ae(n)),{path:i,name:ae(n)}})}function it(e){if(!e.length)return"";let o=e.map(s=>Z(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 ae(e){return e.split(/[/\\]/).pop()||e}var T=b(require("fs"),1),x=b(require("path"),1);function xe(e){let t=[];try{let o=T.readdirSync(e);for(let n of o){let i=x.join(e,n),s=T.statSync(i);if(s.isDirectory()){let r=xe(i);t.push(...r)}else s.isFile()&&t.push(i)}}catch(o){console.error(`Error reading directory ${e}:`,o)}return t}async function Fe(e,t={}){let o=x.resolve(e),i=(()=>{let d=T.statSync(o);return d.isFile()?[o]:d.isDirectory()?xe(o):[]})().filter(d=>{let h=x.basename(d);return V([h]).length>0}),r=T.statSync(o).isDirectory()?o:x.dirname(o),a=i.map(d=>x.relative(r,d).replace(/\\/g,"/")||x.basename(d)),p=Y(a,{flatten:t.pathDetect!==!1}),c=[],l=0;for(let d=0;d<i.length;d++){let h=i[d],$=p[d].path;try{let v=T.statSync(h);if(v.size===0){console.warn(`Skipping empty file: ${h}`);continue}let L=H();if(v.size>L.maxFileSize)throw R.ShipError.business(`File ${h} is too large. Maximum allowed size is ${L.maxFileSize/(1024*1024)}MB.`);if(l+=v.size,l>L.maxTotalSize)throw R.ShipError.business(`Total deploy size is too large. Maximum allowed is ${L.maxTotalSize/(1024*1024)}MB.`);let oe=T.readFileSync(h),{md5:Be}=await U(oe);if($.includes("\0")||$.includes("/../")||$.startsWith("../")||$.endsWith("/.."))throw R.ShipError.business(`Security error: Unsafe file path "${$}" for file: ${h}`);c.push({path:$,content:oe,size:oe.length,md5:Be})}catch(v){if(v instanceof R.ShipError&&v.isClientError&&v.isClientError())throw v;console.error(`Could not process file ${h}:`,v)}}let u=H();if(c.length>u.maxFilesCount)throw R.ShipError.business(`Too many files to deploy. Maximum allowed is ${u.maxFilesCount} files.`);return c}async function le(e,t={}){if(w()!=="node")throw R.ShipError.business("processFilesForNode can only be called in a Node.js environment.");if(e.length>1){let o=[];for(let n of e){let i=await Fe(n,t);o.push(...i)}return o}return await Fe(e[0],t)}var ce=require("@shipstatic/types");async function pe(e,t={}){if(w()!=="browser")throw ce.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let o=Array.isArray(e)?e:Array.from(e),n=o.map(l=>l.webkitRelativePath||l.name),i=Y(n,{flatten:t.pathDetect!==!1}),s=[];for(let l=0;l<o.length;l++){let u=o[l],d=i[l].path;if(d.includes("..")||d.includes("\0"))throw ce.ShipError.business(`Security error: Unsafe file path "${d}" for file: ${u.name}`);s.push({file:u,relativePath:d})}let r=s.map(l=>l.relativePath),a=V(r),p=new Set(a),c=[];for(let l of s){if(!p.has(l.relativePath)||l.file.size===0)continue;let{md5:u}=await U(l.file);c.push({content:l.file,path:l.relativePath,size:l.file.size,md5:u})}return c}function $e(e,t={}){let o=H();if(!t.skipEmptyCheck&&e.length===0)throw P.ShipError.business("No files to deploy.");if(e.length>o.maxFilesCount)throw P.ShipError.business(`Too many files to deploy. Maximum allowed is ${o.maxFilesCount}.`);let n=0;for(let i of e){if(i.size>o.maxFileSize)throw P.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 P.ShipError.business(`Total deploy size is too large. Maximum allowed is ${o.maxTotalSize/(1024*1024)}MB.`)}}function Te(e,t){if(t==="node"){if(!Array.isArray(e))throw P.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(e.length===0)throw P.ShipError.business("No files to deploy.");if(!e.every(o=>typeof o=="string"))throw P.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(t==="browser"&&e instanceof HTMLInputElement&&!e.files)throw P.ShipError.business("No files selected in HTMLInputElement")}function ke(e){return $e(e,{skipEmptyCheck:!0}),e.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),e}async function st(e,t={}){Te(e,"node");let o=await le(e,t);return ke(o)}async function rt(e,t={}){Te(e,"browser");let o;if(e instanceof HTMLInputElement)o=Array.from(e.files);else if(typeof e=="object"&&e!==null&&typeof e.length=="number"&&typeof e.item=="function")o=Array.from(e);else if(Array.isArray(e)){if(e.length>0&&typeof e[0]=="string")throw P.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");o=e}else throw P.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),$e(o);let n=await pe(o,t);return ke(n)}async function Ee(e,t={},o){let n=w();if(n!=="node"&&n!=="browser")throw P.ShipError.business("Unsupported execution environment.");let i;return n==="node"?i=await st(e,t):i=await rt(e,t),o&&(i=await lt(i,o,t)),i}async function at(){let e={rewrites:[{source:"/(.*)",destination:"/index.html"}]},t=Buffer.from(JSON.stringify(e,null,2),"utf-8"),{md5:o}=await U(t);return{path:P.DEPLOYMENT_CONFIG_FILENAME,content:t,size:t.length,md5:o}}async function lt(e,t,o){if(o.spaDetect===!1||e.some(n=>n.path===P.DEPLOYMENT_CONFIG_FILENAME))return e;try{if(await t.checkSPA(e)){let i=await at();return console.log(`SPA detected - generated ${P.DEPLOYMENT_CONFIG_FILENAME}`),[...e,i]}}catch{console.warn("SPA detection failed, continuing without auto-config")}return e}function Oe(e,t,o){return{create:async(n,i={})=>{o&&await o();let s=t?Pe(i,t):i,r=await Ee(n,s,e());return await e().deploy(r,s)},list:async()=>(o&&await o(),e().listDeployments()),remove:async n=>{o&&await o(),await e().removeDeployment(n)},get:async n=>(o&&await o(),e().getDeployment(n))}}function Re(e,t){return{set:async(o,n)=>(t&&await t(),e().setAlias(o,n)),get:async o=>(t&&await t(),e().getAlias(o)),list:async()=>(t&&await t(),e().listAliases()),remove:async o=>{t&&await t(),await e().removeAlias(o)},check:async o=>(t&&await t(),e().checkAlias(o))}}function Ie(e,t){return{get:async()=>(t&&await t(),e().getAccount())}}function je(e,t){return{create:async()=>(t&&await t(),e().createApiKey())}}var I=require("@shipstatic/types"),X=class{constructor(t={}){this.initPromise=null;if(this.clientOptions=t,this.environment=w(),this.environment!=="node"&&this.environment!=="browser")throw Ne.ShipError.business("Unsupported execution environment.");let o=se(t,{});this.http=new K({...t,...o});let n=this.getInitCallback(),i=()=>this.http;this._deployments=Oe(i,this.clientOptions,n),this._aliases=Re(i,n),this._account=Ie(i,n),this._keys=je(i,n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.initializeConfig()),this.initPromise}getInitCallback(){return()=>this.ensureInitialized()}async initializeConfig(){try{let t=await be(this.clientOptions.configFile),o=se(this.clientOptions,t);this.http=new K({...this.clientOptions,...o});let n=await this.http.getConfig();ve(n)}catch(t){throw this.initPromise=null,t}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,o){return this.deployments.create(t,o)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get aliases(){return this._aliases}get account(){return this._account}get keys(){return this._keys}};var B=require("@shipstatic/types"),j=require("fs"),g=b(require("path"),1);var me=b(require("columnify"),1),f=require("yoctocolors"),S=(e,t,o)=>o?t:e(t),F=(e,t,o)=>{console.log(t?JSON.stringify({success:e},null,2)+`
2
+ "use strict";var Me=Object.create;var ye=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Je=Object.getPrototypeOf,Ge=Object.prototype.hasOwnProperty;var ne=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of He(t))!Ge.call(e,i)&&i!==o&&ye(e,i,{get:()=>t[i],enumerable:!(n=Ke(t,i))||n.enumerable});return e},ge=(e,t,o)=>(ne(e,t,"default"),o&&ne(o,t,"default")),b=(e,t,o)=>(o=e!=null?Me(Je(e)):{},ne(t||!e||!e.__esModule?ye(o,"default",{value:e,enumerable:!0}):o,e));var ze=require("commander");var we=null;function We(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function w(){return we||We()}var z=require("zod");var E={};ge(E,require("@shipstatic/types"));var G="https://api.shipstatic.com";var ie="ship",qe=z.z.object({apiUrl:z.z.string().url().optional(),apiKey:z.z.string().optional(),deployToken:z.z.string().optional()}).strict();function Se(e){try{return qe.parse(e)}catch(t){if(t instanceof z.z.ZodError){let o=t.issues[0],n=o.path.length>0?` at ${o.path.join(".")}`:"";throw E.ShipError.config(`Configuration validation failed${n}: ${o.message}`)}throw E.ShipError.config("Configuration validation failed")}}async function Ve(e){try{if(w()!=="node")return{};let{cosmiconfigSync:t}=await import("cosmiconfig"),o=await import("os"),n=t(ie,{searchPlaces:[`.${ie}rc`,"package.json",`${o.homedir()}/.${ie}rc`],stopDir:o.homedir()}),i;if(e?i=n.load(e):i=n.search(),i&&i.config)return Se(i.config)}catch(t){if(t instanceof E.ShipError)throw t}return{}}async function be(e){if(w()!=="node")return{};let t={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},o=await Ve(e),n={apiUrl:t.apiUrl??o.apiUrl,apiKey:t.apiKey??o.apiKey,deployToken:t.deployToken??o.deployToken};return Se(n)}function se(e={},t={}){let o={apiUrl:e.apiUrl||t.apiUrl||G,apiKey:e.apiKey||t.apiKey,deployToken:e.deployToken||t.deployToken},n={apiUrl:o.apiUrl};return o.apiKey!==void 0&&(n.apiKey=o.apiKey),o.deployToken!==void 0&&(n.deployToken=o.deployToken),n}function Pe(e={},t){return{onProgress:t.onProgress,onProgressStats:t.onProgressStats,maxConcurrency:t.maxConcurrentDeploys,timeout:t.timeout,apiKey:t.apiKey,deployToken:t.deployToken,apiUrl:t.apiUrl,...e}}var q=b(require("mime-types"),1),C=require("@shipstatic/types");var W="/deployments",Ce="/ping",M="/aliases",Ze="/config",Ye="/account",Xe="/spa-check";function Qe(e){return typeof e=="string"?q.lookup(e)||"application/octet-stream":q.lookup(e.name)||e.type||"application/octet-stream"}async function et(e){let t=[];for await(let o of e)t.push(o);return t}var K=class{constructor(t){this.apiUrl=t.apiUrl||G,this.apiKey=t.apiKey??"",this.deployToken=t.deployToken??""}#i(t={}){let o={...t};return this.deployToken?o.Authorization=`Bearer ${this.deployToken}`:this.apiKey&&(o.Authorization=`Bearer ${this.apiKey}`),o}async#o(t,o={},n){let i=this.#i(o.headers),s={...o,headers:i,credentials:w()==="browser"?"include":"same-origin"};try{return await fetch(t,s)}catch(r){throw this.#t(r,n),r}}async#e(t,o={},n){try{let i=await this.#o(t,o,n);return i.ok||await this.#n(i,n),i.headers.get("Content-Length")==="0"||i.status===204?void 0:await i.json()}catch(i){throw i instanceof C.ShipError||this.#t(i,n),i}}async ping(){return(await this.#e(`${this.apiUrl}${Ce}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.#e(`${this.apiUrl}${Ce}`,{method:"GET"},"Ping")}async getConfig(){return await this.#e(`${this.apiUrl}${Ze}`,{method:"GET"},"Config")}async deploy(t,o={}){this.#s(t);let{apiUrl:n=this.apiUrl,signal:i,apiKey:s,deployToken:r}=o,{requestBody:a,requestHeaders:p}=await this.#r(t),c={};r?c={Authorization:`Bearer ${r}`}:s&&(c={Authorization:`Bearer ${s}`});let l={method:"POST",body:a,headers:{...p,...c},signal:i||null};return await this.#e(`${n}${W}`,l,"Deploy")}#s(t){if(!t.length)throw C.ShipError.business("No files to deploy.");for(let o of t)if(!o.md5)throw C.ShipError.file(`MD5 checksum missing for file: ${o.path}`,o.path)}async#r(t){let o,n={};if(w()==="browser")o=this.#a(t);else if(w()==="node"){let{body:i,headers:s}=await this.#l(t);o=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),n=s}else throw C.ShipError.business("Unknown or unsupported execution environment");return{requestBody:o,requestHeaders:n}}#a(t){let o=new FormData,n=[];for(let i=0;i<t.length;i++){let s=t[i],r;if(s.content instanceof File||s.content instanceof Blob)r=s.content;else throw C.ShipError.file(`Unsupported file.content type for browser FormData: ${s.path}`,s.path);let a=Qe(r instanceof File?r:s.path),p=new File([r],s.path,{type:a});o.append("files[]",p),n.push(s.md5)}return o.append("checksums",JSON.stringify(n)),o}async#l(t){let{FormData:o,File:n}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),s=await import("path"),r=new o,a=[];for(let d=0;d<t.length;d++){let h=t[d],$=q.lookup(h.path)||"application/octet-stream",v;if(Buffer.isBuffer(h.content))v=new n([h.content],h.path,{type:$});else if(typeof Blob<"u"&&h.content instanceof Blob)v=new n([h.content],h.path,{type:$});else throw C.ShipError.file(`Unsupported file.content type for Node.js FormData: ${h.path}`,h.path);let L=h.path.startsWith("/")?h.path:"/"+h.path;r.append("files[]",v,L),a.push(h.md5)}r.append("checksums",JSON.stringify(a));let p=new i(r),c=await et(p.encode()),l=Buffer.concat(c.map(d=>Buffer.from(d))),u={"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(l).toString()};return{body:l,headers:u}}async#n(t,o){let n={};try{let i=t.headers.get("content-type");i&&i.includes("application/json")?n=await t.json():n={message:await t.text()}}catch{n={message:"Failed to parse error response"}}if(n.error||n.code||n.message){let i=n.message||n.error||`${o} failed due to API error`;throw t.status===401?C.ShipError.authentication(i):C.ShipError.api(i,t.status,n.code,n)}throw t.status===401?C.ShipError.authentication(`Authentication failed for ${o}`):C.ShipError.api(`${o} failed due to API error`,t.status,void 0,n)}#t(t,o){throw t.name==="AbortError"?C.ShipError.cancelled(`${o} operation was cancelled.`):t instanceof TypeError&&t.message.includes("fetch")?C.ShipError.network(`${o} failed due to network error: ${t.message}`,t):t instanceof C.ShipError?t:C.ShipError.business(`An unexpected error occurred during ${o}: ${t.message||"Unknown error"}`)}async listDeployments(){return await this.#e(`${this.apiUrl}${W}`,{method:"GET"},"List Deployments")}async getDeployment(t){return await this.#e(`${this.apiUrl}${W}/${t}`,{method:"GET"},"Get Deployment")}async removeDeployment(t){await this.#e(`${this.apiUrl}${W}/${t}`,{method:"DELETE"},"Remove Deployment")}async setAlias(t,o){try{let n=await this.#o(`${this.apiUrl}${M}/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({deployment:o})},"Set Alias");return n.ok||await this.#n(n,"Set Alias"),{...await n.json(),isCreate:n.status===201}}catch(n){this.#t(n,"Set Alias")}}async getAlias(t){return await this.#e(`${this.apiUrl}${M}/${encodeURIComponent(t)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.#e(`${this.apiUrl}${M}`,{method:"GET"},"List Aliases")}async removeAlias(t){await this.#e(`${this.apiUrl}${M}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove Alias")}async checkAlias(t){return await this.#e(`${this.apiUrl}${M}/${encodeURIComponent(t)}/dns-check`,{method:"POST"},"Check Alias")}async getAccount(){return await this.#e(`${this.apiUrl}${Ye}`,{method:"GET"},"Get Account")}async createApiKey(){return await this.#e(`${this.apiUrl}/key`,{method:"POST"},"Create API Key")}async checkSPA(t){let o=t.find(p=>p.path==="index.html"||p.path==="/index.html");if(!o)return!1;let n=100*1024;if(o.size>n)return!1;let i;if(Buffer.isBuffer(o.content))i=o.content.toString("utf-8");else if(typeof Blob<"u"&&o.content instanceof Blob)i=await o.content.text();else if(typeof File<"u"&&o.content instanceof File)i=await o.content.text();else return!1;let r={files:t.map(p=>p.path),index:i};return(await this.#e(`${this.apiUrl}${Xe}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"SPA Check")).isSPA}};var Ne=require("@shipstatic/types");var De=require("@shipstatic/types"),re=null;function ve(e){re=e}function H(){if(re===null)throw De.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return re}var P=require("@shipstatic/types");var O=require("@shipstatic/types");async function tt(e){let t=(await import("spark-md5")).default;return new Promise((o,n)=>{let s=Math.ceil(e.size/2097152),r=0,a=new t.ArrayBuffer,p=new FileReader,c=()=>{let l=r*2097152,u=Math.min(l+2097152,e.size);p.readAsArrayBuffer(e.slice(l,u))};p.onload=l=>{let u=l.target?.result;if(!u){n(O.ShipError.business("Failed to read file chunk"));return}a.append(u),r++,r<s?c():o({md5:a.end()})},p.onerror=()=>{n(O.ShipError.business("Failed to calculate MD5: FileReader error"))},c()})}async function ot(e){let t=await import("crypto");if(Buffer.isBuffer(e)){let n=t.createHash("md5");return n.update(e),{md5:n.digest("hex")}}let o=await import("fs");return new Promise((n,i)=>{let s=t.createHash("md5"),r=o.createReadStream(e);r.on("error",a=>i(O.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 U(e){let t=w();if(t==="browser"){if(!(e instanceof Blob))throw O.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return tt(e)}if(t==="node"){if(!(Buffer.isBuffer(e)||typeof e=="string"))throw O.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return ot(e)}throw O.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var Ae=require("junk"),nt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"];function V(e){return!e||e.length===0?[]:e.filter(t=>{if(!t)return!1;let o=t.replace(/\\/g,"/").split("/").filter(Boolean);if(o.length===0)return!0;let n=o[o.length-1];if((0,Ae.isJunk)(n))return!1;let i=o.slice(0,-1);for(let s of i)if(nt.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var R=require("@shipstatic/types");function Z(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}function Y(e,t={}){if(t.flatten===!1)return e.map(n=>({path:Z(n),name:ae(n)}));let o=it(e);return e.map(n=>{let i=Z(n);if(o){let s=o.endsWith("/")?o:`${o}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=ae(n)),{path:i,name:ae(n)}})}function it(e){if(!e.length)return"";let o=e.map(s=>Z(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 ae(e){return e.split(/[/\\]/).pop()||e}var T=b(require("fs"),1),x=b(require("path"),1);function xe(e){let t=[];try{let o=T.readdirSync(e);for(let n of o){let i=x.join(e,n),s=T.statSync(i);if(s.isDirectory()){let r=xe(i);t.push(...r)}else s.isFile()&&t.push(i)}}catch(o){console.error(`Error reading directory ${e}:`,o)}return t}async function Fe(e,t={}){let o=x.resolve(e),i=(()=>{let d=T.statSync(o);return d.isFile()?[o]:d.isDirectory()?xe(o):[]})().filter(d=>{let h=x.basename(d);return V([h]).length>0}),r=T.statSync(o).isDirectory()?o:x.dirname(o),a=i.map(d=>x.relative(r,d).replace(/\\/g,"/")||x.basename(d)),p=Y(a,{flatten:t.pathDetect!==!1}),c=[],l=0;for(let d=0;d<i.length;d++){let h=i[d],$=p[d].path;try{let v=T.statSync(h);if(v.size===0){console.warn(`Skipping empty file: ${h}`);continue}let L=H();if(v.size>L.maxFileSize)throw R.ShipError.business(`File ${h} is too large. Maximum allowed size is ${L.maxFileSize/(1024*1024)}MB.`);if(l+=v.size,l>L.maxTotalSize)throw R.ShipError.business(`Total deploy size is too large. Maximum allowed is ${L.maxTotalSize/(1024*1024)}MB.`);let oe=T.readFileSync(h),{md5:Be}=await U(oe);if($.includes("\0")||$.includes("/../")||$.startsWith("../")||$.endsWith("/.."))throw R.ShipError.business(`Security error: Unsafe file path "${$}" for file: ${h}`);c.push({path:$,content:oe,size:oe.length,md5:Be})}catch(v){if(v instanceof R.ShipError&&v.isClientError&&v.isClientError())throw v;console.error(`Could not process file ${h}:`,v)}}let u=H();if(c.length>u.maxFilesCount)throw R.ShipError.business(`Too many files to deploy. Maximum allowed is ${u.maxFilesCount} files.`);return c}async function le(e,t={}){if(w()!=="node")throw R.ShipError.business("processFilesForNode can only be called in a Node.js environment.");if(e.length>1){let o=[];for(let n of e){let i=await Fe(n,t);o.push(...i)}return o}return await Fe(e[0],t)}var ce=require("@shipstatic/types");async function pe(e,t={}){if(w()!=="browser")throw ce.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let o=Array.isArray(e)?e:Array.from(e),n=o.map(l=>l.webkitRelativePath||l.name),i=Y(n,{flatten:t.pathDetect!==!1}),s=[];for(let l=0;l<o.length;l++){let u=o[l],d=i[l].path;if(d.includes("..")||d.includes("\0"))throw ce.ShipError.business(`Security error: Unsafe file path "${d}" for file: ${u.name}`);s.push({file:u,relativePath:d})}let r=s.map(l=>l.relativePath),a=V(r),p=new Set(a),c=[];for(let l of s){if(!p.has(l.relativePath)||l.file.size===0)continue;let{md5:u}=await U(l.file);c.push({content:l.file,path:l.relativePath,size:l.file.size,md5:u})}return c}function $e(e,t={}){let o=H();if(!t.skipEmptyCheck&&e.length===0)throw P.ShipError.business("No files to deploy.");if(e.length>o.maxFilesCount)throw P.ShipError.business(`Too many files to deploy. Maximum allowed is ${o.maxFilesCount}.`);let n=0;for(let i of e){if(i.size>o.maxFileSize)throw P.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 P.ShipError.business(`Total deploy size is too large. Maximum allowed is ${o.maxTotalSize/(1024*1024)}MB.`)}}function Te(e,t){if(t==="node"){if(!Array.isArray(e))throw P.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(e.length===0)throw P.ShipError.business("No files to deploy.");if(!e.every(o=>typeof o=="string"))throw P.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(t==="browser"&&e instanceof HTMLInputElement&&!e.files)throw P.ShipError.business("No files selected in HTMLInputElement")}function ke(e){return $e(e,{skipEmptyCheck:!0}),e.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),e}async function st(e,t={}){Te(e,"node");let o=await le(e,t);return ke(o)}async function rt(e,t={}){Te(e,"browser");let o;if(e instanceof HTMLInputElement)o=Array.from(e.files);else if(typeof e=="object"&&e!==null&&typeof e.length=="number"&&typeof e.item=="function")o=Array.from(e);else if(Array.isArray(e)){if(e.length>0&&typeof e[0]=="string")throw P.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");o=e}else throw P.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),$e(o);let n=await pe(o,t);return ke(n)}async function Ee(e,t={},o){let n=w();if(n!=="node"&&n!=="browser")throw P.ShipError.business("Unsupported execution environment.");let i;return n==="node"?i=await st(e,t):i=await rt(e,t),o&&(i=await lt(i,o,t)),i}async function at(){let e={rewrites:[{source:"/(.*)",destination:"/index.html"}]},t=Buffer.from(JSON.stringify(e,null,2),"utf-8"),{md5:o}=await U(t);return{path:P.DEPLOYMENT_CONFIG_FILENAME,content:t,size:t.length,md5:o}}async function lt(e,t,o){if(o.spaDetect===!1||e.some(n=>n.path===P.DEPLOYMENT_CONFIG_FILENAME))return e;try{if(await t.checkSPA(e)){let i=await at();return console.log(`SPA detected - generated ${P.DEPLOYMENT_CONFIG_FILENAME}`),[...e,i]}}catch{console.warn("SPA detection failed, continuing without auto-config")}return e}function Oe(e,t,o){return{create:async(n,i={})=>{o&&await o();let s=t?Pe(i,t):i,r=e(),a=await Ee(n,s,r);return await r.deploy(a,s)},list:async()=>(o&&await o(),e().listDeployments()),remove:async n=>{o&&await o(),await e().removeDeployment(n)},get:async n=>(o&&await o(),e().getDeployment(n))}}function Re(e,t){return{set:async(o,n)=>(t&&await t(),e().setAlias(o,n)),get:async o=>(t&&await t(),e().getAlias(o)),list:async()=>(t&&await t(),e().listAliases()),remove:async o=>{t&&await t(),await e().removeAlias(o)},check:async o=>(t&&await t(),e().checkAlias(o))}}function Ie(e,t){return{get:async()=>(t&&await t(),e().getAccount())}}function je(e,t){return{create:async()=>(t&&await t(),e().createApiKey())}}var I=require("@shipstatic/types"),X=class{constructor(t={}){this.initPromise=null;if(this.clientOptions=t,this.environment=w(),this.environment!=="node"&&this.environment!=="browser")throw Ne.ShipError.business("Unsupported execution environment.");let o=se(t,{});this.http=new K({...t,...o});let n=this.getInitCallback(),i=()=>this.http;this._deployments=Oe(i,this.clientOptions,n),this._aliases=Re(i,n),this._account=Ie(i,n),this._keys=je(i,n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.initializeConfig()),this.initPromise}getInitCallback(){return()=>this.ensureInitialized()}async initializeConfig(){try{let t=await be(this.clientOptions.configFile),o=se(this.clientOptions,t);this.http=new K({...this.clientOptions,...o});let n=await this.http.getConfig();ve(n)}catch(t){throw this.initPromise=null,t}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,o){return this.deployments.create(t,o)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get aliases(){return this._aliases}get account(){return this._account}get keys(){return this._keys}};var B=require("@shipstatic/types"),j=require("fs"),g=b(require("path"),1);var me=b(require("columnify"),1),f=require("yoctocolors"),S=(e,t,o)=>o?t:e(t),F=(e,t,o)=>{console.log(t?JSON.stringify({success:e},null,2)+`
3
3
  `:`${S(f.green,e.toLowerCase().replace(/\.$/,""),o)}
4
4
  `)},D=(e,t,o)=>{if(t)console.error(JSON.stringify({error:e},null,2)+`
5
5
  `);else{let n=S(s=>(0,f.inverse)((0,f.red)(s)),`${S(f.hidden,"[",o)}error${S(f.hidden,"]",o)}`,o),i=S(f.red,e.toLowerCase().replace(/\.$/,""),o);console.error(`${n} ${i}