@shipstatic/ship 0.9.1 → 0.9.3

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/index.d.cts CHANGED
@@ -215,8 +215,6 @@ declare class ApiHttp extends SimpleEvents {
215
215
  private createTimeoutSignal;
216
216
  private safeClone;
217
217
  private parseResponse;
218
- private handleResponseError;
219
- private handleFetchError;
220
218
  deploy(files: StaticFile[], options?: ApiDeployOptions): Promise<DeploymentCreateResponse>;
221
219
  listDeployments(): Promise<DeploymentListResponse>;
222
220
  getDeployment(id: string): Promise<Deployment>;
package/dist/index.d.ts CHANGED
@@ -215,8 +215,6 @@ declare class ApiHttp extends SimpleEvents {
215
215
  private createTimeoutSignal;
216
216
  private safeClone;
217
217
  private parseResponse;
218
- private handleResponseError;
219
- private handleFetchError;
220
218
  deploy(files: StaticFile[], options?: ApiDeployOptions): Promise<DeploymentCreateResponse>;
221
219
  listDeployments(): Promise<DeploymentListResponse>;
222
220
  getDeployment(id: string): Promise<Deployment>;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Ne=Object.defineProperty;var R=(n,t)=>()=>(n&&(t=n(n=0)),t);var Ce=(n,t)=>{for(var e in t)Ne(n,e,{get:t[e],enumerable:!0})};function b(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function $(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return Fe.has(e)}function oe(n){return Oe.test(n)}function U(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>j.has(e))}function Qe(n){if(!n.startsWith(x.PREFIX))throw a.validation(`API key must start with "${x.PREFIX}"`);if(n.length!==x.TOTAL_LENGTH)throw a.validation(`API key must be ${x.TOTAL_LENGTH} characters total (${x.PREFIX} + ${x.HEX_LENGTH} hex chars)`);let t=n.slice(x.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`API key must contain ${x.HEX_LENGTH} hexadecimal characters after "${x.PREFIX}" prefix`)}function Ze(n){if(!n.startsWith(I.PREFIX))throw a.validation(`Deploy token must start with "${I.PREFIX}"`);if(n.length!==I.TOTAL_LENGTH)throw a.validation(`Deploy token must be ${I.TOTAL_LENGTH} characters total (${I.PREFIX} + ${I.HEX_LENGTH} hex chars)`);let t=n.slice(I.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`Deploy token must contain ${I.HEX_LENGTH} hexadecimal characters after "${I.PREFIX}" prefix`)}function et(n){try{let t=new URL(n);if(!["http:","https:"].includes(t.protocol))throw a.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw a.validation("API URL must not contain a path");if(t.search||t.hash)throw a.validation("API URL must not contain query parameters or fragments")}catch(t){throw b(t)?t:a.validation("API URL must be a valid URL")}}function tt(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function le(n,t){return n.endsWith(`.${t}`)}function nt(n,t){return!le(n,t)}function it(n,t){return le(n,t)?n.slice(0,-(t.length+1)):null}function rt(n){return`https://${n}`}function st(n){return`https://${n}`}function ot(n){return!n||n.length===0?null:JSON.stringify(n)}function at(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}var Xe,We,Ye,m,V,a,Fe,Oe,j,x,I,Je,q,ae,_,g,P,pe,O,E=R(()=>{"use strict";Xe={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},We={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Ye={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},m={Validation:"validation_failed",NotFound:"not_found",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},V={client:new Set([m.Business,m.Config,m.File,m.Validation]),network:new Set([m.Network]),auth:new Set([m.Authentication])},a=class n extends Error{type;status;details;constructor(t,e,i,r){super(e),this.type=t,this.status=i,this.details=r,this.name="ShipError"}toResponse(){let t=this.type===m.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:t}}static fromResponse(t){return new n(t.error,t.message,t.status,t.details)}static validation(t,e){return new n(m.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(m.NotFound,i,404)}static rateLimit(t="Too many requests"){return new n(m.RateLimit,t,429)}static authentication(t="Authentication required",e){return new n(m.Authentication,t,401,e)}static business(t,e=400){return new n(m.Business,t,e)}static network(t,e){return new n(m.Network,t,void 0,{cause:e})}static cancelled(t){return new n(m.Cancelled,t)}static file(t,e){return new n(m.File,t,void 0,{filePath:e})}static config(t,e){return new n(m.Config,t,void 0,e)}static api(t,e=500){return new n(m.Api,t,e)}static database(t,e=500){return new n(m.Api,t,e)}static storage(t,e=500){return new n(m.Api,t,e)}get filePath(){return this.details?.filePath}isClientError(){return V.client.has(this.type)}isNetworkError(){return V.network.has(this.type)}isAuthError(){return V.auth.has(this.type)}isValidationError(){return this.type===m.Validation}isFileError(){return this.type===m.File}isConfigError(){return this.type===m.Config}isType(t){return this.type===t}};Fe=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);Oe=/[\x00-\x1f\x7f#?%\\<>"]/;j=new Set(["node_modules","package.json"]);x={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},I={PREFIX:"token-",HEX_LENGTH:64,TOTAL_LENGTH:70},Je={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},q="ship.json",ae={rewrites:[{source:"/(.*)",destination:"/index.html"}]};_="https://api.shipstatic.com",g={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};P={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},pe=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;O={MIN_LENGTH:6,MAX_LENGTH:128}});function Et(n){X=n}function $e(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function L(){return X||$e()}var X,C=R(()=>{"use strict";X=null});async function Ue(n){let t=(await import("spark-md5")).default;return new Promise((e,i)=>{let s=Math.ceil(n.size/2097152),l=0,c=new t.ArrayBuffer,o=new FileReader,p=()=>{let u=l*2097152,h=Math.min(u+2097152,n.size);o.readAsArrayBuffer(n.slice(u,h))};o.onload=u=>{let h=u.target?.result;if(!h){i(a.business("Failed to read file chunk"));return}c.append(h),l++,l<s?p():e({md5:c.end()})},o.onerror=()=>{i(a.business("Failed to calculate MD5: FileReader error"))},p()})}async function _e(n){let t=await import("crypto");if(Buffer.isBuffer(n)){let i=t.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let e=await import("fs");return new Promise((i,r)=>{let s=t.createHash("md5"),l=e.createReadStream(n);l.on("error",c=>r(a.business(`Failed to read file for MD5: ${c.message}`))),l.on("data",c=>s.update(c)),l.on("end",()=>i({md5:s.digest("hex")}))})}async function H(n){let t=L();if(t==="browser"){if(!(n instanceof Blob))throw a.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Ue(n)}if(t==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw a.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return _e(n)}throw a.business("Unknown or unsupported execution environment for MD5 calculation.")}var z=R(()=>{"use strict";C();E()});import{isJunk as ze}from"junk";function Ae(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&U(i)))throw a.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return n.filter(e=>{if(!e)return!1;let i=e.replace(/\\/g,"/").split("/").filter(Boolean);if(i.length===0)return!0;let r=i[i.length-1];if(ze(r))return!1;for(let l of i)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let s=i.slice(0,-1);for(let l of s)if(Ke.some(c=>l.toLowerCase()===c.toLowerCase()))return!1;return!0})}var Ke,Y=R(()=>{"use strict";E();Ke=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function we(n){if(!n||n.length===0)return"";let t=n.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let e=t.map(s=>s.split("/").filter(Boolean)),i=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r;s++){let l=e[0][s];if(e.every(c=>c[s]===l))i.push(l);else break}return i.join("/")}function G(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var J=R(()=>{"use strict"});function ve(n,t={}){if(t.flatten===!1)return n.map(i=>({path:G(i),name:Q(i)}));let e=Ge(n);return n.map(i=>{let r=G(i);if(e){let s=e.endsWith("/")?e:`${e}/`;r.startsWith(s)&&(r=r.substring(s.length))}return r||(r=Q(i)),{path:r,name:Q(i)}})}function Ge(n){if(!n.length)return"";let e=n.map(s=>G(s)).map(s=>s.split("/")),i=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r-1;s++){let l=e[0][s];if(e.every(c=>c[s]===l))i.push(l);else break}return i.join("/")}function Q(n){return n.split(/[/\\]/).pop()||n}var Z=R(()=>{"use strict";J()});function ee(n,t=1){if(n===0)return"0 Bytes";let e=1024,i=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,r)).toFixed(t))+" "+i[r]}function te(n){if(oe(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,e=n.split("/").pop()||n;return t.test(e)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function Zt(n,t){let e=[],i=[],r=[];if(n.length===0){let o={file:"(no files)",message:"At least one file must be provided"};return e.push(o),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let o of n)if(U(o.name))return e.push({file:o.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(p=>({...p,status:g.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let o={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(o),{files:n.map(p=>({...p,status:g.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let o of n){let p=g.READY,u="Ready for upload",h=o.name?te(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===g.PROCESSING_ERROR)p=g.VALIDATION_FAILED,u=o.statusMessage||"File failed during processing",e.push({file:o.name,message:u});else if(o.size===0){p=g.EXCLUDED,u="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:u}),r.push({...o,status:p,statusMessage:u});continue}else o.size<0?(p=g.VALIDATION_FAILED,u="File size must be positive",e.push({file:o.name,message:u})):!o.name||o.name.trim().length===0?(p=g.VALIDATION_FAILED,u="File name cannot be empty",e.push({file:o.name||"(empty)",message:u})):o.name.includes("\0")?(p=g.VALIDATION_FAILED,u="File name contains invalid characters (null byte)",e.push({file:o.name,message:u})):h.valid?$(o.name)?(p=g.VALIDATION_FAILED,u=`File extension not allowed: "${o.name}"`,e.push({file:o.name,message:u})):o.size>t.maxFileSize?(p=g.VALIDATION_FAILED,u=`File size (${ee(o.size)}) exceeds limit of ${ee(t.maxFileSize)}`,e.push({file:o.name,message:u})):(s+=o.size,s>t.maxTotalSize&&(p=g.VALIDATION_FAILED,u=`Total size would exceed limit of ${ee(t.maxTotalSize)}`,e.push({file:o.name,message:u}))):(p=g.VALIDATION_FAILED,u=h.reason||"Invalid file name",e.push({file:o.name,message:u}));r.push({...o,status:p,statusMessage:u})}e.length>0&&(r=r.map(o=>o.status===g.EXCLUDED?o:{...o,status:g.VALIDATION_FAILED,statusMessage:o.status===g.VALIDATION_FAILED?o.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=e.length===0?r.filter(o=>o.status===g.READY):[],c=e.length===0;return{files:r,validFiles:l,errors:e,warnings:i,canDeploy:c}}function Ve(n){return n.filter(t=>t.status===g.READY)}function en(n){return Ve(n).length>0}var ne=R(()=>{"use strict";E()});function Re(n,t){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw a.business(`Security error: Unsafe file path "${n}" for file: ${t}`)}function xe(n,t){let e=te(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if($(n))throw a.business(`File extension not allowed: "${t}"`)}var ie=R(()=>{"use strict";E();ne()});var Pe={};Ce(Pe,{processFilesForNode:()=>be});import*as S from"fs";import*as T from"path";function Ie(n,t=new Set){let e=[],i=S.realpathSync(n);if(t.has(i))return e;t.add(i);let r=S.readdirSync(n);for(let s of r){let l=T.join(n,s),c=S.statSync(l);if(c.isDirectory()){let o=Ie(l,t);e.push(...o)}else c.isFile()&&e.push(l)}return e}async function be(n,t={},e){if(L()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let d of n){let y=T.resolve(d);try{if(S.statSync(y).isDirectory()){let A=S.readdirSync(y).find(w=>j.has(w));if(A)throw a.business(`"${A}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(A){if(b(A))throw A}}let i=n.flatMap(d=>{let y=T.resolve(d);try{return S.statSync(y).isDirectory()?Ie(y):[y]}catch{throw a.file(`Path does not exist: ${d}`,d)}}),r=[...new Set(i)],s=n.map(d=>T.resolve(d)),l=we(s.map(d=>{try{return S.statSync(d).isDirectory()?d:T.dirname(d)}catch{return T.dirname(d)}})),c=r.map(d=>{if(l&&l.length>0){let y=T.relative(l,d);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return T.basename(d)}),p=ve(c,{flatten:t.pathDetect!==!1}).map(d=>d.path),u=new Set(Ae(p));if(u.size===0)return[];let h=[],N=[];for(let d=0;d<r.length;d++)u.has(p[d])&&(h.push(r[d]),N.push(p[d]));let v=[],D=0;if(!e)throw a.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let d=0;d<h.length;d++){let y=h[d],A=N[d];try{Re(A,y);let w=S.statSync(y);if(w.size===0)continue;if(xe(A,y),w.size>e.maxFileSize)throw a.business(`File ${y} is too large. Maximum allowed size is ${e.maxFileSize/(1024*1024)}MB.`);if(D+=w.size,D>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let F=S.readFileSync(y),{md5:Le}=await H(F);v.push({path:A,content:F,size:F.length,md5:Le})}catch(w){if(b(w))throw w;let F=w instanceof Error?w.message:String(w);throw a.file(`Failed to read file "${y}": ${F}`,y)}}if(v.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return v}var re=R(()=>{"use strict";C();z();Y();ie();E();Z();J()});E();E();var M=class{constructor(){this.handlers=new Map}on(t,e){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e)}off(t,e){let i=this.handlers.get(t);i&&(i.delete(e),i.size===0&&this.handlers.delete(t))}emit(t,...e){let i=this.handlers.get(t);if(!i)return;let r=Array.from(i);for(let s of r)try{s(...e)}catch(l){i.delete(s),t!=="error"&&setTimeout(()=>{let c=l instanceof Error?l:new Error(String(l));this.emit("error",c,String(t))},0)}}};E();function ce(n){if(n!=null){if(typeof n!="string")throw a.validation("Password must be a string");if(n.length<O.MIN_LENGTH||n.length>O.MAX_LENGTH)throw a.validation(`Password must be between ${O.MIN_LENGTH} and ${O.MAX_LENGTH} characters`)}}function k(n){if(n==null)return;if(n.length===0)return n;if(n.length>P.MAX_COUNT)throw a.validation(`Maximum ${P.MAX_COUNT} labels allowed`);let t=n.map((i,r)=>{if(typeof i!="string")throw a.validation(`Label at index ${r} must be a string`);let s=i.trim().toLowerCase();if(s.length<P.MIN_LENGTH)throw a.validation(`Labels must be at least ${P.MIN_LENGTH} characters long`);if(s.length>P.MAX_LENGTH)throw a.validation(`Labels must be no more than ${P.MAX_LENGTH} characters long`);if(!pe.test(s))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${P.SEPARATORS}) between segments`);return s}),e=[...new Set(t)];if(e.length!==t.length)throw a.validation("Duplicate labels are not allowed");return e}var f={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},ke=3e4,B=class extends M{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||_,this.getAuthHeadersCallback=e.getAuthHeaders,this.useCredentials=e.useCredentials??!1,this.timeout=e.timeout??ke,this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||f.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}async executeRequest(e,i,r){let s=this.mergeHeaders(i.headers),{signal:l,cleanup:c}=this.createTimeoutSignal(i.signal),o={...i,headers:s,credentials:this.useCredentials&&!s.Authorization?"include":void 0,signal:l};this.emit("request",e,o);try{let p=await fetch(e,o);return c(),p.ok||await this.handleResponseError(p,r),this.emit("response",this.safeClone(p),e),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(p){c();let u=p instanceof Error?p:new Error(String(p));this.emit("error",u,e),this.handleFetchError(p,r)}}async request(e,i,r){let{data:s}=await this.executeRequest(e,i,r);return s}async requestWithStatus(e,i,r){return this.executeRequest(e,i,r)}mergeHeaders(e={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...e}}createTimeoutSignal(e){let i=new AbortController,r=setTimeout(()=>i.abort(),this.timeout);if(e){let s=()=>i.abort();e.addEventListener("abort",s),e.aborted&&i.abort()}return{signal:i.signal,cleanup:()=>clearTimeout(r)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,i){let r={};try{if(e.headers.get("content-type")?.includes("application/json")){let c=await e.json();if(c&&typeof c=="object"){let o=c;typeof o.message=="string"&&(r.message=o.message),typeof o.error=="string"&&(r.error=o.error)}}else r={message:await e.text()}}catch{r={message:"Failed to parse error response"}}let s=r.message||r.error||`${i} failed`;throw e.status===401?a.authentication(s):e.status===429?a.rateLimit(s):a.api(s,e.status)}handleFetchError(e,i){throw b(e)?e:e instanceof Error&&e.name==="AbortError"?a.cancelled(`${i} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?a.network(`${i} failed: ${e.message}`,e):e instanceof Error?a.business(`${i} failed: ${e.message}`):a.business(`${i} failed: Unknown error`)}async deploy(e,i={}){if(!e.length)throw a.business("No files to deploy");for(let p of e)if(!p.md5)throw a.file(`MD5 checksum missing for file: ${p.path}`,p.path);ce(i.password);let r=k(i.labels),s=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:l,headers:c}=await this.createDeployBody(e,{labels:r,via:i.via,password:i.password,flags:s}),o={};return i.deployToken?o.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(o.Authorization=`Bearer ${i.apiKey}`),i.caller&&(o["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:l,headers:{...c,...o},signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){let r=k(i);return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:r})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,r){let s=k(r),l={};i&&(l.deployment=i),s!==void 0&&(l.labels=s);let{data:c,status:o}=await this.requestWithStatus(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)},"Set domain");return{...c,isCreate:o===201}}async listDomains(){return this.request(`${this.apiUrl}${f.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,i){let r=k(i),s={};return e!==void 0&&(s.ttl=e),r!==void 0&&(s.labels=r),this.request(`${this.apiUrl}${f.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${f.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${f.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async fetchAgentToken(){return this.request(`${this.apiUrl}${f.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent token")}async getAccount(){return this.request(`${this.apiUrl}${f.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${f.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return(await this.request(`${this.apiUrl}${f.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e,i={}){let r=e.find(p=>p.path==="index.html"||p.path==="/index.html");if(!r||r.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(r.content))s=r.content.toString("utf-8");else if(typeof Blob<"u"&&r.content instanceof Blob)s=await r.content.text();else if(typeof File<"u"&&r.content instanceof File)s=await r.content.text();else return!1;let l={"Content-Type":"application/json"};i.deployToken?l.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(l.Authorization=`Bearer ${i.apiKey}`);let c={files:e.map(p=>p.path),index:s};return(await this.request(`${this.apiUrl}${f.SPA_CHECK}`,{method:"POST",headers:l,body:JSON.stringify(c)},"SPA check")).isSPA}};E();function ue(n={}){let t={apiUrl:n.apiUrl||_};return n.apiKey!==void 0&&(t.apiKey=n.apiKey),n.deployToken!==void 0&&(t.deployToken=n.deployToken),t}function de(n,t){let e={...n};return e.apiUrl===void 0&&t.apiUrl!==void 0&&(e.apiUrl=t.apiUrl),e.apiKey===void 0&&t.apiKey!==void 0&&(e.apiKey=t.apiKey),e.deployToken===void 0&&t.deployToken!==void 0&&(e.deployToken=t.deployToken),e.timeout===void 0&&t.timeout!==void 0&&(e.timeout=t.timeout),e.maxConcurrency===void 0&&t.maxConcurrency!==void 0&&(e.maxConcurrency=t.maxConcurrency),e.onProgress===void 0&&t.onProgress!==void 0&&(e.onProgress=t.onProgress),e.caller===void 0&&t.caller!==void 0&&(e.caller=t.caller),e}E();E();z();async function Me(){let n=JSON.stringify(ae,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await H(t);return{path:q,content:t,size:n.length,md5:e}}async function me(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===q))return n;try{if(await t.checkSPA(n,e)){let r=await Me();return[...n,r]}}catch{}return n}function fe(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:r,hasAuth:s}=n;return{upload:async(l,c={})=>{await e();let o=r?de(c,r):c;if(s&&!s()&&!o.deployToken&&!o.apiKey)try{let h=t(),{secret:N}=await h.fetchAgentToken();o.deployToken=N}catch(h){throw b(h)&&h.type===m.RateLimit?a.rateLimit("public deploy rate limit exceeded, try again later or run 'ship config' for a free account with higher limits"):h}if(!i)throw a.config("processInput function is not provided.");let p=t(),u=await i(l,o);return u=await me(u,p,o),p.deploy(u,o)},list:async()=>(await e(),t().listDeployments()),get:async l=>(await e(),t().getDeployment(l)),set:async(l,c)=>(await e(),t().updateDeploymentLabels(l,c.labels)),remove:async l=>{await e(),await t().removeDeployment(l)}}}function he(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,r={})=>(await e(),t().setDomain(i,r.deployment,r.labels)),list:async()=>(await e(),t().listDomains()),get:async i=>(await e(),t().getDomain(i)),remove:async i=>{await e(),await t().removeDomain(i)},verify:async i=>(await e(),t().verifyDomain(i)),validate:async i=>(await e(),t().validateDomain(i)),dns:async i=>(await e(),t().getDomainDns(i)),records:async i=>(await e(),t().getDomainRecords(i)),share:async i=>(await e(),t().getDomainShare(i))}}function ye(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function ge(n){let{getApi:t,ensureInit:e}=n;return{create:async(i={})=>(await e(),t().createToken(i.ttl,i.labels)),list:async()=>(await e(),t().listTokens()),remove:async i=>{await e(),await t().removeToken(i)}}}var K=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.auth=null;t={...t,apiUrl:t.apiUrl||void 0,apiKey:t.apiKey||void 0,deployToken:t.deployToken||void 0},this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.http=new B({...t,...ue(t),getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=fe({...e,processInput:(i,r)=>this.processInput(i,r),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this.domains=he(e),this.account=ye(e),this.tokens=ge(e)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(t){throw this.initPromise=null,t}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,e){return this.deployments.upload(t,e)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setDeployToken(t){if(!t||typeof t!="string")throw a.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:t}}setApiKey(t){if(!t||typeof t!="string")throw a.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:t}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};E();C();E();C();import{z as De}from"zod";import{z as W}from"zod";var Ee={apiUrl:W.string().url().optional(),apiKey:W.string().min(1).optional(),deployToken:W.string().min(1).optional()};var Be=De.object(Ee).strict(),He={apiUrl:"SHIP_API_URL",apiKey:"SHIP_API_KEY",deployToken:"SHIP_DEPLOY_TOKEN"};function Se(){if(L()!=="node")return{};let n={apiUrl:process.env.SHIP_API_URL||void 0,apiKey:process.env.SHIP_API_KEY||void 0,deployToken:process.env.SHIP_DEPLOY_TOKEN||void 0};try{return Be.parse(n)}catch(t){if(t instanceof De.ZodError){let e=t.issues[0],i=e.path[0],r=(i&&He[i])??"SHIP environment configuration";throw a.config(`Invalid ${r}: ${e.message}`)}throw a.config("Invalid environment configuration")}}E();async function Te(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),{labels:s,via:l,password:c,flags:o}=t,p=new e,u=[];for(let D of n){if(!Buffer.isBuffer(D.content)&&!(typeof Blob<"u"&&D.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${D.path}`,D.path);if(!D.md5)throw a.file(`File missing md5 checksum: ${D.path}`,D.path);let d=new i([D.content],D.path,{type:"application/octet-stream"});p.append("files[]",d),u.push(D.md5)}p.append("checksums",JSON.stringify(u)),s&&s.length>0&&p.append("labels",JSON.stringify(s)),l&&p.append("via",l),c&&p.append("password",c),o?.build&&p.append("build","true"),o?.prerender&&p.append("prerender","true"),o?.spa&&p.append("spa","true");let h=new r(p),N=[];for await(let D of h.encode())N.push(Buffer.from(D));let v=Buffer.concat(N);return{body:v.buffer.slice(v.byteOffset,v.byteOffset+v.byteLength),headers:{"Content-Type":h.contentType,"Content-Length":Buffer.byteLength(v).toString()}}}z();function Gt(n,t,e,i=!0){let r=n===1?t:e;return i?`${n} ${r}`:r}Y();Z();C();ne();ie();E();re();var se=class extends K{constructor(t={}){if(L()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=Se();super({...t,apiUrl:t.apiUrl||e.apiUrl,apiKey:t.apiKey||e.apiKey,deployToken:t.deployToken||e.deployToken})}async deploy(t,e){return super.deploy(t,e)}async processInput(t,e){let i=typeof t=="string"?[t]:t;if(!Array.isArray(i)||!i.every(s=>typeof s=="string"))throw a.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw a.business("No files to deploy.");let{processFilesForNode:r}=await Promise.resolve().then(()=>(re(),Pe));return r(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return Te}},je=se;export{x as API_KEY,Ye as AccountPlan,B as ApiHttp,Je as AuthMethod,Fe as BLOCKED_EXTENSIONS,_ as DEFAULT_API,q as DEPLOYMENT_CONFIG_FILENAME,I as DEPLOY_TOKEN,Xe as DeploymentStatus,We as DomainStatus,m as ErrorType,g as FILE_VALIDATION_STATUS,g as FileValidationStatus,Ke as JUNK_DIRECTORIES,P as LABEL_CONSTRAINTS,pe as LABEL_PATTERN,O as PASSWORD_CONSTRAINTS,ae as SPA_DEFAULT_CONFIG,se as Ship,a as ShipError,j as UNBUILT_PROJECT_MARKERS,Oe as UNSAFE_FILENAME_CHARS,Et as __setTestEnvironment,en as allValidFilesReady,H as calculateMD5,ye as createAccountResource,fe as createDeploymentResource,he as createDomainResource,ge as createTokenResource,je as default,at as deserializeLabels,it as extractSubdomain,Ae as filterJunk,ee as formatFileSize,rt as generateDeploymentUrl,st as generateDomainUrl,L as getENV,Ve as getValidFiles,U as hasUnbuiltMarker,oe as hasUnsafeChars,$ as isBlockedExtension,nt as isCustomDomain,tt as isDeployment,le as isPlatformDomain,b as isShipError,de as mergeDeployOptions,ve as optimizeDeployPaths,Gt as pluralize,be as processFilesForNode,ue as resolveConfig,ot as serializeLabels,Qe as validateApiKey,et as validateApiUrl,xe as validateDeployFile,Re as validateDeployPath,Ze as validateDeployToken,te as validateFileName,Zt as validateFiles};
1
+ var Ne=Object.defineProperty;var v=(n,t)=>()=>(n&&(t=n(n=0)),t);var Ce=(n,t)=>{for(var e in t)Ne(n,e,{get:t[e],enumerable:!0})};function N(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function $(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return Oe.has(e)}function oe(n){return ke.test(n)}function U(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>j.has(e))}function Ze(n){if(!n.startsWith(x.PREFIX))throw a.validation(`API key must start with "${x.PREFIX}"`);if(n.length!==x.TOTAL_LENGTH)throw a.validation(`API key must be ${x.TOTAL_LENGTH} characters total (${x.PREFIX} + ${x.HEX_LENGTH} hex chars)`);let t=n.slice(x.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`API key must contain ${x.HEX_LENGTH} hexadecimal characters after "${x.PREFIX}" prefix`)}function et(n){if(!n.startsWith(I.PREFIX))throw a.validation(`Deploy token must start with "${I.PREFIX}"`);if(n.length!==I.TOTAL_LENGTH)throw a.validation(`Deploy token must be ${I.TOTAL_LENGTH} characters total (${I.PREFIX} + ${I.HEX_LENGTH} hex chars)`);let t=n.slice(I.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`Deploy token must contain ${I.HEX_LENGTH} hexadecimal characters after "${I.PREFIX}" prefix`)}function tt(n){try{let t=new URL(n);if(!["http:","https:"].includes(t.protocol))throw a.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw a.validation("API URL must not contain a path");if(t.search||t.hash)throw a.validation("API URL must not contain query parameters or fragments")}catch(t){throw N(t)?t:a.validation("API URL must be a valid URL")}}function nt(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function le(n,t){return n.endsWith(`.${t}`)}function it(n,t){return!le(n,t)}function rt(n,t){return le(n,t)?n.slice(0,-(t.length+1)):null}function st(n){return`https://${n}`}function ot(n){return`https://${n}`}function at(n){return!n||n.length===0?null:JSON.stringify(n)}function lt(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}var Ye,We,Je,d,V,Fe,a,Oe,ke,j,x,I,Qe,q,ae,_,g,P,pe,O,E=v(()=>{"use strict";Ye={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},We={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Je={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},d={Validation:"validation_failed",NotFound:"not_found",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},V={client:new Set([d.Business,d.Config,d.File,d.Validation]),network:new Set([d.Network]),auth:new Set([d.Authentication])},Fe=new Set(Object.values(d).filter(n=>n!==d.Network&&n!==d.Cancelled)),a=class n extends Error{type;status;details;constructor(t,e,i,r){super(e),this.type=t,this.status=i,this.details=r,this.name="ShipError"}toResponse(){let t=this.type===d.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:t}}static async fromHttpResponse(t,e){let i,r,s;try{if(t.headers.get("content-type")?.includes("application/json")){let o=await t.json();if(o&&typeof o=="object"){let l=o;typeof l.message=="string"?i=l.message:typeof l.error=="string"&&(i=l.error),r=l.details,typeof l.error=="string"&&Fe.has(l.error)&&(s=l.error)}}else{let o=await t.text();o&&(i=o)}}catch{}i=i||e||`Request failed with status ${t.status}`;let p=s??(t.status===401?d.Authentication:t.status===429?d.RateLimit:d.Api);return new n(p,i,t.status,r)}static fromFetchError(t,e){if(N(t))return t;let i=e||"Request";return t instanceof Error?t.name==="AbortError"?n.cancelled(`${i} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?n.network(`${i} failed: ${t.message}`,t):new n(d.Api,`${i} failed: ${t.message}`):new n(d.Api,`${i} failed: Unknown error`)}static validation(t,e){return new n(d.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(d.NotFound,i,404)}static rateLimit(t="Too many requests"){return new n(d.RateLimit,t,429)}static authentication(t="Authentication required",e){return new n(d.Authentication,t,401,e)}static business(t,e=400){return new n(d.Business,t,e)}static network(t,e){return new n(d.Network,t,void 0,{cause:e})}static cancelled(t){return new n(d.Cancelled,t)}static file(t,e){return new n(d.File,t,void 0,{filePath:e})}static config(t,e){return new n(d.Config,t,void 0,e)}static api(t,e=500){return new n(d.Api,t,e)}get filePath(){return this.details?.filePath}isClientError(){return V.client.has(this.type)}isNetworkError(){return V.network.has(this.type)}isAuthError(){return V.auth.has(this.type)}isValidationError(){return this.type===d.Validation}isFileError(){return this.type===d.File}isConfigError(){return this.type===d.Config}isType(t){return this.type===t}};Oe=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);ke=/[\x00-\x1f\x7f#?%\\<>"]/;j=new Set(["node_modules","package.json"]);x={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},I={PREFIX:"token-",HEX_LENGTH:64,TOTAL_LENGTH:70},Qe={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},q="ship.json",ae={rewrites:[{source:"/(.*)",destination:"/index.html"}]};_="https://api.shipstatic.com",g={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};P={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},pe=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;O={MIN_LENGTH:6,MAX_LENGTH:128}});function Dt(n){X=n}function Ue(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function b(){return X||Ue()}var X,C=v(()=>{"use strict";X=null});async function _e(n){let t=(await import("spark-md5")).default;return new Promise((e,i)=>{let s=Math.ceil(n.size/2097152),p=0,c=new t.ArrayBuffer,o=new FileReader,l=()=>{let u=p*2097152,h=Math.min(u+2097152,n.size);o.readAsArrayBuffer(n.slice(u,h))};o.onload=u=>{let h=u.target?.result;if(!h){i(a.business("Failed to read file chunk"));return}c.append(h),p++,p<s?l():e({md5:c.end()})},o.onerror=()=>{i(a.business("Failed to calculate MD5: FileReader error"))},l()})}async function Me(n){let t=await import("crypto");if(Buffer.isBuffer(n)){let i=t.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let e=await import("fs");return new Promise((i,r)=>{let s=t.createHash("md5"),p=e.createReadStream(n);p.on("error",c=>r(a.business(`Failed to read file for MD5: ${c.message}`))),p.on("data",c=>s.update(c)),p.on("end",()=>i({md5:s.digest("hex")}))})}async function H(n){let t=b();if(t==="browser"){if(!(n instanceof Blob))throw a.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return _e(n)}if(t==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw a.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Me(n)}throw a.business("Unknown or unsupported execution environment for MD5 calculation.")}var z=v(()=>{"use strict";C();E()});import{isJunk as Ke}from"junk";function Ae(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&U(i)))throw a.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return n.filter(e=>{if(!e)return!1;let i=e.replace(/\\/g,"/").split("/").filter(Boolean);if(i.length===0)return!0;let r=i[i.length-1];if(Ke(r))return!1;for(let p of i)if(p!==".well-known"&&(p.startsWith(".")||p.length>255))return!1;let s=i.slice(0,-1);for(let p of s)if(Ge.some(c=>p.toLowerCase()===c.toLowerCase()))return!1;return!0})}var Ge,W=v(()=>{"use strict";E();Ge=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function we(n){if(!n||n.length===0)return"";let t=n.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let e=t.map(s=>s.split("/").filter(Boolean)),i=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r;s++){let p=e[0][s];if(e.every(c=>c[s]===p))i.push(p);else break}return i.join("/")}function G(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var J=v(()=>{"use strict"});function Re(n,t={}){if(t.flatten===!1)return n.map(i=>({path:G(i),name:Q(i)}));let e=Ve(n);return n.map(i=>{let r=G(i);if(e){let s=e.endsWith("/")?e:`${e}/`;r.startsWith(s)&&(r=r.substring(s.length))}return r||(r=Q(i)),{path:r,name:Q(i)}})}function Ve(n){if(!n.length)return"";let e=n.map(s=>G(s)).map(s=>s.split("/")),i=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r-1;s++){let p=e[0][s];if(e.every(c=>c[s]===p))i.push(p);else break}return i.join("/")}function Q(n){return n.split(/[/\\]/).pop()||n}var Z=v(()=>{"use strict";J()});function ee(n,t=1){if(n===0)return"0 Bytes";let e=1024,i=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,r)).toFixed(t))+" "+i[r]}function te(n){if(oe(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,e=n.split("/").pop()||n;return t.test(e)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function en(n,t){let e=[],i=[],r=[];if(n.length===0){let o={file:"(no files)",message:"At least one file must be provided"};return e.push(o),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let o of n)if(U(o.name))return e.push({file:o.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(l=>({...l,status:g.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let o={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(o),{files:n.map(l=>({...l,status:g.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let o of n){let l=g.READY,u="Ready for upload",h=o.name?te(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===g.PROCESSING_ERROR)l=g.VALIDATION_FAILED,u=o.statusMessage||"File failed during processing",e.push({file:o.name,message:u});else if(o.size===0){l=g.EXCLUDED,u="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:u}),r.push({...o,status:l,statusMessage:u});continue}else o.size<0?(l=g.VALIDATION_FAILED,u="File size must be positive",e.push({file:o.name,message:u})):!o.name||o.name.trim().length===0?(l=g.VALIDATION_FAILED,u="File name cannot be empty",e.push({file:o.name||"(empty)",message:u})):o.name.includes("\0")?(l=g.VALIDATION_FAILED,u="File name contains invalid characters (null byte)",e.push({file:o.name,message:u})):h.valid?$(o.name)?(l=g.VALIDATION_FAILED,u=`File extension not allowed: "${o.name}"`,e.push({file:o.name,message:u})):o.size>t.maxFileSize?(l=g.VALIDATION_FAILED,u=`File size (${ee(o.size)}) exceeds limit of ${ee(t.maxFileSize)}`,e.push({file:o.name,message:u})):(s+=o.size,s>t.maxTotalSize&&(l=g.VALIDATION_FAILED,u=`Total size would exceed limit of ${ee(t.maxTotalSize)}`,e.push({file:o.name,message:u}))):(l=g.VALIDATION_FAILED,u=h.reason||"Invalid file name",e.push({file:o.name,message:u}));r.push({...o,status:l,statusMessage:u})}e.length>0&&(r=r.map(o=>o.status===g.EXCLUDED?o:{...o,status:g.VALIDATION_FAILED,statusMessage:o.status===g.VALIDATION_FAILED?o.statusMessage:"Deployment failed due to validation errors in bundle"}));let p=e.length===0?r.filter(o=>o.status===g.READY):[],c=e.length===0;return{files:r,validFiles:p,errors:e,warnings:i,canDeploy:c}}function je(n){return n.filter(t=>t.status===g.READY)}function tn(n){return je(n).length>0}var ne=v(()=>{"use strict";E()});function ve(n,t){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw a.business(`Security error: Unsafe file path "${n}" for file: ${t}`)}function xe(n,t){let e=te(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if($(n))throw a.business(`File extension not allowed: "${t}"`)}var ie=v(()=>{"use strict";E();ne()});var be={};Ce(be,{processFilesForNode:()=>Pe});import*as S from"fs";import*as T from"path";function Ie(n,t=new Set){let e=[],i=S.realpathSync(n);if(t.has(i))return e;t.add(i);let r=S.readdirSync(n);for(let s of r){let p=T.join(n,s),c=S.statSync(p);if(c.isDirectory()){let o=Ie(p,t);e.push(...o)}else c.isFile()&&e.push(p)}return e}async function Pe(n,t={},e){if(b()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let m of n){let y=T.resolve(m);try{if(S.statSync(y).isDirectory()){let A=S.readdirSync(y).find(w=>j.has(w));if(A)throw a.business(`"${A}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(A){if(N(A))throw A}}let i=n.flatMap(m=>{let y=T.resolve(m);try{return S.statSync(y).isDirectory()?Ie(y):[y]}catch{throw a.file(`Path does not exist: ${m}`,m)}}),r=[...new Set(i)],s=n.map(m=>T.resolve(m)),p=we(s.map(m=>{try{return S.statSync(m).isDirectory()?m:T.dirname(m)}catch{return T.dirname(m)}})),c=r.map(m=>{if(p&&p.length>0){let y=T.relative(p,m);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return T.basename(m)}),l=Re(c,{flatten:t.pathDetect!==!1}).map(m=>m.path),u=new Set(Ae(l));if(u.size===0)return[];let h=[],L=[];for(let m=0;m<r.length;m++)u.has(l[m])&&(h.push(r[m]),L.push(l[m]));let R=[],D=0;if(!e)throw a.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let m=0;m<h.length;m++){let y=h[m],A=L[m];try{ve(A,y);let w=S.statSync(y);if(w.size===0)continue;if(xe(A,y),w.size>e.maxFileSize)throw a.business(`File ${y} is too large. Maximum allowed size is ${e.maxFileSize/(1024*1024)}MB.`);if(D+=w.size,D>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let F=S.readFileSync(y),{md5:Le}=await H(F);R.push({path:A,content:F,size:F.length,md5:Le})}catch(w){if(N(w))throw w;let F=w instanceof Error?w.message:String(w);throw a.file(`Failed to read file "${y}": ${F}`,y)}}if(R.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return R}var re=v(()=>{"use strict";C();z();W();ie();E();Z();J()});E();E();var M=class{constructor(){this.handlers=new Map}on(t,e){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e)}off(t,e){let i=this.handlers.get(t);i&&(i.delete(e),i.size===0&&this.handlers.delete(t))}emit(t,...e){let i=this.handlers.get(t);if(!i)return;let r=Array.from(i);for(let s of r)try{s(...e)}catch(p){i.delete(s),t!=="error"&&setTimeout(()=>{let c=p instanceof Error?p:new Error(String(p));this.emit("error",c,String(t))},0)}}};E();function ce(n){if(n!=null){if(typeof n!="string")throw a.validation("Password must be a string");if(n.length<O.MIN_LENGTH||n.length>O.MAX_LENGTH)throw a.validation(`Password must be between ${O.MIN_LENGTH} and ${O.MAX_LENGTH} characters`)}}function k(n){if(n==null)return;if(n.length===0)return n;if(n.length>P.MAX_COUNT)throw a.validation(`Maximum ${P.MAX_COUNT} labels allowed`);let t=n.map((i,r)=>{if(typeof i!="string")throw a.validation(`Label at index ${r} must be a string`);let s=i.trim().toLowerCase();if(s.length<P.MIN_LENGTH)throw a.validation(`Labels must be at least ${P.MIN_LENGTH} characters long`);if(s.length>P.MAX_LENGTH)throw a.validation(`Labels must be no more than ${P.MAX_LENGTH} characters long`);if(!pe.test(s))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${P.SEPARATORS}) between segments`);return s}),e=[...new Set(t)];if(e.length!==t.length)throw a.validation("Duplicate labels are not allowed");return e}var f={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},$e=3e4,B=class extends M{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||_,this.getAuthHeadersCallback=e.getAuthHeaders,this.useCredentials=e.useCredentials??!1,this.timeout=e.timeout??$e,this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||f.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}async executeRequest(e,i,r){let s=this.mergeHeaders(i.headers),{signal:p,cleanup:c}=this.createTimeoutSignal(i.signal),o={...i,headers:s,credentials:this.useCredentials&&!s.Authorization?"include":void 0,signal:p};this.emit("request",e,o);try{let l=await fetch(e,o);if(c(),!l.ok)throw await a.fromHttpResponse(l,`${r} failed`);return this.emit("response",this.safeClone(l),e),{data:await this.parseResponse(this.safeClone(l)),status:l.status}}catch(l){c();let u=a.fromFetchError(l,r);throw this.emit("error",u,e),u}}async request(e,i,r){let{data:s}=await this.executeRequest(e,i,r);return s}async requestWithStatus(e,i,r){return this.executeRequest(e,i,r)}mergeHeaders(e={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...e}}createTimeoutSignal(e){let i=new AbortController,r=setTimeout(()=>i.abort(),this.timeout);if(e){let s=()=>i.abort();e.addEventListener("abort",s),e.aborted&&i.abort()}return{signal:i.signal,cleanup:()=>clearTimeout(r)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async deploy(e,i={}){if(!e.length)throw a.business("No files to deploy");for(let l of e)if(!l.md5)throw a.file(`MD5 checksum missing for file: ${l.path}`,l.path);ce(i.password);let r=k(i.labels),s=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:p,headers:c}=await this.createDeployBody(e,{labels:r,via:i.via,password:i.password,flags:s}),o={};return i.deployToken?o.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(o.Authorization=`Bearer ${i.apiKey}`),i.caller&&(o["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:p,headers:{...c,...o},signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){let r=k(i);return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:r})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,r){let s=k(r),p={};i&&(p.deployment=i),s!==void 0&&(p.labels=s);let{data:c,status:o}=await this.requestWithStatus(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)},"Set domain");return{...c,isCreate:o===201}}async listDomains(){return this.request(`${this.apiUrl}${f.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,i){let r=k(i),s={};return e!==void 0&&(s.ttl=e),r!==void 0&&(s.labels=r),this.request(`${this.apiUrl}${f.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${f.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${f.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async fetchAgentToken(){return this.request(`${this.apiUrl}${f.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent token")}async getAccount(){return this.request(`${this.apiUrl}${f.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${f.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return(await this.request(`${this.apiUrl}${f.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e,i={}){let r=e.find(l=>l.path==="index.html"||l.path==="/index.html");if(!r||r.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(r.content))s=r.content.toString("utf-8");else if(typeof Blob<"u"&&r.content instanceof Blob)s=await r.content.text();else if(typeof File<"u"&&r.content instanceof File)s=await r.content.text();else return!1;let p={"Content-Type":"application/json"};i.deployToken?p.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(p.Authorization=`Bearer ${i.apiKey}`);let c={files:e.map(l=>l.path),index:s};return(await this.request(`${this.apiUrl}${f.SPA_CHECK}`,{method:"POST",headers:p,body:JSON.stringify(c)},"SPA check")).isSPA}};E();function ue(n={}){let t={apiUrl:n.apiUrl||_};return n.apiKey!==void 0&&(t.apiKey=n.apiKey),n.deployToken!==void 0&&(t.deployToken=n.deployToken),t}function de(n,t){let e={...n};return e.apiUrl===void 0&&t.apiUrl!==void 0&&(e.apiUrl=t.apiUrl),e.apiKey===void 0&&t.apiKey!==void 0&&(e.apiKey=t.apiKey),e.deployToken===void 0&&t.deployToken!==void 0&&(e.deployToken=t.deployToken),e.timeout===void 0&&t.timeout!==void 0&&(e.timeout=t.timeout),e.maxConcurrency===void 0&&t.maxConcurrency!==void 0&&(e.maxConcurrency=t.maxConcurrency),e.onProgress===void 0&&t.onProgress!==void 0&&(e.onProgress=t.onProgress),e.caller===void 0&&t.caller!==void 0&&(e.caller=t.caller),e}E();E();z();async function Be(){let n=JSON.stringify(ae,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await H(t);return{path:q,content:t,size:n.length,md5:e}}async function me(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===q))return n;try{if(await t.checkSPA(n,e)){let r=await Be();return[...n,r]}}catch{}return n}function fe(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:r,hasAuth:s}=n;return{upload:async(p,c={})=>{await e();let o=r?de(c,r):c;if(s&&!s()&&!o.deployToken&&!o.apiKey)try{let h=t(),{secret:L}=await h.fetchAgentToken();o.deployToken=L}catch(h){throw N(h)&&h.type===d.RateLimit?a.rateLimit("public deploy rate limit exceeded, try again later or run 'ship config' for a free account with higher limits"):h}if(!i)throw a.config("processInput function is not provided.");let l=t(),u=await i(p,o);return u=await me(u,l,o),l.deploy(u,o)},list:async()=>(await e(),t().listDeployments()),get:async p=>(await e(),t().getDeployment(p)),set:async(p,c)=>(await e(),t().updateDeploymentLabels(p,c.labels)),remove:async p=>{await e(),await t().removeDeployment(p)}}}function he(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,r={})=>(await e(),t().setDomain(i,r.deployment,r.labels)),list:async()=>(await e(),t().listDomains()),get:async i=>(await e(),t().getDomain(i)),remove:async i=>{await e(),await t().removeDomain(i)},verify:async i=>(await e(),t().verifyDomain(i)),validate:async i=>(await e(),t().validateDomain(i)),dns:async i=>(await e(),t().getDomainDns(i)),records:async i=>(await e(),t().getDomainRecords(i)),share:async i=>(await e(),t().getDomainShare(i))}}function ye(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function ge(n){let{getApi:t,ensureInit:e}=n;return{create:async(i={})=>(await e(),t().createToken(i.ttl,i.labels)),list:async()=>(await e(),t().listTokens()),remove:async i=>{await e(),await t().removeToken(i)}}}var K=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.auth=null;t={...t,apiUrl:t.apiUrl||void 0,apiKey:t.apiKey||void 0,deployToken:t.deployToken||void 0},this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.http=new B({...t,...ue(t),getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=fe({...e,processInput:(i,r)=>this.processInput(i,r),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this.domains=he(e),this.account=ye(e),this.tokens=ge(e)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(t){throw this.initPromise=null,t}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,e){return this.deployments.upload(t,e)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setDeployToken(t){if(!t||typeof t!="string")throw a.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:t}}setApiKey(t){if(!t||typeof t!="string")throw a.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:t}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};E();C();E();C();import{z as De}from"zod";import{z as Y}from"zod";var Ee={apiUrl:Y.string().url().optional(),apiKey:Y.string().min(1).optional(),deployToken:Y.string().min(1).optional()};var He=De.object(Ee).strict(),ze={apiUrl:"SHIP_API_URL",apiKey:"SHIP_API_KEY",deployToken:"SHIP_DEPLOY_TOKEN"};function Se(){if(b()!=="node")return{};let n={apiUrl:process.env.SHIP_API_URL||void 0,apiKey:process.env.SHIP_API_KEY||void 0,deployToken:process.env.SHIP_DEPLOY_TOKEN||void 0};try{return He.parse(n)}catch(t){if(t instanceof De.ZodError){let e=t.issues[0],i=e.path[0],r=(i&&ze[i])??"SHIP environment configuration";throw a.config(`Invalid ${r}: ${e.message}`)}throw a.config("Invalid environment configuration")}}E();async function Te(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),{labels:s,via:p,password:c,flags:o}=t,l=new e,u=[];for(let D of n){if(!Buffer.isBuffer(D.content)&&!(typeof Blob<"u"&&D.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${D.path}`,D.path);if(!D.md5)throw a.file(`File missing md5 checksum: ${D.path}`,D.path);let m=new i([D.content],D.path,{type:"application/octet-stream"});l.append("files[]",m),u.push(D.md5)}l.append("checksums",JSON.stringify(u)),s&&s.length>0&&l.append("labels",JSON.stringify(s)),p&&l.append("via",p),c&&l.append("password",c),o?.build&&l.append("build","true"),o?.prerender&&l.append("prerender","true"),o?.spa&&l.append("spa","true");let h=new r(l),L=[];for await(let D of h.encode())L.push(Buffer.from(D));let R=Buffer.concat(L);return{body:R.buffer.slice(R.byteOffset,R.byteOffset+R.byteLength),headers:{"Content-Type":h.contentType,"Content-Length":Buffer.byteLength(R).toString()}}}z();function Vt(n,t,e,i=!0){let r=n===1?t:e;return i?`${n} ${r}`:r}W();Z();C();ne();ie();E();re();var se=class extends K{constructor(t={}){if(b()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=Se();super({...t,apiUrl:t.apiUrl||e.apiUrl,apiKey:t.apiKey||e.apiKey,deployToken:t.deployToken||e.deployToken})}async deploy(t,e){return super.deploy(t,e)}async processInput(t,e){let i=typeof t=="string"?[t]:t;if(!Array.isArray(i)||!i.every(s=>typeof s=="string"))throw a.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw a.business("No files to deploy.");let{processFilesForNode:r}=await Promise.resolve().then(()=>(re(),be));return r(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return Te}},qe=se;export{x as API_KEY,Je as AccountPlan,B as ApiHttp,Qe as AuthMethod,Oe as BLOCKED_EXTENSIONS,_ as DEFAULT_API,q as DEPLOYMENT_CONFIG_FILENAME,I as DEPLOY_TOKEN,Ye as DeploymentStatus,We as DomainStatus,d as ErrorType,g as FILE_VALIDATION_STATUS,g as FileValidationStatus,Ge as JUNK_DIRECTORIES,P as LABEL_CONSTRAINTS,pe as LABEL_PATTERN,O as PASSWORD_CONSTRAINTS,ae as SPA_DEFAULT_CONFIG,se as Ship,a as ShipError,j as UNBUILT_PROJECT_MARKERS,ke as UNSAFE_FILENAME_CHARS,Dt as __setTestEnvironment,tn as allValidFilesReady,H as calculateMD5,ye as createAccountResource,fe as createDeploymentResource,he as createDomainResource,ge as createTokenResource,qe as default,lt as deserializeLabels,rt as extractSubdomain,Ae as filterJunk,ee as formatFileSize,st as generateDeploymentUrl,ot as generateDomainUrl,b as getENV,je as getValidFiles,U as hasUnbuiltMarker,oe as hasUnsafeChars,$ as isBlockedExtension,it as isCustomDomain,nt as isDeployment,le as isPlatformDomain,N as isShipError,de as mergeDeployOptions,Re as optimizeDeployPaths,Vt as pluralize,Pe as processFilesForNode,ue as resolveConfig,at as serializeLabels,Ze as validateApiKey,tt as validateApiUrl,xe as validateDeployFile,ve as validateDeployPath,et as validateDeployToken,te as validateFileName,en as validateFiles};
2
2
  //# sourceMappingURL=index.js.map