@shipstatic/ship 0.7.1 → 0.7.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.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Le=Object.create;var U=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Be=Object.getPrototypeOf,Me=Object.prototype.hasOwnProperty;var A=(n,t)=>()=>(n&&(t=n(n=0)),t);var ve=(n,t)=>{for(var e in t)U(n,e,{get:t[e],enumerable:!0})},Ce=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ue(t))!Me.call(n,o)&&o!==e&&U(n,o,{get:()=>t[o],enumerable:!(i=_e(t,o))||i.enumerable});return n};var w=(n,t,e)=>(e=n!=null?Le(Be(n)):{},Ce(t||!n||!n.__esModule?U(e,"default",{value:n,enumerable:!0}):e,n)),Ke=n=>Ce(U({},"__esModule",{value:!0}),n);function x(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function N(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return we.has(e)}function qe(n){if(!n.startsWith(R))throw a.validation(`API key must start with "${R}"`);if(n.length!==Z)throw a.validation(`API key must be ${Z} characters total (${R} + ${B} hex chars)`);let t=n.slice(R.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`API key must contain ${B} hexadecimal characters after "${R}" prefix`)}function Ye(n){if(!n.startsWith(T))throw a.validation(`Deploy token must start with "${T}"`);if(n.length!==ee)throw a.validation(`Deploy token must be ${ee} characters total (${T} + ${M} hex chars)`);let t=n.slice(T.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`Deploy token must contain ${M} hexadecimal characters after "${T}" prefix`)}function We(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 x(t)?t:a.validation("API URL must be a valid URL")}}function Je(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(n)}function te(n,t){return n.endsWith(`.${t}`)}function Xe(n,t){return!te(n,t)}function Qe(n,t){return te(n,t)?n.slice(0,-(t.length+1)):null}function Ze(n,t){return`https://${n}.${t||"shipstatic.com"}`}function et(n){return`https://${n}`}function it(n){return!n||n.length===0?null:JSON.stringify(n)}function ot(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}var He,ze,Ve,f,Q,a,we,R,B,Z,Ge,T,M,ee,je,K,$,y,tt,nt,D=A(()=>{"use strict";He={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},ze={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Ve={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"};(function(n){n.Validation="validation_failed",n.NotFound="not_found",n.RateLimit="rate_limit_exceeded",n.Authentication="authentication_failed",n.Business="business_logic_error",n.Api="internal_server_error",n.Network="network_error",n.Cancelled="operation_cancelled",n.File="file_error",n.Config="config_error"})(f||(f={}));Q={client:new Set([f.Business,f.Config,f.File,f.Validation]),network:new Set([f.Network]),auth:new Set([f.Authentication])},a=class n extends Error{type;status;details;constructor(t,e,i,o){super(e),this.type=t,this.status=i,this.details=o,this.name="ShipError"}toResponse(){let t=this.type===f.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(f.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(f.NotFound,i,404)}static rateLimit(t="Too many requests"){return new n(f.RateLimit,t,429)}static authentication(t="Authentication required",e){return new n(f.Authentication,t,401,e)}static business(t,e=400){return new n(f.Business,t,e)}static network(t,e){return new n(f.Network,t,void 0,{cause:e})}static cancelled(t){return new n(f.Cancelled,t)}static file(t,e){return new n(f.File,t,void 0,{filePath:e})}static config(t,e){return new n(f.Config,t,void 0,e)}static api(t,e=500){return new n(f.Api,t,e)}static database(t,e=500){return new n(f.Api,t,e)}static storage(t,e=500){return new n(f.Api,t,e)}get filePath(){return this.details?.filePath}isClientError(){return Q.client.has(this.type)}isNetworkError(){return Q.network.has(this.type)}isAuthError(){return Q.auth.has(this.type)}isValidationError(){return this.type===f.Validation}isFileError(){return this.type===f.File}isConfigError(){return this.type===f.Config}isType(t){return this.type===t}};we=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"]);R="ship-",B=64,Z=R.length+B,Ge=4,T="token-",M=64,ee=T.length+M,je={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},K="ship.json";$="https://api.shipstatic.com",y={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};tt={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},nt=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function z(n){ne=n}function P(){if(ne===null)throw a.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ne}var ne,L=A(()=>{"use strict";D();ne=null});function rt(n){oe=n}function at(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function v(){return oe||at()}var oe,b=A(()=>{"use strict";oe=null});async function lt(n){let t=(await import("spark-md5")).default;return new Promise((e,i)=>{let s=Math.ceil(n.size/2097152),l=0,p=new t.ArrayBuffer,r=new FileReader,u=()=>{let c=l*2097152,d=Math.min(c+2097152,n.size);r.readAsArrayBuffer(n.slice(c,d))};r.onload=c=>{let d=c.target?.result;if(!d){i(a.business("Failed to read file chunk"));return}p.append(d),l++,l<s?u():e({md5:p.end()})},r.onerror=()=>{i(a.business("Failed to calculate MD5: FileReader error"))},u()})}async function pt(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,o)=>{let s=t.createHash("md5"),l=e.createReadStream(n);l.on("error",p=>o(a.business(`Failed to read file for MD5: ${p.message}`))),l.on("data",p=>s.update(p)),l.on("end",()=>i({md5:s.digest("hex")}))})}async function _(n){let t=v();if(t==="browser"){if(!(n instanceof Blob))throw a.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return lt(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 pt(n)}throw a.business("Unknown or unsupported execution environment for MD5 calculation.")}var G=A(()=>{"use strict";b();D()});function ce(n){return!n||n.length===0?[]:n.filter(t=>{if(!t)return!1;let e=t.replace(/\\/g,"/").split("/").filter(Boolean);if(e.length===0)return!0;let i=e[e.length-1];if((0,Ie.isJunk)(i))return!1;for(let s of e)if(s!==".well-known"&&(s.startsWith(".")||s.length>255))return!1;let o=e.slice(0,-1);for(let s of o)if(Pe.some(l=>s.toLowerCase()===l.toLowerCase()))return!1;return!0})}var Ie,Pe,ue=A(()=>{"use strict";Ie=require("junk"),Pe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function be(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=[],o=Math.min(...e.map(s=>s.length));for(let s=0;s<o;s++){let l=e[0][s];if(e.every(p=>p[s]===l))i.push(l);else break}return i.join("/")}function Y(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var de=A(()=>{"use strict"});function me(n,t={}){if(t.flatten===!1)return n.map(i=>({path:Y(i),name:fe(i)}));let e=mt(n);return n.map(i=>{let o=Y(i);if(e){let s=e.endsWith("/")?e:`${e}/`;o.startsWith(s)&&(o=o.substring(s.length))}return o||(o=fe(i)),{path:o,name:fe(i)}})}function mt(n){if(!n.length)return"";let e=n.map(s=>Y(s)).map(s=>s.split("/")),i=[],o=Math.min(...e.map(s=>s.length));for(let s=0;s<o-1;s++){let l=e[0][s];if(e.every(p=>p[s]===l))i.push(l);else break}return i.join("/")}function fe(n){return n.split(/[/\\]/).pop()||n}var he=A(()=>{"use strict";de()});function W(n,t=1){if(n===0)return"0 Bytes";let e=1024,i=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,o)).toFixed(t))+" "+i[o]}function J(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(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 e=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,i=n.split("/").pop()||n;return e.test(i)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function ht(n,t){let e=[],i=[],o=[];if(n.length===0){let r={file:"(no files)",message:"At least one file must be provided"};return e.push(r),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}if(n.length>t.maxFilesCount){let r={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(r),{files:n.map(u=>({...u,status:y.VALIDATION_FAILED,statusMessage:r.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let r of n){let u=y.READY,c="Ready for upload",d=r.name?J(r.name):{valid:!1,reason:"File name cannot be empty"};if(r.status===y.PROCESSING_ERROR)u=y.VALIDATION_FAILED,c=r.statusMessage||"File failed during processing",e.push({file:r.name,message:c});else if(r.size===0){u=y.EXCLUDED,c="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:r.name,message:c}),o.push({...r,status:u,statusMessage:c});continue}else r.size<0?(u=y.VALIDATION_FAILED,c="File size must be positive",e.push({file:r.name,message:c})):!r.name||r.name.trim().length===0?(u=y.VALIDATION_FAILED,c="File name cannot be empty",e.push({file:r.name||"(empty)",message:c})):r.name.includes("\0")?(u=y.VALIDATION_FAILED,c="File name contains invalid characters (null byte)",e.push({file:r.name,message:c})):d.valid?N(r.name)?(u=y.VALIDATION_FAILED,c=`File extension not allowed: "${r.name}"`,e.push({file:r.name,message:c})):r.size>t.maxFileSize?(u=y.VALIDATION_FAILED,c=`File size (${W(r.size)}) exceeds limit of ${W(t.maxFileSize)}`,e.push({file:r.name,message:c})):(s+=r.size,s>t.maxTotalSize&&(u=y.VALIDATION_FAILED,c=`Total size would exceed limit of ${W(t.maxTotalSize)}`,e.push({file:r.name,message:c}))):(u=y.VALIDATION_FAILED,c=d.reason||"Invalid file name",e.push({file:r.name,message:c}));o.push({...r,status:u,statusMessage:c})}e.length>0&&(o=o.map(r=>r.status===y.EXCLUDED?r:{...r,status:y.VALIDATION_FAILED,statusMessage:r.status===y.VALIDATION_FAILED?r.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=e.length===0?o.filter(r=>r.status===y.READY):[],p=e.length===0;return{files:o,validFiles:l,errors:e,warnings:i,canDeploy:p}}function Fe(n){return n.filter(t=>t.status===y.READY)}function yt(n){return Fe(n).length>0}var ye=A(()=>{"use strict";D()});function ge(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 De(n,t){let e=J(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if(N(n))throw a.business(`File extension not allowed: "${t}"`)}var Se=A(()=>{"use strict";D();ye()});var ke={};ve(ke,{processFilesForNode:()=>Ee});function Oe(n,t=new Set){let e=[],i=E.realpathSync(n);if(t.has(i))return e;t.add(i);let o=E.readdirSync(n);for(let s of o){let l=S.join(n,s),p=E.statSync(l);if(p.isDirectory()){let r=Oe(l,t);e.push(...r)}else p.isFile()&&e.push(l)}return e}async function Ee(n,t={}){if(v()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");let e=n.flatMap(h=>{let g=S.resolve(h);try{return E.statSync(g).isDirectory()?Oe(g):[g]}catch{throw a.file(`Path does not exist: ${h}`,h)}}),i=[...new Set(e)],o=ce(i);if(o.length===0)return[];let s=n.map(h=>S.resolve(h)),l=be(s.map(h=>{try{return E.statSync(h).isDirectory()?h:S.dirname(h)}catch{return S.dirname(h)}})),p=o.map(h=>{if(l&&l.length>0){let g=S.relative(l,h);if(g&&typeof g=="string"&&!g.startsWith(".."))return g.replace(/\\/g,"/")}return S.basename(h)}),r=me(p,{flatten:t.pathDetect!==!1}),u=[],c=0,d=P();for(let h=0;h<o.length;h++){let g=o[h],O=r[h].path;try{ge(O,g);let C=E.statSync(g);if(C.size===0)continue;if(De(O,g),C.size>d.maxFileSize)throw a.business(`File ${g} is too large. Maximum allowed size is ${d.maxFileSize/(1024*1024)}MB.`);if(c+=C.size,c>d.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${d.maxTotalSize/(1024*1024)}MB.`);let k=E.readFileSync(g),{md5:$e}=await _(k);u.push({path:O,content:k,size:k.length,md5:$e})}catch(C){if(x(C))throw C;let k=C instanceof Error?C.message:String(C);throw a.file(`Failed to read file "${g}": ${k}`,g)}}if(u.length>d.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return u}var E,S,Ae=A(()=>{"use strict";b();G();ue();Se();D();L();he();de();E=w(require("fs"),1),S=w(require("path"),1)});var gt={};ve(gt,{API_KEY_HEX_LENGTH:()=>B,API_KEY_HINT_LENGTH:()=>Ge,API_KEY_PREFIX:()=>R,API_KEY_TOTAL_LENGTH:()=>Z,AccountPlan:()=>Ve,ApiHttp:()=>I,AuthMethod:()=>je,BLOCKED_EXTENSIONS:()=>we,DEFAULT_API:()=>$,DEPLOYMENT_CONFIG_FILENAME:()=>K,DEPLOY_TOKEN_HEX_LENGTH:()=>M,DEPLOY_TOKEN_PREFIX:()=>T,DEPLOY_TOKEN_TOTAL_LENGTH:()=>ee,DeploymentStatus:()=>He,DomainStatus:()=>ze,ErrorType:()=>f,FILE_VALIDATION_STATUS:()=>y,FileValidationStatus:()=>y,JUNK_DIRECTORIES:()=>Pe,LABEL_CONSTRAINTS:()=>tt,LABEL_PATTERN:()=>nt,Ship:()=>X,ShipError:()=>a,__setTestEnvironment:()=>rt,allValidFilesReady:()=>yt,calculateMD5:()=>_,createAccountResource:()=>ae,createDeploymentResource:()=>se,createDomainResource:()=>re,createTokenResource:()=>le,default:()=>Ne,deserializeLabels:()=>ot,extractSubdomain:()=>Qe,filterJunk:()=>ce,formatFileSize:()=>W,generateDeploymentUrl:()=>Ze,generateDomainUrl:()=>et,getCurrentConfig:()=>P,getENV:()=>v,getValidFiles:()=>Fe,isBlockedExtension:()=>N,isCustomDomain:()=>Xe,isDeployment:()=>Je,isPlatformDomain:()=>te,isShipError:()=>x,loadConfig:()=>q,mergeDeployOptions:()=>ie,optimizeDeployPaths:()=>me,pluralize:()=>ft,processFilesForNode:()=>Ee,resolveConfig:()=>V,serializeLabels:()=>it,setPlatformConfig:()=>z,validateApiKey:()=>qe,validateApiUrl:()=>We,validateDeployFile:()=>De,validateDeployPath:()=>ge,validateDeployToken:()=>Ye,validateFileName:()=>J,validateFiles:()=>ht});module.exports=Ke(gt);D();var H=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 o=Array.from(i);for(let s of o)try{s(...e)}catch(l){i.delete(s),t!=="error"&&setTimeout(()=>{l instanceof Error?this.emit("error",l,String(t)):this.emit("error",new Error(String(l)),String(t))},0)}}transfer(t){this.handlers.forEach((e,i)=>{e.forEach(o=>{t.on(i,o)})})}clear(){this.handlers.clear()}};var m={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},st=3e4,I=class extends H{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||$,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??st,this.createDeployBody=e.createDeployBody}setGlobalHeaders(e){this.globalHeaders=e}transferEventsTo(e){this.transfer(e)}async executeRequest(e,i,o){let s=this.mergeHeaders(i.headers),{signal:l,cleanup:p}=this.createTimeoutSignal(i.signal),r={...i,headers:s,credentials:s.Authorization?void 0:"include",signal:l};this.emit("request",e,r);try{let u=await fetch(e,r);return p(),u.ok||await this.handleResponseError(u,o),this.emit("response",this.safeClone(u),e),{data:await this.parseResponse(this.safeClone(u)),status:u.status}}catch(u){p();let c=u instanceof Error?u:new Error(String(u));this.emit("error",c,e),this.handleFetchError(u,o)}}async request(e,i,o){let{data:s}=await this.executeRequest(e,i,o);return s}async requestWithStatus(e,i,o){return this.executeRequest(e,i,o)}mergeHeaders(e={}){return{...this.globalHeaders,...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let i=new AbortController,o=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(o)}}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 o={};try{if(e.headers.get("content-type")?.includes("application/json")){let p=await e.json();if(p&&typeof p=="object"){let r=p;typeof r.message=="string"&&(o.message=r.message),typeof r.error=="string"&&(o.error=r.error)}}else o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}let s=o.message||o.error||`${i} failed`;throw e.status===401?a.authentication(s):a.api(s,e.status)}handleFetchError(e,i){throw x(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);let{body:o,headers:s}=await this.createDeployBody(e,i.labels,i.via),l={};return i.deployToken?l.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(l.Authorization=`Bearer ${i.apiKey}`),i.caller&&(l["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${m.DEPLOYMENTS}`,{method:"POST",body:o,headers:{...s,...l},signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:i})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,o){let s={};i&&(s.deployment=i),o!==void 0&&(s.labels=o);let{data:l,status:p}=await this.requestWithStatus(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Set domain");return{...l,isCreate:p===201}}async listDomains(){return this.request(`${this.apiUrl}${m.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,i){let o={};return e!==void 0&&(o.ttl=e),i!==void 0&&(o.labels=i),this.request(`${this.apiUrl}${m.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${m.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${m.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${m.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${m.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${m.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e){let i=e.find(p=>p.path==="index.html"||p.path==="/index.html");if(!i||i.size>100*1024)return!1;let o;if(typeof Buffer<"u"&&Buffer.isBuffer(i.content))o=i.content.toString("utf-8");else if(typeof Blob<"u"&&i.content instanceof Blob)o=await i.content.text();else if(typeof File<"u"&&i.content instanceof File)o=await i.content.text();else return!1;let s={files:e.map(p=>p.path),index:o};return(await this.request(`${this.apiUrl}${m.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA check")).isSPA}};D();L();D();D();function V(n={},t={}){let e={apiUrl:n.apiUrl||t.apiUrl||$,apiKey:n.apiKey!==void 0?n.apiKey:t.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:t.deployToken},i={apiUrl:e.apiUrl};return e.apiKey!==void 0&&(i.apiKey=e.apiKey),e.deployToken!==void 0&&(i.deployToken=e.deployToken),i}function ie(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}D();G();async function ct(){let t=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),e;typeof Buffer<"u"?e=Buffer.from(t,"utf-8"):e=new Blob([t],{type:"application/json"});let{md5:i}=await _(e);return{path:K,content:e,size:t.length,md5:i}}async function xe(n,t,e){if(e.spaDetect===!1||n.some(i=>i.path===K))return n;try{if(await t.checkSPA(n)){let o=await ct();return[...n,o]}}catch{}return n}function se(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:o,hasAuth:s}=n;return{upload:async(l,p={})=>{await e();let r=o?ie(p,o):p;if(s&&!s()&&!r.deployToken&&!r.apiKey)throw a.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!i)throw a.config("processInput function is not provided.");let u=t(),c=await i(l,r);return c=await xe(c,u,r),u.deploy(c,r)},list:async()=>(await e(),t().listDeployments()),get:async l=>(await e(),t().getDeployment(l)),set:async(l,p)=>(await e(),t().updateDeploymentLabels(l,p.labels)),remove:async l=>{await e(),await t().removeDeployment(l)}}}function re(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,o={})=>(await e(),t().setDomain(i,o.deployment,o.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 ae(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function le(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 j=class{constructor(t={}){this.initPromise=null;this._config=null;this.auth=null;this.customHeaders={};this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let e=this.resolveInitialConfig(t);this.http=new I({...t,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=se({...i,processInput:(o,s)=>this.processInput(o,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=re(i),this._account=ae(i),this._tokens=le(i)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}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()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=P(),this._config)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.customHeaders=t,this.http.setGlobalHeaders(t)}clearHeaders(){this.customHeaders={},this.http.setGlobalHeaders({})}replaceHttpClient(t){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(t)}catch(e){console.warn("Event transfer failed during client replacement:",e)}this.http=t,Object.keys(this.customHeaders).length>0&&this.http.setGlobalHeaders(this.customHeaders)}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}};D();b();var F=require("zod");D();b();var pe="ship",ut=F.z.object({apiUrl:F.z.string().url().optional(),apiKey:F.z.string().optional(),deployToken:F.z.string().optional()}).strict();function Re(n){try{return ut.parse(n)}catch(t){if(t instanceof F.z.ZodError){let e=t.issues[0],i=e.path.length>0?` at ${e.path.join(".")}`:"";throw a.config(`Configuration validation failed${i}: ${e.message}`)}throw a.config("Configuration validation failed")}}async function dt(n){try{if(v()!=="node")return{};let{cosmiconfigSync:t}=await import("cosmiconfig"),e=await import("os"),i=t(pe,{searchPlaces:[`.${pe}rc`,"package.json",`${e.homedir()}/.${pe}rc`],stopDir:e.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return Re(o.config)}catch(t){if(x(t))throw t}return{}}async function q(n){if(v()!=="node")return{};let t={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},e=await dt(n),i={apiUrl:t.apiUrl??e.apiUrl,apiKey:t.apiKey??e.apiKey,deployToken:t.deployToken??e.deployToken};return Re(i)}L();D();async function Te(n,t,e){let{FormData:i,File:o}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),l=new i,p=[];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 h=new o([d.content],d.path,{type:"application/octet-stream"});l.append("files[]",h),p.push(d.md5)}l.append("checksums",JSON.stringify(p)),t&&t.length>0&&l.append("labels",JSON.stringify(t)),e&&l.append("via",e);let r=new s(l),u=[];for await(let d of r.encode())u.push(Buffer.from(d));let c=Buffer.concat(u);return{body:c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength),headers:{"Content-Type":r.contentType,"Content-Length":Buffer.byteLength(c).toString()}}}G();function ft(n,t,e,i=!0){let o=n===1?t:e;return i?`${n} ${o}`:o}ue();he();b();ye();Se();D();L();Ae();var X=class extends j{constructor(t={}){if(v()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");super(t)}resolveInitialConfig(t){return V(t,{})}async loadFullConfig(){try{let t=await q(this.clientOptions.configFile),e=V(this.clientOptions,t);e.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(e.deployToken):e.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(e.apiKey);let i=new I({...this.clientOptions,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();z(o)}catch(t){throw this.initPromise=null,t}}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:o}=await Promise.resolve().then(()=>(Ae(),ke));return o(i,e)}getDeployBodyCreator(){return Te}},Ne=X;0&&(module.exports={API_KEY_HEX_LENGTH,API_KEY_HINT_LENGTH,API_KEY_PREFIX,API_KEY_TOTAL_LENGTH,AccountPlan,ApiHttp,AuthMethod,BLOCKED_EXTENSIONS,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_TOKEN_HEX_LENGTH,DEPLOY_TOKEN_PREFIX,DEPLOY_TOKEN_TOTAL_LENGTH,DeploymentStatus,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,Ship,ShipError,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getCurrentConfig,getENV,getValidFiles,isBlockedExtension,isCustomDomain,isDeployment,isPlatformDomain,isShipError,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,serializeLabels,setPlatformConfig,validateApiKey,validateApiUrl,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles});
1
+ "use strict";var Le=Object.create;var U=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Be=Object.getPrototypeOf,Me=Object.prototype.hasOwnProperty;var A=(n,t)=>()=>(n&&(t=n(n=0)),t);var ve=(n,t)=>{for(var e in t)U(n,e,{get:t[e],enumerable:!0})},Ce=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ue(t))!Me.call(n,o)&&o!==e&&U(n,o,{get:()=>t[o],enumerable:!(i=_e(t,o))||i.enumerable});return n};var T=(n,t,e)=>(e=n!=null?Le(Be(n)):{},Ce(t||!n||!n.__esModule?U(e,"default",{value:n,enumerable:!0}):e,n)),Ke=n=>Ce(U({},"__esModule",{value:!0}),n);function w(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function N(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return Te.has(e)}function qe(n){if(!n.startsWith(R))throw l.validation(`API key must start with "${R}"`);if(n.length!==Z)throw l.validation(`API key must be ${Z} characters total (${R} + ${B} hex chars)`);let t=n.slice(R.length);if(!/^[a-f0-9]{64}$/i.test(t))throw l.validation(`API key must contain ${B} hexadecimal characters after "${R}" prefix`)}function Ye(n){if(!n.startsWith(x))throw l.validation(`Deploy token must start with "${x}"`);if(n.length!==ee)throw l.validation(`Deploy token must be ${ee} characters total (${x} + ${M} hex chars)`);let t=n.slice(x.length);if(!/^[a-f0-9]{64}$/i.test(t))throw l.validation(`Deploy token must contain ${M} hexadecimal characters after "${x}" prefix`)}function We(n){try{let t=new URL(n);if(!["http:","https:"].includes(t.protocol))throw l.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw l.validation("API URL must not contain a path");if(t.search||t.hash)throw l.validation("API URL must not contain query parameters or fragments")}catch(t){throw w(t)?t:l.validation("API URL must be a valid URL")}}function Je(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(n)}function te(n,t){return n.endsWith(`.${t}`)}function Xe(n,t){return!te(n,t)}function Qe(n,t){return te(n,t)?n.slice(0,-(t.length+1)):null}function Ze(n,t){return`https://${n}.${t||"shipstatic.com"}`}function et(n){return`https://${n}`}function it(n){return!n||n.length===0?null:JSON.stringify(n)}function ot(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}var He,ze,Ve,f,Q,l,Te,R,B,Z,Ge,x,M,ee,je,K,$,y,tt,nt,D=A(()=>{"use strict";He={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},ze={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Ve={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"};(function(n){n.Validation="validation_failed",n.NotFound="not_found",n.RateLimit="rate_limit_exceeded",n.Authentication="authentication_failed",n.Business="business_logic_error",n.Api="internal_server_error",n.Network="network_error",n.Cancelled="operation_cancelled",n.File="file_error",n.Config="config_error"})(f||(f={}));Q={client:new Set([f.Business,f.Config,f.File,f.Validation]),network:new Set([f.Network]),auth:new Set([f.Authentication])},l=class n extends Error{type;status;details;constructor(t,e,i,o){super(e),this.type=t,this.status=i,this.details=o,this.name="ShipError"}toResponse(){let t=this.type===f.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(f.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(f.NotFound,i,404)}static rateLimit(t="Too many requests"){return new n(f.RateLimit,t,429)}static authentication(t="Authentication required",e){return new n(f.Authentication,t,401,e)}static business(t,e=400){return new n(f.Business,t,e)}static network(t,e){return new n(f.Network,t,void 0,{cause:e})}static cancelled(t){return new n(f.Cancelled,t)}static file(t,e){return new n(f.File,t,void 0,{filePath:e})}static config(t,e){return new n(f.Config,t,void 0,e)}static api(t,e=500){return new n(f.Api,t,e)}static database(t,e=500){return new n(f.Api,t,e)}static storage(t,e=500){return new n(f.Api,t,e)}get filePath(){return this.details?.filePath}isClientError(){return Q.client.has(this.type)}isNetworkError(){return Q.network.has(this.type)}isAuthError(){return Q.auth.has(this.type)}isValidationError(){return this.type===f.Validation}isFileError(){return this.type===f.File}isConfigError(){return this.type===f.Config}isType(t){return this.type===t}};Te=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"]);R="ship-",B=64,Z=R.length+B,Ge=4,x="token-",M=64,ee=x.length+M,je={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},K="ship.json";$="https://api.shipstatic.com",y={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};tt={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},nt=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function z(n){ne=n}function P(){if(ne===null)throw l.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ne}var ne,L=A(()=>{"use strict";D();ne=null});function at(n){oe=n}function lt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function v(){return oe||lt()}var oe,b=A(()=>{"use strict";oe=null});async function pt(n){let t=(await import("spark-md5")).default;return new Promise((e,i)=>{let s=Math.ceil(n.size/2097152),a=0,c=new t.ArrayBuffer,r=new FileReader,d=()=>{let p=a*2097152,u=Math.min(p+2097152,n.size);r.readAsArrayBuffer(n.slice(p,u))};r.onload=p=>{let u=p.target?.result;if(!u){i(l.business("Failed to read file chunk"));return}c.append(u),a++,a<s?d():e({md5:c.end()})},r.onerror=()=>{i(l.business("Failed to calculate MD5: FileReader error"))},d()})}async function ct(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,o)=>{let s=t.createHash("md5"),a=e.createReadStream(n);a.on("error",c=>o(l.business(`Failed to read file for MD5: ${c.message}`))),a.on("data",c=>s.update(c)),a.on("end",()=>i({md5:s.digest("hex")}))})}async function _(n){let t=v();if(t==="browser"){if(!(n instanceof Blob))throw l.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return pt(n)}if(t==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw l.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return ct(n)}throw l.business("Unknown or unsupported execution environment for MD5 calculation.")}var G=A(()=>{"use strict";b();D()});function ce(n){return!n||n.length===0?[]:n.filter(t=>{if(!t)return!1;let e=t.replace(/\\/g,"/").split("/").filter(Boolean);if(e.length===0)return!0;let i=e[e.length-1];if((0,Ie.isJunk)(i))return!1;for(let s of e)if(s!==".well-known"&&(s.startsWith(".")||s.length>255))return!1;let o=e.slice(0,-1);for(let s of o)if(Pe.some(a=>s.toLowerCase()===a.toLowerCase()))return!1;return!0})}var Ie,Pe,ue=A(()=>{"use strict";Ie=require("junk"),Pe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function be(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=[],o=Math.min(...e.map(s=>s.length));for(let s=0;s<o;s++){let a=e[0][s];if(e.every(c=>c[s]===a))i.push(a);else break}return i.join("/")}function Y(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var de=A(()=>{"use strict"});function me(n,t={}){if(t.flatten===!1)return n.map(i=>({path:Y(i),name:fe(i)}));let e=ht(n);return n.map(i=>{let o=Y(i);if(e){let s=e.endsWith("/")?e:`${e}/`;o.startsWith(s)&&(o=o.substring(s.length))}return o||(o=fe(i)),{path:o,name:fe(i)}})}function ht(n){if(!n.length)return"";let e=n.map(s=>Y(s)).map(s=>s.split("/")),i=[],o=Math.min(...e.map(s=>s.length));for(let s=0;s<o-1;s++){let a=e[0][s];if(e.every(c=>c[s]===a))i.push(a);else break}return i.join("/")}function fe(n){return n.split(/[/\\]/).pop()||n}var he=A(()=>{"use strict";de()});function W(n,t=1){if(n===0)return"0 Bytes";let e=1024,i=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,o)).toFixed(t))+" "+i[o]}function J(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(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 e=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,i=n.split("/").pop()||n;return e.test(i)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function yt(n,t){let e=[],i=[],o=[];if(n.length===0){let r={file:"(no files)",message:"At least one file must be provided"};return e.push(r),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}if(n.length>t.maxFilesCount){let r={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(r),{files:n.map(d=>({...d,status:y.VALIDATION_FAILED,statusMessage:r.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let r of n){let d=y.READY,p="Ready for upload",u=r.name?J(r.name):{valid:!1,reason:"File name cannot be empty"};if(r.status===y.PROCESSING_ERROR)d=y.VALIDATION_FAILED,p=r.statusMessage||"File failed during processing",e.push({file:r.name,message:p});else if(r.size===0){d=y.EXCLUDED,p="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:r.name,message:p}),o.push({...r,status:d,statusMessage:p});continue}else r.size<0?(d=y.VALIDATION_FAILED,p="File size must be positive",e.push({file:r.name,message:p})):!r.name||r.name.trim().length===0?(d=y.VALIDATION_FAILED,p="File name cannot be empty",e.push({file:r.name||"(empty)",message:p})):r.name.includes("\0")?(d=y.VALIDATION_FAILED,p="File name contains invalid characters (null byte)",e.push({file:r.name,message:p})):u.valid?N(r.name)?(d=y.VALIDATION_FAILED,p=`File extension not allowed: "${r.name}"`,e.push({file:r.name,message:p})):r.size>t.maxFileSize?(d=y.VALIDATION_FAILED,p=`File size (${W(r.size)}) exceeds limit of ${W(t.maxFileSize)}`,e.push({file:r.name,message:p})):(s+=r.size,s>t.maxTotalSize&&(d=y.VALIDATION_FAILED,p=`Total size would exceed limit of ${W(t.maxTotalSize)}`,e.push({file:r.name,message:p}))):(d=y.VALIDATION_FAILED,p=u.reason||"Invalid file name",e.push({file:r.name,message:p}));o.push({...r,status:d,statusMessage:p})}e.length>0&&(o=o.map(r=>r.status===y.EXCLUDED?r:{...r,status:y.VALIDATION_FAILED,statusMessage:r.status===y.VALIDATION_FAILED?r.statusMessage:"Deployment failed due to validation errors in bundle"}));let a=e.length===0?o.filter(r=>r.status===y.READY):[],c=e.length===0;return{files:o,validFiles:a,errors:e,warnings:i,canDeploy:c}}function Fe(n){return n.filter(t=>t.status===y.READY)}function gt(n){return Fe(n).length>0}var ye=A(()=>{"use strict";D()});function ge(n,t){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw l.business(`Security error: Unsafe file path "${n}" for file: ${t}`)}function De(n,t){let e=J(n);if(!e.valid)throw l.business(e.reason||"Invalid file name");if(N(n))throw l.business(`File extension not allowed: "${t}"`)}var Se=A(()=>{"use strict";D();ye()});var ke={};ve(ke,{processFilesForNode:()=>Ee});function Oe(n,t=new Set){let e=[],i=E.realpathSync(n);if(t.has(i))return e;t.add(i);let o=E.readdirSync(n);for(let s of o){let a=S.join(n,s),c=E.statSync(a);if(c.isDirectory()){let r=Oe(a,t);e.push(...r)}else c.isFile()&&e.push(a)}return e}async function Ee(n,t={}){if(v()!=="node")throw l.business("processFilesForNode can only be called in Node.js environment.");let e=n.flatMap(h=>{let g=S.resolve(h);try{return E.statSync(g).isDirectory()?Oe(g):[g]}catch{throw l.file(`Path does not exist: ${h}`,h)}}),i=[...new Set(e)],o=ce(i);if(o.length===0)return[];let s=n.map(h=>S.resolve(h)),a=be(s.map(h=>{try{return E.statSync(h).isDirectory()?h:S.dirname(h)}catch{return S.dirname(h)}})),c=o.map(h=>{if(a&&a.length>0){let g=S.relative(a,h);if(g&&typeof g=="string"&&!g.startsWith(".."))return g.replace(/\\/g,"/")}return S.basename(h)}),r=me(c,{flatten:t.pathDetect!==!1}),d=[],p=0,u=P();for(let h=0;h<o.length;h++){let g=o[h],O=r[h].path;try{ge(O,g);let C=E.statSync(g);if(C.size===0)continue;if(De(O,g),C.size>u.maxFileSize)throw l.business(`File ${g} is too large. Maximum allowed size is ${u.maxFileSize/(1024*1024)}MB.`);if(p+=C.size,p>u.maxTotalSize)throw l.business(`Total deploy size is too large. Maximum allowed is ${u.maxTotalSize/(1024*1024)}MB.`);let k=E.readFileSync(g),{md5:$e}=await _(k);d.push({path:O,content:k,size:k.length,md5:$e})}catch(C){if(w(C))throw C;let k=C instanceof Error?C.message:String(C);throw l.file(`Failed to read file "${g}": ${k}`,g)}}if(d.length>u.maxFilesCount)throw l.business(`Too many files to deploy. Maximum allowed is ${u.maxFilesCount} files.`);return d}var E,S,Ae=A(()=>{"use strict";b();G();ue();Se();D();L();he();de();E=T(require("fs"),1),S=T(require("path"),1)});var Dt={};ve(Dt,{API_KEY_HEX_LENGTH:()=>B,API_KEY_HINT_LENGTH:()=>Ge,API_KEY_PREFIX:()=>R,API_KEY_TOTAL_LENGTH:()=>Z,AccountPlan:()=>Ve,ApiHttp:()=>I,AuthMethod:()=>je,BLOCKED_EXTENSIONS:()=>Te,DEFAULT_API:()=>$,DEPLOYMENT_CONFIG_FILENAME:()=>K,DEPLOY_TOKEN_HEX_LENGTH:()=>M,DEPLOY_TOKEN_PREFIX:()=>x,DEPLOY_TOKEN_TOTAL_LENGTH:()=>ee,DeploymentStatus:()=>He,DomainStatus:()=>ze,ErrorType:()=>f,FILE_VALIDATION_STATUS:()=>y,FileValidationStatus:()=>y,JUNK_DIRECTORIES:()=>Pe,LABEL_CONSTRAINTS:()=>tt,LABEL_PATTERN:()=>nt,Ship:()=>X,ShipError:()=>l,__setTestEnvironment:()=>at,allValidFilesReady:()=>gt,calculateMD5:()=>_,createAccountResource:()=>ae,createDeploymentResource:()=>se,createDomainResource:()=>re,createTokenResource:()=>le,default:()=>Ne,deserializeLabels:()=>ot,extractSubdomain:()=>Qe,filterJunk:()=>ce,formatFileSize:()=>W,generateDeploymentUrl:()=>Ze,generateDomainUrl:()=>et,getCurrentConfig:()=>P,getENV:()=>v,getValidFiles:()=>Fe,isBlockedExtension:()=>N,isCustomDomain:()=>Xe,isDeployment:()=>Je,isPlatformDomain:()=>te,isShipError:()=>w,loadConfig:()=>q,mergeDeployOptions:()=>ie,optimizeDeployPaths:()=>me,pluralize:()=>mt,processFilesForNode:()=>Ee,resolveConfig:()=>V,serializeLabels:()=>it,setPlatformConfig:()=>z,validateApiKey:()=>qe,validateApiUrl:()=>We,validateDeployFile:()=>De,validateDeployPath:()=>ge,validateDeployToken:()=>Ye,validateFileName:()=>J,validateFiles:()=>yt});module.exports=Ke(Dt);D();var H=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 o=Array.from(i);for(let s of o)try{s(...e)}catch(a){i.delete(s),t!=="error"&&setTimeout(()=>{a instanceof Error?this.emit("error",a,String(t)):this.emit("error",new Error(String(a)),String(t))},0)}}transfer(t){this.handlers.forEach((e,i)=>{e.forEach(o=>{t.on(i,o)})})}clear(){this.handlers.clear()}};var m={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},st=3e4,rt=6e4,I=class extends H{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||$,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??st,this.createDeployBody=e.createDeployBody}setGlobalHeaders(e){this.globalHeaders=e}transferEventsTo(e){this.transfer(e)}async executeRequest(e,i,o,s){let a=this.mergeHeaders(i.headers),{signal:c,cleanup:r}=this.createTimeoutSignal(i.signal,s),d={...i,headers:a,credentials:a.Authorization?void 0:"include",signal:c};this.emit("request",e,d);try{let p=await fetch(e,d);return r(),p.ok||await this.handleResponseError(p,o),this.emit("response",this.safeClone(p),e),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(p){r();let u=p instanceof Error?p:new Error(String(p));this.emit("error",u,e),this.handleFetchError(p,o)}}async request(e,i,o,s){let{data:a}=await this.executeRequest(e,i,o,s);return a}async requestWithStatus(e,i,o){return this.executeRequest(e,i,o)}mergeHeaders(e={}){return{...this.globalHeaders,...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e,i){let o=new AbortController,s=setTimeout(()=>o.abort(),i??this.timeout);if(e){let a=()=>o.abort();e.addEventListener("abort",a),e.aborted&&o.abort()}return{signal:o.signal,cleanup:()=>clearTimeout(s)}}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 o={};try{if(e.headers.get("content-type")?.includes("application/json")){let c=await e.json();if(c&&typeof c=="object"){let r=c;typeof r.message=="string"&&(o.message=r.message),typeof r.error=="string"&&(o.error=r.error)}}else o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}let s=o.message||o.error||`${i} failed`;throw e.status===401?l.authentication(s):l.api(s,e.status)}handleFetchError(e,i){throw w(e)?e:e instanceof Error&&e.name==="AbortError"?l.cancelled(`${i} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?l.network(`${i} failed: ${e.message}`,e):e instanceof Error?l.business(`${i} failed: ${e.message}`):l.business(`${i} failed: Unknown error`)}async deploy(e,i={}){if(!e.length)throw l.business("No files to deploy");for(let c of e)if(!c.md5)throw l.file(`MD5 checksum missing for file: ${c.path}`,c.path);let{body:o,headers:s}=await this.createDeployBody(e,i.labels,i.via),a={};return i.deployToken?a.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(a.Authorization=`Bearer ${i.apiKey}`),i.caller&&(a["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${m.DEPLOYMENTS}`,{method:"POST",body:o,headers:{...s,...a},signal:i.signal||null},"Deploy",rt)}async listDeployments(){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:i})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,o){let s={};i&&(s.deployment=i),o!==void 0&&(s.labels=o);let{data:a,status:c}=await this.requestWithStatus(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Set domain");return{...a,isCreate:c===201}}async listDomains(){return this.request(`${this.apiUrl}${m.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,i){let o={};return e!==void 0&&(o.ttl=e),i!==void 0&&(o.labels=i),this.request(`${this.apiUrl}${m.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${m.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${m.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${m.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${m.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${m.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e){let i=e.find(c=>c.path==="index.html"||c.path==="/index.html");if(!i||i.size>100*1024)return!1;let o;if(typeof Buffer<"u"&&Buffer.isBuffer(i.content))o=i.content.toString("utf-8");else if(typeof Blob<"u"&&i.content instanceof Blob)o=await i.content.text();else if(typeof File<"u"&&i.content instanceof File)o=await i.content.text();else return!1;let s={files:e.map(c=>c.path),index:o};return(await this.request(`${this.apiUrl}${m.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA check")).isSPA}};D();L();D();D();function V(n={},t={}){let e={apiUrl:n.apiUrl||t.apiUrl||$,apiKey:n.apiKey!==void 0?n.apiKey:t.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:t.deployToken},i={apiUrl:e.apiUrl};return e.apiKey!==void 0&&(i.apiKey=e.apiKey),e.deployToken!==void 0&&(i.deployToken=e.deployToken),i}function ie(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}D();G();async function ut(){let t=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),e;typeof Buffer<"u"?e=Buffer.from(t,"utf-8"):e=new Blob([t],{type:"application/json"});let{md5:i}=await _(e);return{path:K,content:e,size:t.length,md5:i}}async function we(n,t,e){if(e.spaDetect===!1||n.some(i=>i.path===K))return n;try{if(await t.checkSPA(n)){let o=await ut();return[...n,o]}}catch{}return n}function se(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:o,hasAuth:s}=n;return{upload:async(a,c={})=>{await e();let r=o?ie(c,o):c;if(s&&!s()&&!r.deployToken&&!r.apiKey)throw l.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!i)throw l.config("processInput function is not provided.");let d=t(),p=await i(a,r);return p=await we(p,d,r),d.deploy(p,r)},list:async()=>(await e(),t().listDeployments()),get:async a=>(await e(),t().getDeployment(a)),set:async(a,c)=>(await e(),t().updateDeploymentLabels(a,c.labels)),remove:async a=>{await e(),await t().removeDeployment(a)}}}function re(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,o={})=>(await e(),t().setDomain(i,o.deployment,o.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 ae(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function le(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 j=class{constructor(t={}){this.initPromise=null;this._config=null;this.auth=null;this.customHeaders={};this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let e=this.resolveInitialConfig(t);this.http=new I({...t,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=se({...i,processInput:(o,s)=>this.processInput(o,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=re(i),this._account=ae(i),this._tokens=le(i)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}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()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=P(),this._config)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.customHeaders=t,this.http.setGlobalHeaders(t)}clearHeaders(){this.customHeaders={},this.http.setGlobalHeaders({})}replaceHttpClient(t){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(t)}catch(e){console.warn("Event transfer failed during client replacement:",e)}this.http=t,Object.keys(this.customHeaders).length>0&&this.http.setGlobalHeaders(this.customHeaders)}setDeployToken(t){if(!t||typeof t!="string")throw l.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:t}}setApiKey(t){if(!t||typeof t!="string")throw l.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:t}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};D();b();var F=require("zod");D();b();var pe="ship",dt=F.z.object({apiUrl:F.z.string().url().optional(),apiKey:F.z.string().optional(),deployToken:F.z.string().optional()}).strict();function Re(n){try{return dt.parse(n)}catch(t){if(t instanceof F.z.ZodError){let e=t.issues[0],i=e.path.length>0?` at ${e.path.join(".")}`:"";throw l.config(`Configuration validation failed${i}: ${e.message}`)}throw l.config("Configuration validation failed")}}async function ft(n){try{if(v()!=="node")return{};let{cosmiconfigSync:t}=await import("cosmiconfig"),e=await import("os"),i=t(pe,{searchPlaces:[`.${pe}rc`,"package.json",`${e.homedir()}/.${pe}rc`],stopDir:e.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return Re(o.config)}catch(t){if(w(t))throw t}return{}}async function q(n){if(v()!=="node")return{};let t={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},e=await ft(n),i={apiUrl:t.apiUrl??e.apiUrl,apiKey:t.apiKey??e.apiKey,deployToken:t.deployToken??e.deployToken};return Re(i)}L();D();async function xe(n,t,e){let{FormData:i,File:o}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),a=new i,c=[];for(let u of n){if(!Buffer.isBuffer(u.content)&&!(typeof Blob<"u"&&u.content instanceof Blob))throw l.file(`Unsupported file.content type for Node.js: ${u.path}`,u.path);if(!u.md5)throw l.file(`File missing md5 checksum: ${u.path}`,u.path);let h=new o([u.content],u.path,{type:"application/octet-stream"});a.append("files[]",h),c.push(u.md5)}a.append("checksums",JSON.stringify(c)),t&&t.length>0&&a.append("labels",JSON.stringify(t)),e&&a.append("via",e);let r=new s(a),d=[];for await(let u of r.encode())d.push(Buffer.from(u));let p=Buffer.concat(d);return{body:p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength),headers:{"Content-Type":r.contentType,"Content-Length":Buffer.byteLength(p).toString()}}}G();function mt(n,t,e,i=!0){let o=n===1?t:e;return i?`${n} ${o}`:o}ue();he();b();ye();Se();D();L();Ae();var X=class extends j{constructor(t={}){if(v()!=="node")throw l.business("Node.js Ship class can only be used in Node.js environment.");super(t)}resolveInitialConfig(t){return V(t,{})}async loadFullConfig(){try{let t=await q(this.clientOptions.configFile),e=V(this.clientOptions,t);e.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(e.deployToken):e.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(e.apiKey);let i=new I({...this.clientOptions,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();z(o)}catch(t){throw this.initPromise=null,t}}async processInput(t,e){let i=typeof t=="string"?[t]:t;if(!Array.isArray(i)||!i.every(s=>typeof s=="string"))throw l.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw l.business("No files to deploy.");let{processFilesForNode:o}=await Promise.resolve().then(()=>(Ae(),ke));return o(i,e)}getDeployBodyCreator(){return xe}},Ne=X;0&&(module.exports={API_KEY_HEX_LENGTH,API_KEY_HINT_LENGTH,API_KEY_PREFIX,API_KEY_TOTAL_LENGTH,AccountPlan,ApiHttp,AuthMethod,BLOCKED_EXTENSIONS,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_TOKEN_HEX_LENGTH,DEPLOY_TOKEN_PREFIX,DEPLOY_TOKEN_TOTAL_LENGTH,DeploymentStatus,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,Ship,ShipError,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getCurrentConfig,getENV,getValidFiles,isBlockedExtension,isCustomDomain,isDeployment,isPlatformDomain,isShipError,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,serializeLabels,setPlatformConfig,validateApiKey,validateApiUrl,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles});
2
2
 
3
3
  // Ship SDK: Enable axios-style CommonJS imports
4
4
  const originalExports = module.exports;