@shipstatic/ship 2.0.0-beta.2 → 2.0.0-beta.21

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.js CHANGED
@@ -1,2 +1,2 @@
1
- var _e=Object.defineProperty;var w=(n,t)=>()=>(n&&(t=n(n=0)),t);var ke=(n,t)=>{for(var e in t)_e(n,e,{get:t[e],enumerable:!0})};function L(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 Be.has(e)}function le(n){return He.test(n)}function _(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>j.has(e))}function Ge(n){return n.startsWith(pe.PREFIX)?x.API_KEY:n.startsWith(ce.PREFIX)?x.DEPLOY_TOKEN:x.OPAQUE}function de(n,t,e){if(!n.startsWith(t.PREFIX))throw a.validation(`${e} must start with "${t.PREFIX}"`);if(n.length!==t.TOTAL_LENGTH)throw a.validation(`${e} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let i=n.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(i))throw a.validation(`${e} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function ze(n){de(n,pe,"API key")}function Ve(n){de(n,ce,"Deploy token")}function K(n){switch(Ge(n)){case x.API_KEY:ze(n);return;case x.DEPLOY_TOKEN:Ve(n);return;case x.OPAQUE:if(!n)throw a.validation("Token must be a non-empty string")}}function me(n){if(!n||n.length>V.MAX_LENGTH||!V.PATTERN.test(n))throw a.validation(`Caller must be 1-${V.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function pt(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 L(t)?t:a.validation("API URL must be a valid URL")}}function ct(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function fe(n,t){return n.endsWith(`.${t}`)}function ut(n,t){return!fe(n,t)}function dt(n,t){return fe(n,t)?n.slice(0,-(t.length+1)):null}function mt(n){return`https://${n}`}function ft(n){return`https://${n}`}function ht(n){return!n||n.length===0?null:JSON.stringify(n)}function yt(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}function Y(n){if(n==null)return;if(typeof n!="string")throw a.validation("Password must be a string");let t=n.trim();if(t.length<C.MIN_LENGTH||t.length>C.MAX_LENGTH)throw a.validation(`Password must be between ${C.MIN_LENGTH} and ${C.MAX_LENGTH} characters`);return t}var st,ot,at,m,Ue,z,Me,a,Be,He,j,ae,pe,ce,V,x,lt,q,ue,X,y,P,he,C,g=w(()=>{"use strict";st={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},ot={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},at={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},m={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},Ue=new Set([m.Network,m.Cancelled,m.File,m.Config]),z={client:new Set([m.Business,m.Config,m.File,m.Forbidden,m.Validation]),network:new Set([m.Network]),auth:new Set([m.Authentication])},Me=new Set(Object.values(m).filter(n=>!Ue.has(n))),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.details,e=this.type===m.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}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 p=o;typeof p.message=="string"?i=p.message:typeof p.error=="string"&&(i=p.error),r=p.details,typeof p.error=="string"&&Me.has(p.error)&&(s=p.error)}}else{let o=await t.text();o&&(i=o)}}catch{}i=i||`${e||"Request"} failed with status ${t.status}`;let l=s??(t.status===401?m.Authentication:t.status===403?m.Forbidden:t.status===429?m.RateLimit:m.Api);return new n(l,i,t.status,r)}static fromFetchError(t,e){if(L(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}`,{cause:t}):new n(m.Api,`${i} failed: ${t.message}`):new n(m.Api,`${i} failed: Unknown error`)}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 forbidden(t,e){return new n(m.Forbidden,t,403,e)}static rateLimit(t="Too many requests",e){return new n(m.RateLimit,t,429,e)}static authentication(t="Authentication required",e){return new n(m.Authentication,t,401,e)}static business(t,e=400,i){return new n(m.Business,t,e,i)}static network(t,e){return new n(m.Network,t,void 0,e)}static cancelled(t,e){return new n(m.Cancelled,t,void 0,e)}static file(t,e){return new n(m.File,t,void 0,e)}static config(t,e){return new n(m.Config,t,void 0,e)}static api(t,e=500,i){return new n(m.Api,t,e,i)}isClientError(){return z.client.has(this.type)}isNetworkError(){return z.network.has(this.type)}isAuthError(){return z.auth.has(this.type)}isType(t){return this.type===t}};Be=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"]);He=/[\x00-\x1f\x7f#?%\\<>"]/;j=new Set(["node_modules","package.json"]);ae={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},pe={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},ce={PREFIX:"deploy-",HEX_LENGTH:64,TOTAL_LENGTH:71},V={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},x={API_KEY:ae.API_KEY,DEPLOY_TOKEN:ae.TOKEN,OPAQUE:"opaque"};lt={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},q="ship.json",ue={rewrites:[{source:"/(.*)",destination:"/index.html"}]};X="https://api.shipstatic.com",y={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:"._-"},he=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;C={MIN_LENGTH:6,MAX_LENGTH:128}});async function qe(n){let t=(await import("spark-md5")).default,e=new t.ArrayBuffer,i=2097152;for(let r=0;r<n.size;r+=i){let s=Math.min(r+i,n.size);e.append(await n.slice(r,s).arrayBuffer())}return{md5:e.end()}}async function Ke(n){let{createHash:t}=await import("crypto"),e=t("md5");return e.update(n),{md5:e.digest("hex")}}async function Xe(n){let{createHash:t}=await import("crypto"),{createReadStream:e}=await import("fs");return new Promise((i,r)=>{let s=t("md5"),l=e(n);l.on("error",u=>r(a.business(`Failed to read file for MD5: ${u.message}`))),l.on("data",u=>s.update(u)),l.on("end",()=>i({md5:s.digest("hex")}))})}async function M(n){if(n instanceof Blob)return qe(n);if(typeof Buffer<"u"&&Buffer.isBuffer(n))return Ke(n);if(typeof n=="string")return Xe(n);throw a.business("Invalid input for MD5 calculation")}var B=w(()=>{"use strict";g()});function Bt(n){W=n}function We(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function I(){return W||We()}var W,F=w(()=>{"use strict";W=null});function xe(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(u=>u[s]===l))i.push(l);else break}return i.join("/")}function G(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var J=w(()=>{"use strict"});function Ie(n,t={}){if(t.flatten===!1)return n.map(i=>({path:G(i),name:Q(i)}));let e=Ze(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 Ze(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(u=>u[s]===l))i.push(l);else break}return i.join("/")}function Q(n){return n.split(/[/\\]/).pop()||n}var Z=w(()=>{"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/e**r).toFixed(t))} ${i[r]}`}function te(n){if(le(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 rn(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(_(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:y.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:y.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let o of n){let p=y.READY,d="Ready for upload",A=o.name?te(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===y.PROCESSING_ERROR)p=y.VALIDATION_FAILED,d=o.statusMessage||"File failed during processing",e.push({file:o.name,message:d});else if(o.size===0){p=y.EXCLUDED,d="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:d}),r.push({...o,status:p,statusMessage:d});continue}else o.size<0?(p=y.VALIDATION_FAILED,d="File size must be positive",e.push({file:o.name,message:d})):!o.name||o.name.trim().length===0?(p=y.VALIDATION_FAILED,d="File name cannot be empty",e.push({file:o.name||"(empty)",message:d})):o.name.includes("\0")?(p=y.VALIDATION_FAILED,d="File name contains invalid characters (null byte)",e.push({file:o.name,message:d})):A.valid?$(o.name)?(p=y.VALIDATION_FAILED,d=`File extension not allowed: "${o.name}"`,e.push({file:o.name,message:d})):o.size>t.maxFileSize?(p=y.VALIDATION_FAILED,d=`File size (${ee(o.size)}) exceeds limit of ${ee(t.maxFileSize)}`,e.push({file:o.name,message:d})):(s+=o.size,s>t.maxTotalSize&&(p=y.VALIDATION_FAILED,d=`Total size would exceed limit of ${ee(t.maxTotalSize)}`,e.push({file:o.name,message:d}))):(p=y.VALIDATION_FAILED,d=A.reason||"Invalid file name",e.push({file:o.name,message:d}));r.push({...o,status:p,statusMessage:d})}e.length>0&&(r=r.map(o=>o.status===y.EXCLUDED?o:{...o,status:y.VALIDATION_FAILED,statusMessage:o.status===y.VALIDATION_FAILED?o.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=e.length===0?r.filter(o=>o.status===y.READY):[],u=e.length===0;return{files:r,validFiles:l,errors:e,warnings:i,canDeploy:u}}function et(n){return n.filter(t=>t.status===y.READY)}function sn(n){return et(n).length>0}var ne=w(()=>{"use strict";g()});import{isJunk as tt}from"junk";function be(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&_(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(tt(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(nt.some(u=>l.toLowerCase()===u.toLowerCase()))return!1;return!0})}var nt,ie=w(()=>{"use strict";g();nt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ne(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 Le(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 re=w(()=>{"use strict";g();ne()});var Ce={};ke(Ce,{processFilesForNode:()=>Fe});import*as E from"fs";import*as D from"path";function Oe(n,t=new Set){let e=[],i=E.realpathSync(n);if(t.has(i))return e;t.add(i);let r=E.readdirSync(n);for(let s of r){let l=D.join(n,s),u=E.statSync(l);if(u.isDirectory()){let o=Oe(l,t);e.push(...o)}else u.isFile()&&e.push(l)}return e}async function Fe(n,t={},e){if(I()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let c of n){let f=D.resolve(c);try{if(E.statSync(f).isDirectory()){let S=E.readdirSync(f).find(T=>j.has(T));if(S)throw a.business(`"${S}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(S){if(L(S))throw S}}let i=n.flatMap(c=>{let f=D.resolve(c);try{return E.statSync(f).isDirectory()?Oe(f):[f]}catch{throw a.file(`Path does not exist: ${c}`,{filePath:c})}}),r=[...new Set(i)],s=n.map(c=>D.resolve(c)),l=xe(s.map(c=>{try{return E.statSync(c).isDirectory()?c:D.dirname(c)}catch{return D.dirname(c)}})),u=r.map(c=>{if(l&&l.length>0){let f=D.relative(l,c);if(f&&typeof f=="string"&&!f.startsWith(".."))return f.replace(/\\/g,"/")}return D.basename(c)}),p=Ie(u,{flatten:t.pathDetect!==!1}).map(c=>c.path),d=new Set(be(p));if(d.size===0)return[];let A=[],b=[];for(let c=0;c<r.length;c++)d.has(p[c])&&(A.push(r[c]),b.push(p[c]));let v=[],R=0;if(!e)throw a.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let c=0;c<A.length;c++){let f=A[c],S=b[c];try{Ne(S,f);let T=E.statSync(f);if(T.size===0)continue;if(Le(S,f),T.size>e.maxFileSize)throw a.business(`File ${f} is too large. Maximum allowed size is ${e.maxFileSize/(1024*1024)}MB.`);if(R+=T.size,R>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let N=E.readFileSync(f),{md5:$e}=await M(N);v.push({path:S,content:N,size:N.length,md5:$e})}catch(T){if(L(T))throw T;let N=T instanceof Error?T.message:String(T);throw a.file(`Failed to read file "${f}": ${N}`,{filePath:f})}}if(v.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return v}var se=w(()=>{"use strict";g();Z();F();ie();B();J();re()});g();g();g();var k=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 u=l instanceof Error?l:new Error(String(l));this.emit("error",u,String(t))},0)}}};g();g();function O(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(!he.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 h={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},je=3e4,U=class extends k{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||X,this.getAuthHeadersCallback=e.getAuthHeaders,this.session=e.session??!1,this.caller=e.caller,this.timeout=e.timeout??je,this.fetch=e.fetch??globalThis.fetch.bind(globalThis),this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||h.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}async executeRequest(e,i,r){let s=()=>{};try{let l=await this.mergeHeaders(i.headers),u=this.createTimeoutSignal(i.signal);s=u.cleanup;let o={...i,headers:l,credentials:this.session&&!l.Authorization?"include":void 0,signal:u.signal};this.emit("request",e,o);let p=await this.fetch(e,o);if(s(),!p.ok)throw await a.fromHttpResponse(p,r);return this.emit("response",this.safeClone(p),e),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(l){s();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)}async mergeHeaders(e={}){return{...this.globalHeaders,...this.caller?{"X-Caller":this.caller}:{},...await 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 o of e)if(!o.md5)throw a.file(`MD5 checksum missing for file: ${o.path}`,{filePath:o.path});Y(i.password);let r=O(i.labels),s=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:l,headers:u}=await this.createDeployBody(e,{labels:r,via:i.via,password:i.password,flags:s,captcha:i.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:l,headers:u,signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){let r=O(i);return this.request(`${this.apiUrl}${h.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}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,r){let s=O(r),l={};i&&(l.deployment=i),s!==void 0&&(l.labels=s);let{data:u,status:o}=await this.requestWithStatus(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)},"Set domain");return{...u,isCreate:o===201}}async listDomains(){return this.request(`${this.apiUrl}${h.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,i){let r=O(i),s={};return e!==void 0&&(s.ttl=e),r!==void 0&&(s.labels=r),this.request(`${this.apiUrl}${h.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${h.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${h.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${h.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${h.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return(await this.request(`${this.apiUrl}${h.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e,i={}){let r=e.find(o=>o.path==="index.html"||o.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={files:e.map(o=>o.path),index:s};return(await this.request(`${this.apiUrl}${h.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)},"SPA check")).isSPA}};g();function ye(n,t){let e={...n};return 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}g();B();async function Ye(){let n=JSON.stringify(ue,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await M(t);return{path:q,content:t,size:n.length,md5:e}}async function ge(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 Ye();return[...n,r]}}catch{}return n}function Ee(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:r}=n;return{upload:async(s,l={})=>{await e();let u=r?ye(l,r):l;if(!i)throw a.config("processInput function is not provided.");let o=t(),p=await i(s,u);return p=await ge(p,o,u),o.deploy(p,u)},list:async()=>(await e(),t().listDeployments()),get:async s=>(await e(),t().getDeployment(s)),set:async(s,l)=>(await e(),t().updateDeploymentLabels(s,l.labels)),remove:async s=>{await e(),await t().removeDeployment(s)}}}function De(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 Se(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function Te(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 H=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.credential=null;if(t={...t,apiUrl:t.apiUrl||void 0,token:t.token||void 0,caller:t.caller||void 0},this.clientOptions=t,t.caller!==void 0&&me(t.caller),t.token&&t.session)throw a.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(K(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new U({...t,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=Ee({...e,processInput:(i,r)=>this.processInput(i,r),clientDefaults:this.clientOptions}),this.domains=De(e),this.account=Se(e),this.tokens=Te(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({})}setToken(t){if(this.clientOptions.session)throw a.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw a.business("Invalid token provided. Token must be a non-empty string.");K(t),this.credential=t;return}if(typeof t!="function")throw a.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw a.authentication("Token provider returned no token.");if(typeof t!="string")throw a.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};F();g();import{z as Re}from"zod";import{z as Ae}from"zod";var we={apiUrl:Ae.string().url().optional(),token:Ae.string().min(1).optional()};F();var Je=Re.object(we).strict(),Qe={apiUrl:"SHIP_API_URL",token:"SHIP_TOKEN"};function Pe(){if(I()!=="node")return{};let n={apiUrl:process.env.SHIP_API_URL||void 0,token:process.env.SHIP_TOKEN||void 0};try{return Je.parse(n)}catch(t){if(t instanceof Re.ZodError){let e=t.issues[0],i=e.path[0],r=(i&&Qe[i])??"SHIP environment configuration";throw a.config(`Invalid ${r}: ${e.message}`)}throw a.config("Invalid environment configuration")}}g();async function ve(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),{labels:s,via:l,password:u,flags:o,captcha:p}=t,d=new e,A=[];for(let c of n){if(!Buffer.isBuffer(c.content)&&!(typeof Blob<"u"&&c.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${c.path}`,{filePath:c.path});if(!c.md5)throw a.file(`File missing md5 checksum: ${c.path}`,{filePath:c.path});let f=new i([c.content],c.path,{type:"application/octet-stream"});d.append("files[]",f),A.push(c.md5)}d.append("checksums",JSON.stringify(A)),s&&s.length>0&&d.append("labels",JSON.stringify(s)),l&&d.append("via",l),u&&d.append("password",u),o?.build&&d.append("build","true"),o?.prerender&&d.append("prerender","true"),o?.spa&&d.append("spa","true"),p&&d.append("captcha",p);let b=new r(d),v=[];for await(let c of b.encode())v.push(Buffer.from(c));let R=Buffer.concat(v);return{body:R.buffer.slice(R.byteOffset,R.byteOffset+R.byteLength),headers:{"Content-Type":b.contentType,"Content-Length":Buffer.byteLength(R).toString()}}}g();g();Z();F();ne();ie();B();re();function mn(n,t,e,i=!0){let r=n===1?t:e;return i?`${n} ${r}`:r}se();var oe=class extends H{constructor(t={}){if(I()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=Pe();super({...t,apiUrl:t.apiUrl||e.apiUrl,token:t.token||(t.session?void 0:e.token)})}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(()=>(se(),Ce));return r(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return ve}},it=oe;export{pe as API_KEY,at as AccountPlan,U as ApiHttp,ae as AuthMethod,Be as BLOCKED_EXTENSIONS,V as CALLER,X as DEFAULT_API,q as DEPLOYMENT_CONFIG_FILENAME,ce as DEPLOY_TOKEN,st as DeploymentStatus,ot as DomainStatus,m as ErrorType,y as FILE_VALIDATION_STATUS,y as FileValidationStatus,nt as JUNK_DIRECTORIES,P as LABEL_CONSTRAINTS,he as LABEL_PATTERN,lt as OAuthScope,C as PASSWORD_CONSTRAINTS,ue as SPA_DEFAULT_CONFIG,oe as Ship,a as ShipError,x as TokenKind,j as UNBUILT_PROJECT_MARKERS,He as UNSAFE_FILENAME_CHARS,Bt as __setTestEnvironment,sn as allValidFilesReady,M as calculateMD5,Ge as classifyToken,Se as createAccountResource,Ee as createDeploymentResource,De as createDomainResource,Te as createTokenResource,it as default,yt as deserializeLabels,dt as extractSubdomain,be as filterJunk,ee as formatFileSize,mt as generateDeploymentUrl,ft as generateDomainUrl,I as getENV,et as getValidFiles,_ as hasUnbuiltMarker,le as hasUnsafeChars,$ as isBlockedExtension,ut as isCustomDomain,ct as isDeployment,fe as isPlatformDomain,L as isShipError,ye as mergeDeployOptions,Ie as optimizeDeployPaths,mn as pluralize,Fe as processFilesForNode,ht as serializeLabels,ze as validateApiKey,pt as validateApiUrl,me as validateCaller,Le as validateDeployFile,Ne as validateDeployPath,Ve as validateDeployToken,te as validateFileName,rn as validateFiles,Y as validatePassword,K as validateToken};
1
+ var Ve=Object.defineProperty;var I=(n,t)=>()=>(n&&(t=n(n=0)),t);var Ke=(n,t)=>{for(var e in t)Ve(n,e,{get:t[e],enumerable:!0})};function St(n){if(!n||typeof n!="string")return;let t=n.trim().toLowerCase();return Object.values(je).includes(t)?t:void 0}function me(n){if(n==null)return;if(typeof n!="string")throw a.validation("Idempotency key must be a string.");let t=n.trim();if(!t)throw a.validation("Idempotency key must not be empty.");if(t.length>M.MAX_LENGTH)throw a.validation(`Idempotency key must be at most ${M.MAX_LENGTH} characters.`);return t}function We(n){return typeof n.code=="string"?!0:n instanceof TypeError&&n.message.includes("fetch")}function _(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function B(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return Je.has(e)}function fe(n){return Ze.test(n)}function H(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>W.has(e))}function et(n){return n.startsWith(he.PREFIX)?x.API_KEY:n.startsWith(ye.PREFIX)?x.DEPLOY_TOKEN:x.OPAQUE}function Ee(n){let t=n.charCodeAt(0)===65279?n.slice(1):n,e;try{e=JSON.parse(t)}catch(i){throw a.config(`invalid JSON format in config: ${i.message}`,{filePath:P})}if(e===null||typeof e!="object"||Array.isArray(e))throw a.config(`${P} must contain a JSON object`,{filePath:P})}function De(n,t,e){if(!n.startsWith(t.PREFIX))throw a.validation(`${e} must start with "${t.PREFIX}"`);if(n.length!==t.TOTAL_LENGTH)throw a.validation(`${e} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let i=n.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(i))throw a.validation(`${e} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function tt(n){De(n,he,"API key")}function nt(n){De(n,ye,"Deploy token")}function J(n){switch(et(n)){case x.API_KEY:tt(n);return;case x.DEPLOY_TOKEN:nt(n);return;case x.OPAQUE:if(!n)throw a.validation("Token must be a non-empty string")}}function Ae(n){if(!n||n.length>C.MAX_LENGTH||!C.PATTERN.test(n))throw a.validation(`Caller must be 1-${C.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function Lt(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 _(t)?t:a.validation("API URL must be a valid URL")}}function wt(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function Te(n,t){return n.endsWith(`.${t}`)}function Ot(n,t){return!Te(n,t)}function vt(n,t){return Te(n,t)?n.slice(0,-(t.length+1)):null}function Ct(n){return`https://${n}`}function _t(n){return`https://${n}`}function Ft(n){return!n||n.length===0?null:JSON.stringify(n)}function kt(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}function Z(n){if(n==null)return;if(typeof n!="string")throw a.validation("Password must be a string");let t=n.trim();if(t.length<U.MIN_LENGTH||t.length>U.MAX_LENGTH)throw a.validation(`Password must be between ${U.MIN_LENGTH} and ${U.MAX_LENGTH} characters`);return t}var At,je,Tt,M,Rt,f,R,m,Ye,X,qe,Xe,a,Je,Qe,It,Ze,W,Pt,de,he,ye,C,x,Nt,P,ge,G,Q,F,xt,bt,y,L,Se,U,g=I(()=>{"use strict";At={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},je={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc"},Tt={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},M={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};Rt={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},f={DEPLOYMENTS:"/deployments",DEPLOYMENT:n=>`/deployments/${n}`,DEPLOYMENT_CONFIG:n=>`/deployments/${n}/config`,DOMAINS:"/domains",DOMAIN:n=>`/domains/${n}`,DOMAIN_VERIFY:n=>`/domains/${n}/verify`,DOMAIN_DNS:n=>`/domains/${n}/dns`,DOMAIN_RECORDS:n=>`/domains/${n}/records`,DOMAIN_SHARE:n=>`/domains/${n}/share`,DOMAIN_PROPAGATION:n=>`/domains/${n}/propagation`,DOMAINS_VALIDATE:"/domains/validate",TOKENS:"/tokens",TOKEN:n=>`/tokens/${n}`,ACCOUNT:"/account",ACCOUNT_KEY:"/account/key",ACCOUNT_CLAIM:"/account/claim",ACTIVITIES:"/activities",LABELS:"/labels",LIMITS:"/limits",PING:"/ping",SETUP:"/setup",SPA_CHECK:"/spa-check",UPLOAD:"/upload"},R={FILES:"files[]",CHECKSUMS:"checksums",LABELS:"labels",VIA:"via",PASSWORD:"password",BUILD:"build",PRERENDER:"prerender",SPA:"spa",CAPTCHA:"captcha"},m={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Maintenance:"maintenance",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},Ye=new Set([m.Network,m.Cancelled,m.File,m.Config]),X={client:new Set([m.Business,m.Cancelled,m.Config,m.File,m.Forbidden,m.NotFound,m.RateLimit,m.Validation]),network:new Set([m.Network]),auth:new Set([m.Authentication])},qe=new Set(Object.values(m).filter(n=>!Ye.has(n))),Xe=200;a=class n extends Error{type;status;details;constructor(t,e,i,s){super(e),this.type=t,this.status=i,this.details=s,this.name="ShipError"}toResponse(){let t=this.details,e=this.type===m.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static async fromHttpResponse(t,e){let i,s,r;try{if(t.headers.get("content-type")?.includes("application/json")){let c=await t.json();if(c&&typeof c=="object"){let p=c;typeof p.message=="string"?i=p.message:typeof p.error=="string"&&(i=p.error),s=p.details,typeof p.error=="string"&&qe.has(p.error)&&(r=p.error)}}else{let c=(await t.text()).trim();c&&!c.startsWith("<")&&c.length<=Xe&&(i=c)}}catch{}let l=t.headers.get("retry-after");if(l!==null){let o=l.trim(),c=/^\d+$/.test(o)?Number(o):Math.ceil((Date.parse(o)-Date.now())/1e3);if(Number.isFinite(c)&&c>=0){let p=s&&typeof s=="object"?s:{};p.retryAfter===void 0&&(s={...p,retryAfter:c})}}i=i||`${e||"Request"} failed with status ${t.status}`;let d=r??(t.status===401?m.Authentication:t.status===403?m.Forbidden:t.status===429?m.RateLimit:m.Api);return new n(d,i,t.status,s)}static fromFetchError(t,e){if(_(t))return t;let i=e||"Request";return t instanceof Error?t.name==="AbortError"?n.cancelled(`${i} was cancelled`):We(t)?n.network(`${i} failed: ${t.message}`,{cause:t}):new n(m.Api,`${i} failed: ${t.message}`):new n(m.Api,`${i} failed: Unknown error`)}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 forbidden(t,e){return new n(m.Forbidden,t,403,e)}static rateLimit(t="Too many requests",e){return new n(m.RateLimit,t,429,e)}static authentication(t="Authentication required",e){return new n(m.Authentication,t,401,e)}static business(t,e=400,i){return new n(m.Business,t,e,i)}static network(t,e){return new n(m.Network,t,void 0,e)}static cancelled(t,e){return new n(m.Cancelled,t,void 0,e)}static file(t,e){return new n(m.File,t,void 0,e)}static config(t,e){return new n(m.Config,t,void 0,e)}static api(t,e=500,i){return new n(m.Api,t,e,i)}static maintenance(t,e){return new n(m.Maintenance,t,503,e)}isClientError(){return X.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return X.network.has(this.type)}isAuthError(){return X.auth.has(this.type)}isType(t){return this.type===t}};Je=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"]);Qe=["html","htm","xhtml","xml","txt","md","markdown","pdf","csv","json","jsonc","webmanifest","map","toml","yaml","yml","rss","atom","css","scss","sass","less","js","mjs","cjs","jsx","ts","tsx","wasm","vue","svelte","png","jpg","jpeg","gif","webp","avif","svg","ico","bmp","tif","tiff","heic","heif","woff","woff2","ttf","otf","eot","mp3","wav","ogg","oga","opus","m4a","aac","flac","weba","mp4","webm","ogv","mov","m4v","avi","glb","gltf","usdz","vtt","srt","zip"],It=Qe.map(n=>`.${n}`).join(","),Ze=/[\x00-\x1f\x7f#?%\\<>"]/;W=new Set(["node_modules","package.json"]);Pt="/auth",de={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},he={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},ye={PREFIX:"deploy-",HEX_LENGTH:64,TOTAL_LENGTH:71},C={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},x={API_KEY:de.API_KEY,DEPLOY_TOKEN:de.TOKEN,OPAQUE:"opaque"};Nt={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},P="ship.json",ge={rewrites:[{source:"/(.*)",destination:"/index.html"}]},G={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};Q="https://api.shipstatic.com",F={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},xt="https://my.shipstatic.com/api-key",bt=4320*60,y={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};L={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},Se=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;U={MIN_LENGTH:6,MAX_LENGTH:128}});async function at(n){let t=(await import("spark-md5")).default,e=new t.ArrayBuffer,i=2097152;for(let s=0;s<n.size;s+=i){let r=Math.min(s+i,n.size);e.append(await n.slice(s,r).arrayBuffer())}return{md5:e.end()}}async function lt(n){let{createHash:t}=await import("crypto"),e=t("md5");return e.update(n),{md5:e.digest("hex")}}async function pt(n){let{createHash:t}=await import("crypto"),{createReadStream:e}=await import("fs");return new Promise((i,s)=>{let r=t("md5"),l=e(n);l.on("error",d=>s(a.file(`Failed to read file for MD5: ${d.message}`,{filePath:n}))),l.on("data",d=>r.update(d)),l.on("end",()=>i({md5:r.digest("hex")}))})}async function K(n){if(n instanceof Blob)return at(n);if(typeof Buffer<"u"&&Buffer.isBuffer(n))return lt(n);if(typeof n=="string")return pt(n);throw a.business("Invalid input for MD5 calculation")}var j=I(()=>{"use strict";g()});function rn(n){te=n}function ut(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function b(){return te||ut()}var te,$=I(()=>{"use strict";te=null});function Fe(n){if(!n||n.length===0)return"";let t=n.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let e=t.map(r=>r.split("/").filter(Boolean)),i=[],s=Math.min(...e.map(r=>r.length));for(let r=0;r<s;r++){let l=e[0][r];if(e.every(d=>d[r]===l))i.push(l);else break}return i.join("/")}function q(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ne=I(()=>{"use strict"});function ke(n,t={}){if(t.flatten===!1)return n.map(i=>({path:q(i),name:ie(i)}));let e=ft(n);return n.map(i=>{let s=q(i);if(e){let r=e.endsWith("/")?e:`${e}/`;s.startsWith(r)&&(s=s.substring(r.length))}return s||(s=ie(i)),{path:s,name:ie(i)}})}function ft(n){if(!n.length)return"";let e=n.map(r=>q(r)).map(r=>r.split("/")),i=[],s=Math.min(...e.map(r=>r.length));for(let r=0;r<s-1;r++){let l=e[0][r];if(e.every(d=>d[r]===l))i.push(l);else break}return i.join("/")}function ie(n){return n.split(/[/\\]/).pop()||n}var se=I(()=>{"use strict";ne()});function re(n,t=1){if(n===0)return"0 Bytes";let e=1024,i=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(n)/Math.log(e));return`${parseFloat((n/e**s).toFixed(t))} ${i[s]}`}function oe(n){if(fe(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 Sn(n,t){let e=[],i=[],s=[];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(H(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(c=>({...c,status:y.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(c=>({...c,status:y.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let r=0;for(let o of n){let c=y.READY,p="Ready for upload",S=o.name?oe(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===y.PROCESSING_ERROR)c=y.VALIDATION_FAILED,p=o.statusMessage||"File failed during processing",e.push({file:o.name,message:p});else if(o.size===0){c=y.EXCLUDED,p="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:p}),s.push({...o,status:c,statusMessage:p});continue}else o.size<0?(c=y.VALIDATION_FAILED,p="File size must be positive",e.push({file:o.name,message:p})):!o.name||o.name.trim().length===0?(c=y.VALIDATION_FAILED,p="File name cannot be empty",e.push({file:o.name||"(empty)",message:p})):o.name.includes("\0")?(c=y.VALIDATION_FAILED,p="File name contains invalid characters (null byte)",e.push({file:o.name,message:p})):S.valid?B(o.name)?(c=y.VALIDATION_FAILED,p=`File extension not allowed: "${o.name}"`,e.push({file:o.name,message:p})):o.size>t.maxFileSize?(c=y.VALIDATION_FAILED,p=`File size (${re(o.size)}) exceeds limit of ${re(t.maxFileSize)}`,e.push({file:o.name,message:p})):(r+=o.size,r>t.maxTotalSize&&(c=y.VALIDATION_FAILED,p=`Total size would exceed limit of ${re(t.maxTotalSize)}`,e.push({file:o.name,message:p}))):(c=y.VALIDATION_FAILED,p=S.reason||"Invalid file name",e.push({file:o.name,message:p}));s.push({...o,status:c,statusMessage:p})}e.length>0&&(s=s.map(o=>o.status===y.EXCLUDED?o:{...o,status:y.VALIDATION_FAILED,statusMessage:o.status===y.VALIDATION_FAILED?o.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=e.length===0?s.filter(o=>o.status===y.READY):[],d=e.length===0;return{files:s,validFiles:l,errors:e,warnings:i,canDeploy:d}}function ht(n){return n.filter(t=>t.status===y.READY)}function Rn(n){return ht(n).length>0}var ae=I(()=>{"use strict";g()});import{isJunk as yt}from"junk";function $e(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&H(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 s=i[i.length-1];if(yt(s))return!1;for(let l of i)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let r=i.slice(0,-1);for(let l of r)if(gt.some(d=>l.toLowerCase()===d.toLowerCase()))return!1;return!0})}var gt,le=I(()=>{"use strict";g();gt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ue(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 Me(n,t){let e=oe(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if(B(n))throw a.business(`File extension not allowed: "${t}"`)}var pe=I(()=>{"use strict";g();ae()});var Ge={};Ke(Ge,{processFilesForNode:()=>He});import*as E from"fs";import*as D from"path";function Be(n,t=new Set){let e=[],i=E.realpathSync(n);if(t.has(i))return e;t.add(i);let s=E.readdirSync(n);for(let r of s){let l=D.join(n,r),d=E.statSync(l);if(d.isDirectory()){let o=Be(l,t);e.push(...o)}else d.isFile()&&e.push(l)}return e}async function He(n,t={},e){if(b()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let u of n){let h=D.resolve(u);try{if(E.statSync(h).isDirectory()){let A=E.readdirSync(h).find(T=>W.has(T));if(A)throw a.business(`"${A}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(A){if(_(A))throw A}}let i=n.flatMap(u=>{let h=D.resolve(u);try{return E.statSync(h).isDirectory()?Be(h):[h]}catch{throw a.file(`Path does not exist: ${u}`,{filePath:u})}}),s=[...new Set(i)],r=n.map(u=>D.resolve(u)),l=Fe(r.map(u=>{try{return E.statSync(u).isDirectory()?u:D.dirname(u)}catch{return D.dirname(u)}})),d=s.map(u=>{if(l&&l.length>0){let h=D.relative(l,u);if(h&&typeof h=="string"&&!h.startsWith(".."))return h.replace(/\\/g,"/")}return D.basename(u)}),c=ke(d,{flatten:t.pathDetect!==!1}).map(u=>u.path),p=new Set($e(c));if(p.size===0)return[];let S=[],O=[];for(let u=0;u<s.length;u++)p.has(c[u])&&(S.push(s[u]),O.push(c[u]));let w=[],N=0;if(!e)throw a.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let u=0;u<S.length;u++){let h=S[u],A=O[u];try{Ue(A,h);let T=E.statSync(h);if(T.size===0)continue;if(Me(A,h),T.size>e.maxFileSize)throw a.business(`File ${h} is too large. Maximum allowed size is ${e.maxFileSize/(1024*1024)}MB.`);if(N+=T.size,N>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let v=E.readFileSync(h),{md5:ze}=await K(v);w.push({path:A,content:v,size:v.length,md5:ze})}catch(T){if(_(T))throw T;let v=T instanceof Error?T.message:String(T);throw a.file(`Failed to read file "${h}": ${v}`,{filePath:h})}}if(w.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return w}var ce=I(()=>{"use strict";g();se();$();le();j();ne();pe()});g();g();g();var z=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 s=Array.from(i);for(let r of s)try{r(...e)}catch(l){i.delete(r),t!=="error"&&setTimeout(()=>{let d=l instanceof Error?l:new Error(String(l));this.emit("error",d,String(t))},0)}}};g();g();function k(n){if(n==null)return;if(n.length===0)return n;if(n.length>L.MAX_COUNT)throw a.validation(`Maximum ${L.MAX_COUNT} labels allowed`);let t=n.map((i,s)=>{if(typeof i!="string")throw a.validation(`Label at index ${s} must be a string`);let r=i.trim().toLowerCase();if(r.length<L.MIN_LENGTH)throw a.validation(`Labels must be at least ${L.MIN_LENGTH} characters long`);if(r.length>L.MAX_LENGTH)throw a.validation(`Labels must be no more than ${L.MAX_LENGTH} characters long`);if(!Se.test(r))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${L.SEPARATORS}) between segments`);return r}),e=[...new Set(t)];if(e.length!==t.length)throw a.validation("Duplicate labels are not allowed");return e}async function Re(n){let t=n.find(s=>s.path===P||s.path===`/${P}`);if(!t)return;let e=t.content,i=typeof e.text=="function"?await e.text():t.content.toString("utf8");Ee(i)}var it=3e4,Ie=3e5,st=3e5,rt=Ie+st,ot="sdk";function ee(n){let t=new URLSearchParams;n?.limit!==void 0&&t.set("limit",String(n.limit)),n?.cursor!==void 0&&t.set("cursor",n.cursor);let e=t.toString();return e?`?${e}`:""}var V=class extends z{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||Q,this.getAuthHeadersCallback=e.getAuthHeaders,this.session=e.session??!1,this.caller=e.caller,this.timeout=e.timeout??it,this.deployTimeout=e.timeout??Ie,this.deployBuildTimeout=e.timeout??rt,this.fetch=e.fetch??globalThis.fetch.bind(globalThis),this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||f.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}async executeRequest(e,i,s,r=this.timeout){let l=()=>{};try{let d=await this.mergeHeaders(i.headers),o=this.createTimeoutSignal(i.signal,r);l=o.cleanup;let c={...i,headers:d,credentials:this.session&&!d.Authorization?"include":void 0,signal:o.signal};this.emit("request",e,c);let p=await this.fetch(e,c);if(l(),!p.ok)throw await a.fromHttpResponse(p,s);return this.emit("response",this.safeClone(p),e),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(d){l();let o=a.fromFetchError(d,s);throw this.emit("error",o,e),o}}async request(e,i,s,r){let{data:l}=await this.executeRequest(e,i,s,r);return l}async requestWithStatus(e,i,s){return this.executeRequest(e,i,s)}async mergeHeaders(e={}){return{...this.globalHeaders,...this.caller?{[C.HEADER]:this.caller}:{},...await this.getAuthHeadersCallback(),...e}}createTimeoutSignal(e,i=this.timeout){let s=new AbortController,r=setTimeout(()=>s.abort(),i);if(e){let l=()=>s.abort();e.addEventListener("abort",l),e.aborted&&s.abort()}return{signal:s.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 c of e)if(!c.md5)throw a.file(`MD5 checksum missing for file: ${c.path}`,{filePath:c.path});Z(i.password);let s=me(i.idempotencyKey),r=k(i.labels);await Re(e);let l=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:d,headers:o}=await this.createDeployBody(e,{labels:r,via:i.via??ot,password:i.password,flags:l,captcha:i.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:d,headers:s?{...o,[M.HEADER]:s}:o,signal:i.signal||null},"Deploy",i.build||i.prerender?this.deployBuildTimeout:this.deployTimeout)}async listDeployments(e){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}${ee(e)}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENT(encodeURIComponent(e))}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){let s=k(i);return this.request(`${this.apiUrl}${f.DEPLOYMENT(encodeURIComponent(e))}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:s})},"Update deployment labels")}async deleteDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENT(encodeURIComponent(e))}`,{method:"DELETE"},"Delete deployment")}async setDomain(e,i,s){let r=k(s),l={};i&&(l.deployment=i),r!==void 0&&(l.labels=r);let{data:d,status:o}=await this.requestWithStatus(`${this.apiUrl}${f.DOMAIN(encodeURIComponent(e))}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)},"Set domain");return{...d,isCreate:o===201}}async listDomains(e){return this.request(`${this.apiUrl}${f.DOMAINS}${ee(e)}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${f.DOMAIN(encodeURIComponent(e))}`,{method:"GET"},"Get domain")}async deleteDomain(e){return this.request(`${this.apiUrl}${f.DOMAIN(encodeURIComponent(e))}`,{method:"DELETE"},"Delete domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${f.DOMAIN_VERIFY(encodeURIComponent(e))}`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${f.DOMAIN_DNS(encodeURIComponent(e))}`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${f.DOMAIN_RECORDS(encodeURIComponent(e))}`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${f.DOMAIN_SHARE(encodeURIComponent(e))}`,{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 s=k(i),r={};return e!==void 0&&(r.ttl=e),s!==void 0&&(r.labels=s),this.request(`${this.apiUrl}${f.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"Create token")}async listTokens(e){return this.request(`${this.apiUrl}${f.TOKENS}${ee(e)}`,{method:"GET"},"List tokens")}async deleteToken(e){return this.request(`${this.apiUrl}${f.TOKEN(encodeURIComponent(e))}`,{method:"DELETE"},"Delete token")}async getToken(e){return this.request(`${this.apiUrl}${f.TOKEN(encodeURIComponent(e))}`,{method:"GET"},"Get 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 this.request(`${this.apiUrl}${f.PING}`,{method:"GET"},"Ping")}async checkSPA(e,i={}){let s=e.find(o=>o.path===G.INDEX_FILE||o.path===`/${G.INDEX_FILE}`);if(!s||s.size>G.MAX_INDEX_BYTES)return!1;let r;if(typeof Buffer<"u"&&Buffer.isBuffer(s.content))r=s.content.toString("utf-8");else if(typeof Blob<"u"&&s.content instanceof Blob)r=await s.content.text();else if(typeof File<"u"&&s.content instanceof File)r=await s.content.text();else return!1;let l={files:e.map(o=>o.path),index:r};return(await this.request(`${this.apiUrl}${f.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)},"SPA check")).isSPA}};g();g();j();async function ct(){let n=JSON.stringify(ge,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await K(t);return{path:P,content:t,size:n.length,md5:e}}async function Pe(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===P))return n;try{if(await t.checkSPA(n,e)){let s=await ct();return[...n,s]}}catch{}return n}function Ne(n){let{getApi:t,ensureInit:e,processInput:i}=n;return{upload:async(s,r={})=>{if(await e(),!i)throw a.config("processInput function is not provided.");let l=t(),d=await i(s,r);return d=await Pe(d,l,r),l.deploy(d,r)},list:async s=>(await e(),t().listDeployments(s)),get:async s=>(await e(),t().getDeployment(s)),set:async(s,r)=>(await e(),t().updateDeploymentLabels(s,r.labels)),delete:async s=>(await e(),t().deleteDeployment(s))}}function Le(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,s={})=>(await e(),t().setDomain(i,s.deployment,s.labels)),list:async i=>(await e(),t().listDomains(i)),get:async i=>(await e(),t().getDomain(i)),delete:async i=>(await e(),t().deleteDomain(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 we(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function xe(n){let{getApi:t,ensureInit:e}=n;return{create:async(i={})=>(await e(),t().createToken(i.ttl,i.labels)),list:async i=>(await e(),t().listTokens(i)),get:async i=>(await e(),t().getToken(i)),delete:async i=>(await e(),t().deleteToken(i))}}var Y=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.credential=null;if(t={...t,apiUrl:t.apiUrl||void 0,token:t.token||void 0,caller:t.caller||void 0},this.clientOptions=t,t.caller!==void 0&&Ae(t.caller),t.token&&t.session)throw a.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(J(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new V({...t,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=Ne({...e,processInput:(i,s)=>this.processInput(i,s)}),this.domains=Le(e),this.account=we(e),this.tokens=xe(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({})}setToken(t){if(this.clientOptions.session)throw a.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw a.business("Invalid token provided. Token must be a non-empty string.");J(t),this.credential=t;return}if(typeof t!="function")throw a.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw a.authentication("Token provider returned no token.");if(typeof t!="string")throw a.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};$();g();import{z as ve}from"zod";import{z as be}from"zod";var Oe={apiUrl:be.string().url().optional(),token:be.string().min(1).optional()};$();var dt=ve.object(Oe).strict(),mt={apiUrl:F.API_URL,token:F.TOKEN};function Ce(){if(b()!=="node")return{};let n={apiUrl:process.env[F.API_URL]||void 0,token:process.env[F.TOKEN]||void 0};try{return dt.parse(n)}catch(t){if(t instanceof ve.ZodError){let e=t.issues[0],i=e.path[0],s=(i&&mt[i])??"SHIP environment configuration";throw a.config(`Invalid ${s}: ${e.message}`)}throw a.config("Invalid environment configuration")}}g();async function _e(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),{labels:r,via:l,password:d,flags:o,captcha:c}=t,p=new e,S=[];for(let u of n){if(!Buffer.isBuffer(u.content)&&!(typeof Blob<"u"&&u.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${u.path}`,{filePath:u.path});if(!u.md5)throw a.file(`File missing md5 checksum: ${u.path}`,{filePath:u.path});let h=new i([u.content],u.path,{type:"application/octet-stream"});p.append(R.FILES,h),S.push(u.md5)}p.append(R.CHECKSUMS,JSON.stringify(S)),r&&r.length>0&&p.append(R.LABELS,JSON.stringify(r)),l&&p.append(R.VIA,l),d&&p.append(R.PASSWORD,d),o?.build&&p.append(R.BUILD,"true"),o?.prerender&&p.append(R.PRERENDER,"true"),o?.spa&&p.append(R.SPA,"true"),c&&p.append(R.CAPTCHA,c);let O=new s(p),w=[];for await(let u of O.encode())w.push(Buffer.from(u));let N=Buffer.concat(w);return{body:N.buffer.slice(N.byteOffset,N.byteOffset+N.byteLength),headers:{"Content-Type":O.contentType,"Content-Length":Buffer.byteLength(N).toString()}}}g();g();se();$();ae();le();j();pe();function On(n,t,e,i=!0){let s=n===1?t:e;return i?`${n} ${s}`:s}ce();var ue=class extends Y{constructor(t={}){if(b()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=Ce();super({...t,apiUrl:t.apiUrl||e.apiUrl,token:t.token||(t.session?void 0:e.token)})}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(r=>typeof r=="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:s}=await Promise.resolve().then(()=>(ce(),Ge));return s(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return _e}},Et=ue;export{he as API_KEY,f as API_PATHS,Pt as AUTH_BASE_PATH,Rt as AccountPlan,V as ApiHttp,de as AuthMethod,Je as BLOCKED_EXTENSIONS,C as CALLER,Q as DEFAULT_API,P as DEPLOYMENT_CONFIG_FILENAME,R as DEPLOY_FIELDS,ye as DEPLOY_TOKEN,At as DeploymentStatus,je as DeploymentVia,Tt as DomainStatus,m as ErrorType,y as FILE_VALIDATION_STATUS,y as FileValidationStatus,M as IDEMPOTENCY_KEY_CONSTRAINTS,gt as JUNK_DIRECTORIES,L as LABEL_CONSTRAINTS,Se as LABEL_PATTERN,xt as MY_API_KEY_URL,Nt as OAuthScope,U as PASSWORD_CONSTRAINTS,bt as PUBLIC_DEPLOYMENT_TTL_SECONDS,F as SHIP_ENV,G as SPA_CHECK_CONSTRAINTS,ge as SPA_DEFAULT_CONFIG,ue as Ship,a as ShipError,x as TokenKind,W as UNBUILT_PROJECT_MARKERS,Ze as UNSAFE_FILENAME_CHARS,It as WEB_FILE_ACCEPT,rn as __setTestEnvironment,Rn as allValidFilesReady,Ee as assertShipJsonSyntax,K as calculateMD5,et as classifyToken,we as createAccountResource,Ne as createDeploymentResource,Le as createDomainResource,xe as createTokenResource,Et as default,kt as deserializeLabels,vt as extractSubdomain,$e as filterJunk,re as formatFileSize,Ct as generateDeploymentUrl,_t as generateDomainUrl,b as getENV,ht as getValidFiles,H as hasUnbuiltMarker,fe as hasUnsafeChars,B as isBlockedExtension,Ot as isCustomDomain,wt as isDeployment,Te as isPlatformDomain,_ as isShipError,St as normalizeVia,ke as optimizeDeployPaths,On as pluralize,He as processFilesForNode,Ft as serializeLabels,tt as validateApiKey,Lt as validateApiUrl,Ae as validateCaller,Me as validateDeployFile,Ue as validateDeployPath,nt as validateDeployToken,oe as validateFileName,Sn as validateFiles,me as validateIdempotencyKey,Z as validatePassword,J as validateToken};
2
2
  //# sourceMappingURL=index.js.map