@shipstatic/ship 0.8.13 → 0.8.14

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.
@@ -97,7 +97,7 @@ _ship_completions() {
97
97
 
98
98
  # Flag completion
99
99
  if [[ "$current_word" == --* ]]; then
100
- completions="--api-key --deploy-token --config --api-url --label --no-path-detect --no-spa-detect --json --no-color --version --help"
100
+ completions="--api-key --deploy-token --config --api-url --label --password --no-path-detect --no-spa-detect --json --no-color --version --help"
101
101
  COMPREPLY=( $(compgen -W "${completions}" -- "${current_word}") )
102
102
  return
103
103
  fi
@@ -46,6 +46,7 @@ complete -c ship -l deploy-token -d 'Deploy token for single-use deployments' -x
46
46
  complete -c ship -l config -d 'Custom config file path' -r
47
47
  complete -c ship -l api-url -d 'API URL (for development)' -x
48
48
  complete -c ship -l label -d 'Label (can be repeated)' -x
49
+ complete -c ship -l password -d 'Password-protect this deployment' -x
49
50
  complete -c ship -l json -d 'Output results in JSON format'
50
51
  complete -c ship -l no-color -d 'Disable colored output'
51
52
  complete -c ship -l no-path-detect -d 'Disable automatic path optimization and flattening'
@@ -103,7 +103,7 @@ if [[ -n ${ZSH_VERSION-} ]]; then
103
103
 
104
104
  # Flag completion
105
105
  if [[ "$current_word" == --* ]]; then
106
- completions=("--api-key:API key for authentication" "--deploy-token:Deploy token for single-use deployments" "--config:Custom config file path" "--api-url:API URL (for development)" "--label:Label (can be repeated)" "--no-path-detect:Disable automatic path optimization and flattening" "--no-spa-detect:Disable automatic SPA detection and configuration" "--json:Output results in JSON format" "--no-color:Disable colored output" "--version:Show version information" "--help:Display help for command")
106
+ completions=("--api-key:API key for authentication" "--deploy-token:Deploy token for single-use deployments" "--config:Custom config file path" "--api-url:API URL (for development)" "--label:Label (can be repeated)" "--password:Password-protect this deployment" "--no-path-detect:Disable automatic path optimization and flattening" "--no-spa-detect:Disable automatic SPA detection and configuration" "--json:Output results in JSON format" "--no-color:Disable colored output" "--version:Show version information" "--help:Display help for command")
107
107
  _describe 'options' completions
108
108
  return
109
109
  fi
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var je=Object.create;var z=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var Ge=Object.getOwnPropertyNames;var qe=Object.getPrototypeOf,Ye=Object.prototype.hasOwnProperty;var R=(n,t)=>()=>(n&&(t=n(n=0)),t);var Ie=(n,t)=>{for(var e in t)z(n,e,{get:t[e],enumerable:!0})},Pe=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ge(t))!Ye.call(n,o)&&o!==e&&z(n,o,{get:()=>t[o],enumerable:!(i=Ve(t,o))||i.enumerable});return n};var x=(n,t,e)=>(e=n!=null?je(qe(n)):{},Pe(t||!n||!n.__esModule?z(e,"default",{value:n,enumerable:!0}):e,n)),We=n=>Pe(z({},"__esModule",{value:!0}),n);function T(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function L(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return Fe.has(e)}function se(n){return Oe.test(n)}function U(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>V.has(e))}function tt(n){if(!n.startsWith(b))throw a.validation(`API key must start with "${b}"`);if(n.length!==oe)throw a.validation(`API key must be ${oe} characters total (${b} + ${H} hex chars)`);let t=n.slice(b.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`API key must contain ${H} hexadecimal characters after "${b}" prefix`)}function nt(n){if(!n.startsWith(I))throw a.validation(`Deploy token must start with "${I}"`);if(n.length!==re)throw a.validation(`Deploy token must be ${re} characters total (${I} + ${j} hex chars)`);let t=n.slice(I.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`Deploy token must contain ${j} hexadecimal characters after "${I}" prefix`)}function it(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)?t:a.validation("API URL must be a valid URL")}}function ot(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function le(n,t){return n.endsWith(`.${t}`)}function rt(n,t){return!le(n,t)}function st(n,t){return le(n,t)?n.slice(0,-(t.length+1)):null}function at(n){return`https://${n}`}function lt(n){return`https://${n}`}function ut(n){return!n||n.length===0?null:JSON.stringify(n)}function dt(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}var Je,Xe,Qe,f,ie,a,Fe,Oe,V,b,H,oe,Ze,I,j,re,et,G,ae,_,g,pt,ct,S=R(()=>{"use strict";Je={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Xe={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Qe={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={}));ie={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 ie.client.has(this.type)}isNetworkError(){return ie.network.has(this.type)}isAuthError(){return ie.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}};Fe=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);Oe=/[\x00-\x1f\x7f#?%\\<>"]/;V=new Set(["node_modules","package.json"]);b="ship-",H=64,oe=b.length+H,Ze=4,I="token-",j=64,re=I.length+j,et={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},G="ship.json",ae={rewrites:[{source:"/(.*)",destination:"/index.html"}]};_="https://api.shipstatic.com",g={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};pt={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},ct=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function Y(n){pe=n}function O(){if(pe===null)throw a.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return pe}var pe,B=R(()=>{"use strict";S();pe=null});function mt(n){ue=n}function ht(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function w(){return ue||ht()}var ue,k=R(()=>{"use strict";ue=null});async function yt(n){let t=(await import("spark-md5")).default;return new Promise((e,i)=>{let r=Math.ceil(n.size/2097152),l=0,p=new t.ArrayBuffer,s=new FileReader,c=()=>{let u=l*2097152,m=Math.min(u+2097152,n.size);s.readAsArrayBuffer(n.slice(u,m))};s.onload=u=>{let m=u.target?.result;if(!m){i(a.business("Failed to read file chunk"));return}p.append(m),l++,l<r?c():e({md5:p.end()})},s.onerror=()=>{i(a.business("Failed to calculate MD5: FileReader error"))},c()})}async function gt(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 r=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=>r.update(p)),l.on("end",()=>i({md5:r.digest("hex")}))})}async function M(n){let t=w();if(t==="browser"){if(!(n instanceof Blob))throw a.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return yt(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 gt(n)}throw a.business("Unknown or unsupported execution environment for MD5 calculation.")}var J=R(()=>{"use strict";k();S()});function ge(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&U(i)))throw a.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return n.filter(e=>{if(!e)return!1;let i=e.replace(/\\/g,"/").split("/").filter(Boolean);if(i.length===0)return!0;let o=i[i.length-1];if((0,Le.isJunk)(o))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(Ue.some(p=>l.toLowerCase()===p.toLowerCase()))return!1;return!0})}var Le,Ue,De=R(()=>{"use strict";Le=require("junk");S();Ue=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function _e(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=[],o=Math.min(...e.map(r=>r.length));for(let r=0;r<o;r++){let l=e[0][r];if(e.every(p=>p[r]===l))i.push(l);else break}return i.join("/")}function Z(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Se=R(()=>{"use strict"});function Ae(n,t={}){if(t.flatten===!1)return n.map(i=>({path:Z(i),name:Ee(i)}));let e=Ct(n);return n.map(i=>{let o=Z(i);if(e){let r=e.endsWith("/")?e:`${e}/`;o.startsWith(r)&&(o=o.substring(r.length))}return o||(o=Ee(i)),{path:o,name:Ee(i)}})}function Ct(n){if(!n.length)return"";let e=n.map(r=>Z(r)).map(r=>r.split("/")),i=[],o=Math.min(...e.map(r=>r.length));for(let r=0;r<o-1;r++){let l=e[0][r];if(e.every(p=>p[r]===l))i.push(l);else break}return i.join("/")}function Ee(n){return n.split(/[/\\]/).pop()||n}var Ce=R(()=>{"use strict";Se()});function ee(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 te(n){if(se(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 vt(n,t){let e=[],i=[],o=[];if(n.length===0){let s={file:"(no files)",message:"At least one file must be provided"};return e.push(s),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let s of n)if(U(s.name))return e.push({file:s.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(c=>({...c,status:g.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let s={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(s),{files:n.map(c=>({...c,status:g.VALIDATION_FAILED,statusMessage:s.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let r=0;for(let s of n){let c=g.READY,u="Ready for upload",m=s.name?te(s.name):{valid:!1,reason:"File name cannot be empty"};if(s.status===g.PROCESSING_ERROR)c=g.VALIDATION_FAILED,u=s.statusMessage||"File failed during processing",e.push({file:s.name,message:u});else if(s.size===0){c=g.EXCLUDED,u="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:s.name,message:u}),o.push({...s,status:c,statusMessage:u});continue}else s.size<0?(c=g.VALIDATION_FAILED,u="File size must be positive",e.push({file:s.name,message:u})):!s.name||s.name.trim().length===0?(c=g.VALIDATION_FAILED,u="File name cannot be empty",e.push({file:s.name||"(empty)",message:u})):s.name.includes("\0")?(c=g.VALIDATION_FAILED,u="File name contains invalid characters (null byte)",e.push({file:s.name,message:u})):m.valid?L(s.name)?(c=g.VALIDATION_FAILED,u=`File extension not allowed: "${s.name}"`,e.push({file:s.name,message:u})):s.size>t.maxFileSize?(c=g.VALIDATION_FAILED,u=`File size (${ee(s.size)}) exceeds limit of ${ee(t.maxFileSize)}`,e.push({file:s.name,message:u})):(r+=s.size,r>t.maxTotalSize&&(c=g.VALIDATION_FAILED,u=`Total size would exceed limit of ${ee(t.maxTotalSize)}`,e.push({file:s.name,message:u}))):(c=g.VALIDATION_FAILED,u=m.reason||"Invalid file name",e.push({file:s.name,message:u}));o.push({...s,status:c,statusMessage:u})}e.length>0&&(o=o.map(s=>s.status===g.EXCLUDED?s:{...s,status:g.VALIDATION_FAILED,statusMessage:s.status===g.VALIDATION_FAILED?s.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=e.length===0?o.filter(s=>s.status===g.READY):[],p=e.length===0;return{files:o,validFiles:l,errors:e,warnings:i,canDeploy:p}}function Be(n){return n.filter(t=>t.status===g.READY)}function Tt(n){return Be(n).length>0}var ve=R(()=>{"use strict";S()});function Te(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 Re(n,t){let e=te(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if(L(n))throw a.business(`File extension not allowed: "${t}"`)}var we=R(()=>{"use strict";S();ve()});var Ke={};Ie(Ke,{processFilesForNode:()=>xe});function Me(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 r of o){let l=A.join(n,r),p=E.statSync(l);if(p.isDirectory()){let s=Me(l,t);e.push(...s)}else p.isFile()&&e.push(l)}return e}async function xe(n,t={}){if(w()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let d of n){let y=A.resolve(d);try{if(E.statSync(y).isDirectory()){let C=E.readdirSync(y).find(v=>V.has(v));if(C)throw a.business(`"${C}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(C){if(T(C))throw C}}let e=n.flatMap(d=>{let y=A.resolve(d);try{return E.statSync(y).isDirectory()?Me(y):[y]}catch{throw a.file(`Path does not exist: ${d}`,d)}}),i=[...new Set(e)],o=n.map(d=>A.resolve(d)),r=_e(o.map(d=>{try{return E.statSync(d).isDirectory()?d:A.dirname(d)}catch{return A.dirname(d)}})),l=i.map(d=>{if(r&&r.length>0){let y=A.relative(r,d);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return A.basename(d)}),s=Ae(l,{flatten:t.pathDetect!==!1}).map(d=>d.path),c=new Set(ge(s));if(c.size===0)return[];let u=[],m=[];for(let d=0;d<i.length;d++)c.has(s[d])&&(u.push(i[d]),m.push(s[d]));let D=[],K=0,F=O();for(let d=0;d<u.length;d++){let y=u[d],C=m[d];try{Te(C,y);let v=E.statSync(y);if(v.size===0)continue;if(Re(C,y),v.size>F.maxFileSize)throw a.business(`File ${y} is too large. Maximum allowed size is ${F.maxFileSize/(1024*1024)}MB.`);if(K+=v.size,K>F.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${F.maxTotalSize/(1024*1024)}MB.`);let $=E.readFileSync(y),{md5:He}=await M($);D.push({path:C,content:$,size:$.length,md5:He})}catch(v){if(T(v))throw v;let $=v instanceof Error?v.message:String(v);throw a.file(`Failed to read file "${y}": ${$}`,y)}}if(D.length>F.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${F.maxFilesCount} files.`);return D}var E,A,be=R(()=>{"use strict";k();J();De();we();S();B();Ce();Se();E=x(require("fs"),1),A=x(require("path"),1)});var Rt={};Ie(Rt,{API_KEY_HEX_LENGTH:()=>H,API_KEY_HINT_LENGTH:()=>Ze,API_KEY_PREFIX:()=>b,API_KEY_TOTAL_LENGTH:()=>oe,AccountPlan:()=>Qe,ApiHttp:()=>P,AuthMethod:()=>et,BLOCKED_EXTENSIONS:()=>Fe,DEFAULT_API:()=>_,DEPLOYMENT_CONFIG_FILENAME:()=>G,DEPLOY_TOKEN_HEX_LENGTH:()=>j,DEPLOY_TOKEN_PREFIX:()=>I,DEPLOY_TOKEN_TOTAL_LENGTH:()=>re,DeploymentStatus:()=>Je,DomainStatus:()=>Xe,ErrorType:()=>f,FILE_VALIDATION_STATUS:()=>g,FileValidationStatus:()=>g,JUNK_DIRECTORIES:()=>Ue,LABEL_CONSTRAINTS:()=>pt,LABEL_PATTERN:()=>ct,SPA_DEFAULT_CONFIG:()=>ae,Ship:()=>ne,ShipError:()=>a,UNBUILT_PROJECT_MARKERS:()=>V,UNSAFE_FILENAME_CHARS:()=>Oe,__setTestEnvironment:()=>mt,allValidFilesReady:()=>Tt,calculateMD5:()=>M,createAccountResource:()=>me,createDeploymentResource:()=>de,createDomainResource:()=>fe,createTokenResource:()=>he,default:()=>ze,deserializeLabels:()=>dt,extractSubdomain:()=>st,filterJunk:()=>ge,formatFileSize:()=>ee,generateDeploymentUrl:()=>at,generateDomainUrl:()=>lt,getCurrentConfig:()=>O,getENV:()=>w,getValidFiles:()=>Be,hasUnbuiltMarker:()=>U,hasUnsafeChars:()=>se,isBlockedExtension:()=>L,isCustomDomain:()=>rt,isDeployment:()=>ot,isPlatformDomain:()=>le,isShipError:()=>T,loadConfig:()=>Q,mergeDeployOptions:()=>ce,optimizeDeployPaths:()=>Ae,pluralize:()=>At,processFilesForNode:()=>xe,resolveConfig:()=>W,serializeLabels:()=>ut,setPlatformConfig:()=>Y,validateApiKey:()=>tt,validateApiUrl:()=>it,validateDeployFile:()=>Re,validateDeployPath:()=>Te,validateDeployToken:()=>nt,validateFileName:()=>te,validateFiles:()=>vt});module.exports=We(Rt);S();var q=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 r of o)try{r(...e)}catch(l){i.delete(r),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 h={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},ft=3e4,P=class extends q{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||_,this.getAuthHeadersCallback=e.getAuthHeaders,this.useCredentials=e.useCredentials??!1,this.timeout=e.timeout??ft,this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||h.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}transferEventsTo(e){this.transfer(e)}async executeRequest(e,i,o){let r=this.mergeHeaders(i.headers),{signal:l,cleanup:p}=this.createTimeoutSignal(i.signal),s={...i,headers:r,credentials:this.useCredentials&&!r.Authorization?"include":void 0,signal:l};this.emit("request",e,s);try{let c=await fetch(e,s);return p(),c.ok||await this.handleResponseError(c,o),this.emit("response",this.safeClone(c),e),{data:await this.parseResponse(this.safeClone(c)),status:c.status}}catch(c){p();let u=c instanceof Error?c:new Error(String(c));this.emit("error",u,e),this.handleFetchError(c,o)}}async request(e,i,o){let{data:r}=await this.executeRequest(e,i,o);return r}async requestWithStatus(e,i,o){return this.executeRequest(e,i,o)}mergeHeaders(e={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...e}}createTimeoutSignal(e){let i=new AbortController,o=setTimeout(()=>i.abort(),this.timeout);if(e){let r=()=>i.abort();e.addEventListener("abort",r),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 s=p;typeof s.message=="string"&&(o.message=s.message),typeof s.error=="string"&&(o.error=s.error)}}else o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}let r=o.message||o.error||`${i} failed`;throw e.status===401?a.authentication(r):e.status===429?a.rateLimit(r):a.api(r,e.status)}handleFetchError(e,i){throw T(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 s of e)if(!s.md5)throw a.file(`MD5 checksum missing for file: ${s.path}`,s.path);let o=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:r,headers:l}=await this.createDeployBody(e,i.labels,i.via,o),p={};return i.deployToken?p.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(p.Authorization=`Bearer ${i.apiKey}`),i.caller&&(p["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:r,headers:{...l,...p},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){return this.request(`${this.apiUrl}${h.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}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,o){let r={};i&&(r.deployment=i),o!==void 0&&(r.labels=o);let{data:l,status:p}=await this.requestWithStatus(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"Set domain");return{...l,isCreate:p===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 o={};return e!==void 0&&(o.ttl=e),i!==void 0&&(o.labels=i),this.request(`${this.apiUrl}${h.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"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 fetchAgentToken(){return this.request(`${this.apiUrl}${h.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent token")}async getAccount(){return this.request(`${this.apiUrl}${h.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${h.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${h.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e,i={}){let o=e.find(c=>c.path==="index.html"||c.path==="/index.html");if(!o||o.size>100*1024)return!1;let r;if(typeof Buffer<"u"&&Buffer.isBuffer(o.content))r=o.content.toString("utf-8");else if(typeof Blob<"u"&&o.content instanceof Blob)r=await o.content.text();else if(typeof File<"u"&&o.content instanceof File)r=await o.content.text();else return!1;let l={"Content-Type":"application/json"};i.deployToken?l.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(l.Authorization=`Bearer ${i.apiKey}`);let p={files:e.map(c=>c.path),index:r};return(await this.request(`${this.apiUrl}${h.SPA_CHECK}`,{method:"POST",headers:l,body:JSON.stringify(p)},"SPA check")).isSPA}};S();B();S();S();function W(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 ce(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}S();J();async function Dt(){let n=JSON.stringify(ae,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await M(t);return{path:G,content:t,size:n.length,md5:e}}async function ke(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===G))return n;try{if(await t.checkSPA(n,e)){let o=await Dt();return[...n,o]}}catch{}return n}function de(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:o,hasAuth:r}=n;return{upload:async(l,p={})=>{await e();let s=o?ce(p,o):p;if(r&&!r()&&!s.deployToken&&!s.apiKey)try{let m=t(),{secret:D}=await m.fetchAgentToken();s.deployToken=D}catch(m){throw T(m)&&m.type===f.RateLimit?a.rateLimit("public deploy rate limit exceeded, try again later or run 'ship config' for a free account with higher limits"):m}if(!i)throw a.config("processInput function is not provided.");let c=t(),u=await i(l,s);return u=await ke(u,c,s),c.deploy(u,s)},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 fe(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 me(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function he(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 X=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 P({...t,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=de({...i,processInput:(o,r)=>this.processInput(o,r),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=fe(i),this._account=me(i),this._tokens=he(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=O(),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}};S();k();var N=require("zod");S();k();var ye="ship",St=N.z.object({apiUrl:N.z.string().url().optional(),apiKey:N.z.string().min(1).optional(),deployToken:N.z.string().min(1).optional()}).strict();function Ne(n){try{return St.parse(n)}catch(t){if(t instanceof N.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 Et(n){try{if(w()!=="node")return{};let{cosmiconfigSync:t}=await import("cosmiconfig"),e=await import("os"),i=t(ye,{searchPlaces:[`.${ye}rc`,"package.json",`${e.homedir()}/.${ye}rc`],stopDir:e.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return Ne(o.config)}catch(t){if(T(t))throw t}return{}}async function Q(n){if(w()!=="node")return{};let t={apiUrl:process.env.SHIP_API_URL||void 0,apiKey:process.env.SHIP_API_KEY||void 0,deployToken:process.env.SHIP_DEPLOY_TOKEN||void 0},e=await Et(n),i={apiUrl:t.apiUrl??e.apiUrl,apiKey:t.apiKey??e.apiKey,deployToken:t.deployToken??e.deployToken};return Ne(i)}B();S();async function $e(n,t,e,i){let{FormData:o,File:r}=await import("formdata-node"),{FormDataEncoder:l}=await import("form-data-encoder"),p=new o,s=[];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 K=new r([D.content],D.path,{type:"application/octet-stream"});p.append("files[]",K),s.push(D.md5)}p.append("checksums",JSON.stringify(s)),t&&t.length>0&&p.append("labels",JSON.stringify(t)),e&&p.append("via",e),i?.build&&p.append("build","true"),i?.prerender&&p.append("prerender","true"),i?.spa&&p.append("spa","true");let c=new l(p),u=[];for await(let D of c.encode())u.push(Buffer.from(D));let m=Buffer.concat(u);return{body:m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength),headers:{"Content-Type":c.contentType,"Content-Length":Buffer.byteLength(m).toString()}}}J();function At(n,t,e,i=!0){let o=n===1?t:e;return i?`${n} ${o}`:o}De();Ce();k();ve();we();S();B();be();var ne=class extends X{constructor(t={}){if(w()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");super(t)}resolveInitialConfig(t){return W(t,{})}async loadFullConfig(){try{let t=await Q(this.clientOptions.configFile),e=W(this.clientOptions,t);e.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(e.deployToken):e.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(e.apiKey);let i=new P({...this.clientOptions,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();Y(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(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:o}=await Promise.resolve().then(()=>(be(),Ke));return o(i,e)}getDeployBodyCreator(){return $e}},ze=ne;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,SPA_DEFAULT_CONFIG,Ship,ShipError,UNBUILT_PROJECT_MARKERS,UNSAFE_FILENAME_CHARS,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getCurrentConfig,getENV,getValidFiles,hasUnbuiltMarker,hasUnsafeChars,isBlockedExtension,isCustomDomain,isDeployment,isPlatformDomain,isShipError,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,serializeLabels,setPlatformConfig,validateApiKey,validateApiUrl,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles});
1
+ "use strict";var We=Object.create;var j=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var Qe=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty;var C=(n,t)=>()=>(n&&(t=n(n=0)),t);var Fe=(n,t)=>{for(var e in t)j(n,e,{get:t[e],enumerable:!0})},ke=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Je(t))!Ze.call(n,o)&&o!==e&&j(n,o,{get:()=>t[o],enumerable:!(i=Xe(t,o))||i.enumerable});return n};var x=(n,t,e)=>(e=n!=null?We(Qe(n)):{},ke(t||!n||!n.__esModule?j(e,"default",{value:n,enumerable:!0}):e,n)),et=n=>ke(j({},"__esModule",{value:!0}),n);function v(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function M(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return Le.has(e)}function pe(n){return $e.test(n)}function B(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>Y.has(e))}function st(n){if(!n.startsWith(O))throw a.validation(`API key must start with "${O}"`);if(n.length!==ae)throw a.validation(`API key must be ${ae} characters total (${O} + ${V} hex chars)`);let t=n.slice(O.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`API key must contain ${V} hexadecimal characters after "${O}" prefix`)}function at(n){if(!n.startsWith(N))throw a.validation(`Deploy token must start with "${N}"`);if(n.length!==le)throw a.validation(`Deploy token must be ${le} characters total (${N} + ${q} hex chars)`);let t=n.slice(N.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`Deploy token must contain ${q} hexadecimal characters after "${N}" prefix`)}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 v(t)?t:a.validation("API URL must be a valid URL")}}function pt(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function ue(n,t){return n.endsWith(`.${t}`)}function ct(n,t){return!ue(n,t)}function ut(n,t){return ue(n,t)?n.slice(0,-(t.length+1)):null}function dt(n){return`https://${n}`}function ft(n){return`https://${n}`}function mt(n){return!n||n.length===0?null:JSON.stringify(n)}function ht(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}var tt,nt,it,f,se,a,Le,$e,Y,O,V,ae,ot,N,q,le,rt,W,ce,H,y,b,de,k,S=C(()=>{"use strict";tt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},nt={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},it={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={}));se={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 se.client.has(this.type)}isNetworkError(){return se.network.has(this.type)}isAuthError(){return se.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}};Le=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"]);$e=/[\x00-\x1f\x7f#?%\\<>"]/;Y=new Set(["node_modules","package.json"]);O="ship-",V=64,ae=O.length+V,ot=4,N="token-",q=64,le=N.length+q,rt={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},W="ship.json",ce={rewrites:[{source:"/(.*)",destination:"/index.html"}]};H="https://api.shipstatic.com",y={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};b={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},de=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;k={MIN_LENGTH:6,MAX_LENGTH:128}});function J(n){fe=n}function L(){if(fe===null)throw a.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return fe}var fe,z=C(()=>{"use strict";S();fe=null});function gt(n){he=n}function Dt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function R(){return he||Dt()}var he,$=C(()=>{"use strict";he=null});async function St(n){let t=(await import("spark-md5")).default;return new Promise((e,i)=>{let r=Math.ceil(n.size/2097152),l=0,c=new t.ArrayBuffer,s=new FileReader,p=()=>{let u=l*2097152,g=Math.min(u+2097152,n.size);s.readAsArrayBuffer(n.slice(u,g))};s.onload=u=>{let g=u.target?.result;if(!g){i(a.business("Failed to read file chunk"));return}c.append(g),l++,l<r?p():e({md5:c.end()})},s.onerror=()=>{i(a.business("Failed to calculate MD5: FileReader error"))},p()})}async function Et(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 r=t.createHash("md5"),l=e.createReadStream(n);l.on("error",c=>o(a.business(`Failed to read file for MD5: ${c.message}`))),l.on("data",c=>r.update(c)),l.on("end",()=>i({md5:r.digest("hex")}))})}async function G(n){let t=R();if(t==="browser"){if(!(n instanceof Blob))throw a.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return St(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 Et(n)}throw a.business("Unknown or unsupported execution environment for MD5 calculation.")}var Z=C(()=>{"use strict";$();S()});function Ae(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&B(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 o=i[i.length-1];if((0,He.isJunk)(o))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(Ke.some(c=>l.toLowerCase()===c.toLowerCase()))return!1;return!0})}var He,Ke,we=C(()=>{"use strict";He=require("junk");S();Ke=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function ze(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=[],o=Math.min(...e.map(r=>r.length));for(let r=0;r<o;r++){let l=e[0][r];if(e.every(c=>c[r]===l))i.push(l);else break}return i.join("/")}function ne(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Te=C(()=>{"use strict"});function Ce(n,t={}){if(t.flatten===!1)return n.map(i=>({path:ne(i),name:ve(i)}));let e=Ct(n);return n.map(i=>{let o=ne(i);if(e){let r=e.endsWith("/")?e:`${e}/`;o.startsWith(r)&&(o=o.substring(r.length))}return o||(o=ve(i)),{path:o,name:ve(i)}})}function Ct(n){if(!n.length)return"";let e=n.map(r=>ne(r)).map(r=>r.split("/")),i=[],o=Math.min(...e.map(r=>r.length));for(let r=0;r<o-1;r++){let l=e[0][r];if(e.every(c=>c[r]===l))i.push(l);else break}return i.join("/")}function ve(n){return n.split(/[/\\]/).pop()||n}var Re=C(()=>{"use strict";Te()});function ie(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 oe(n){if(pe(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 Rt(n,t){let e=[],i=[],o=[];if(n.length===0){let s={file:"(no files)",message:"At least one file must be provided"};return e.push(s),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let s of n)if(B(s.name))return e.push({file:s.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 s={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(s),{files:n.map(p=>({...p,status:y.VALIDATION_FAILED,statusMessage:s.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let r=0;for(let s of n){let p=y.READY,u="Ready for upload",g=s.name?oe(s.name):{valid:!1,reason:"File name cannot be empty"};if(s.status===y.PROCESSING_ERROR)p=y.VALIDATION_FAILED,u=s.statusMessage||"File failed during processing",e.push({file:s.name,message:u});else if(s.size===0){p=y.EXCLUDED,u="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:s.name,message:u}),o.push({...s,status:p,statusMessage:u});continue}else s.size<0?(p=y.VALIDATION_FAILED,u="File size must be positive",e.push({file:s.name,message:u})):!s.name||s.name.trim().length===0?(p=y.VALIDATION_FAILED,u="File name cannot be empty",e.push({file:s.name||"(empty)",message:u})):s.name.includes("\0")?(p=y.VALIDATION_FAILED,u="File name contains invalid characters (null byte)",e.push({file:s.name,message:u})):g.valid?M(s.name)?(p=y.VALIDATION_FAILED,u=`File extension not allowed: "${s.name}"`,e.push({file:s.name,message:u})):s.size>t.maxFileSize?(p=y.VALIDATION_FAILED,u=`File size (${ie(s.size)}) exceeds limit of ${ie(t.maxFileSize)}`,e.push({file:s.name,message:u})):(r+=s.size,r>t.maxTotalSize&&(p=y.VALIDATION_FAILED,u=`Total size would exceed limit of ${ie(t.maxTotalSize)}`,e.push({file:s.name,message:u}))):(p=y.VALIDATION_FAILED,u=g.reason||"Invalid file name",e.push({file:s.name,message:u}));o.push({...s,status:p,statusMessage:u})}e.length>0&&(o=o.map(s=>s.status===y.EXCLUDED?s:{...s,status:y.VALIDATION_FAILED,statusMessage:s.status===y.VALIDATION_FAILED?s.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=e.length===0?o.filter(s=>s.status===y.READY):[],c=e.length===0;return{files:o,validFiles:l,errors:e,warnings:i,canDeploy:c}}function Ge(n){return n.filter(t=>t.status===y.READY)}function xt(n){return Ge(n).length>0}var xe=C(()=>{"use strict";S()});function be(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 Ie(n,t){let e=oe(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if(M(n))throw a.business(`File extension not allowed: "${t}"`)}var Pe=C(()=>{"use strict";S();xe()});var Ve={};Fe(Ve,{processFilesForNode:()=>Oe});function je(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 r of o){let l=A.join(n,r),c=E.statSync(l);if(c.isDirectory()){let s=je(l,t);e.push(...s)}else c.isFile()&&e.push(l)}return e}async function Oe(n,t={}){if(R()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let d of n){let h=A.resolve(d);try{if(E.statSync(h).isDirectory()){let w=E.readdirSync(h).find(T=>Y.has(T));if(w)throw a.business(`"${w}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(w){if(v(w))throw w}}let e=n.flatMap(d=>{let h=A.resolve(d);try{return E.statSync(h).isDirectory()?je(h):[h]}catch{throw a.file(`Path does not exist: ${d}`,d)}}),i=[...new Set(e)],o=n.map(d=>A.resolve(d)),r=ze(o.map(d=>{try{return E.statSync(d).isDirectory()?d:A.dirname(d)}catch{return A.dirname(d)}})),l=i.map(d=>{if(r&&r.length>0){let h=A.relative(r,d);if(h&&typeof h=="string"&&!h.startsWith(".."))return h.replace(/\\/g,"/")}return A.basename(d)}),s=Ce(l,{flatten:t.pathDetect!==!1}).map(d=>d.path),p=new Set(Ae(s));if(p.size===0)return[];let u=[],g=[];for(let d=0;d<i.length;d++)p.has(s[d])&&(u.push(i[d]),g.push(s[d]));let I=[],P=0,D=L();for(let d=0;d<u.length;d++){let h=u[d],w=g[d];try{be(w,h);let T=E.statSync(h);if(T.size===0)continue;if(Ie(w,h),T.size>D.maxFileSize)throw a.business(`File ${h} is too large. Maximum allowed size is ${D.maxFileSize/(1024*1024)}MB.`);if(P+=T.size,P>D.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${D.maxTotalSize/(1024*1024)}MB.`);let U=E.readFileSync(h),{md5:Ye}=await G(U);I.push({path:w,content:U,size:U.length,md5:Ye})}catch(T){if(v(T))throw T;let U=T instanceof Error?T.message:String(T);throw a.file(`Failed to read file "${h}": ${U}`,h)}}if(I.length>D.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${D.maxFilesCount} files.`);return I}var E,A,Ne=C(()=>{"use strict";$();Z();we();Pe();S();z();Re();Te();E=x(require("fs"),1),A=x(require("path"),1)});var bt={};Fe(bt,{API_KEY_HEX_LENGTH:()=>V,API_KEY_HINT_LENGTH:()=>ot,API_KEY_PREFIX:()=>O,API_KEY_TOTAL_LENGTH:()=>ae,AccountPlan:()=>it,ApiHttp:()=>F,AuthMethod:()=>rt,BLOCKED_EXTENSIONS:()=>Le,DEFAULT_API:()=>H,DEPLOYMENT_CONFIG_FILENAME:()=>W,DEPLOY_TOKEN_HEX_LENGTH:()=>q,DEPLOY_TOKEN_PREFIX:()=>N,DEPLOY_TOKEN_TOTAL_LENGTH:()=>le,DeploymentStatus:()=>tt,DomainStatus:()=>nt,ErrorType:()=>f,FILE_VALIDATION_STATUS:()=>y,FileValidationStatus:()=>y,JUNK_DIRECTORIES:()=>Ke,LABEL_CONSTRAINTS:()=>b,LABEL_PATTERN:()=>de,PASSWORD_CONSTRAINTS:()=>k,SPA_DEFAULT_CONFIG:()=>ce,Ship:()=>re,ShipError:()=>a,UNBUILT_PROJECT_MARKERS:()=>Y,UNSAFE_FILENAME_CHARS:()=>$e,__setTestEnvironment:()=>gt,allValidFilesReady:()=>xt,calculateMD5:()=>G,createAccountResource:()=>De,createDeploymentResource:()=>ye,createDomainResource:()=>ge,createTokenResource:()=>Se,default:()=>qe,deserializeLabels:()=>ht,extractSubdomain:()=>ut,filterJunk:()=>Ae,formatFileSize:()=>ie,generateDeploymentUrl:()=>dt,generateDomainUrl:()=>ft,getCurrentConfig:()=>L,getENV:()=>R,getValidFiles:()=>Ge,hasUnbuiltMarker:()=>B,hasUnsafeChars:()=>pe,isBlockedExtension:()=>M,isCustomDomain:()=>ct,isDeployment:()=>pt,isPlatformDomain:()=>ue,isShipError:()=>v,loadConfig:()=>te,mergeDeployOptions:()=>me,optimizeDeployPaths:()=>Ce,pluralize:()=>vt,processFilesForNode:()=>Oe,resolveConfig:()=>Q,serializeLabels:()=>mt,setPlatformConfig:()=>J,validateApiKey:()=>st,validateApiUrl:()=>lt,validateDeployFile:()=>Ie,validateDeployPath:()=>be,validateDeployToken:()=>at,validateFileName:()=>oe,validateFiles:()=>Rt});module.exports=et(bt);S();var X=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 r of o)try{r(...e)}catch(l){i.delete(r),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()}};S();function _e(n){if(n!=null){if(typeof n!="string")throw a.validation("Password must be a string");if(n.length<k.MIN_LENGTH||n.length>k.MAX_LENGTH)throw a.validation(`Password must be between ${k.MIN_LENGTH} and ${k.MAX_LENGTH} characters`)}}function K(n){if(n==null)return;if(n.length===0)return n;if(n.length>b.MAX_COUNT)throw a.validation(`Maximum ${b.MAX_COUNT} labels allowed`);let t=n.map((i,o)=>{if(typeof i!="string")throw a.validation(`Label at index ${o} must be a string`);let r=i.trim().toLowerCase();if(r.length<b.MIN_LENGTH)throw a.validation(`Labels must be at least ${b.MIN_LENGTH} characters long`);if(r.length>b.MAX_LENGTH)throw a.validation(`Labels must be no more than ${b.MAX_LENGTH} characters long`);if(!de.test(r))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${b.SEPARATORS}) between segments`);return r}),e=[...new Set(t)];if(e.length!==t.length)throw a.validation("Duplicate labels are not allowed");return e}var m={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},yt=3e4,F=class extends X{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||H,this.getAuthHeadersCallback=e.getAuthHeaders,this.useCredentials=e.useCredentials??!1,this.timeout=e.timeout??yt,this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||m.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}transferEventsTo(e){this.transfer(e)}async executeRequest(e,i,o){let r=this.mergeHeaders(i.headers),{signal:l,cleanup:c}=this.createTimeoutSignal(i.signal),s={...i,headers:r,credentials:this.useCredentials&&!r.Authorization?"include":void 0,signal:l};this.emit("request",e,s);try{let p=await fetch(e,s);return c(),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){c();let u=p instanceof Error?p:new Error(String(p));this.emit("error",u,e),this.handleFetchError(p,o)}}async request(e,i,o){let{data:r}=await this.executeRequest(e,i,o);return r}async requestWithStatus(e,i,o){return this.executeRequest(e,i,o)}mergeHeaders(e={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...e}}createTimeoutSignal(e){let i=new AbortController,o=setTimeout(()=>i.abort(),this.timeout);if(e){let r=()=>i.abort();e.addEventListener("abort",r),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 c=await e.json();if(c&&typeof c=="object"){let s=c;typeof s.message=="string"&&(o.message=s.message),typeof s.error=="string"&&(o.error=s.error)}}else o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}let r=o.message||o.error||`${i} failed`;throw e.status===401?a.authentication(r):e.status===429?a.rateLimit(r):a.api(r,e.status)}handleFetchError(e,i){throw v(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);_e(i.password);let o=K(i.labels),r=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:l,headers:c}=await this.createDeployBody(e,{labels:o,via:i.via,password:i.password,flags:r}),s={};return i.deployToken?s.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(s.Authorization=`Bearer ${i.apiKey}`),i.caller&&(s["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:l,headers:{...c,...s},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){let o=K(i);return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:o})},"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 r=K(o),l={};i&&(l.deployment=i),r!==void 0&&(l.labels=r);let{data:c,status:s}=await this.requestWithStatus(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)},"Set domain");return{...c,isCreate:s===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=K(i),r={};return e!==void 0&&(r.ttl=e),o!==void 0&&(r.labels=o),this.request(`${this.apiUrl}${m.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"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 fetchAgentToken(){return this.request(`${this.apiUrl}${m.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent 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,i={}){let o=e.find(p=>p.path==="index.html"||p.path==="/index.html");if(!o||o.size>100*1024)return!1;let r;if(typeof Buffer<"u"&&Buffer.isBuffer(o.content))r=o.content.toString("utf-8");else if(typeof Blob<"u"&&o.content instanceof Blob)r=await o.content.text();else if(typeof File<"u"&&o.content instanceof File)r=await o.content.text();else return!1;let l={"Content-Type":"application/json"};i.deployToken?l.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(l.Authorization=`Bearer ${i.apiKey}`);let c={files:e.map(p=>p.path),index:r};return(await this.request(`${this.apiUrl}${m.SPA_CHECK}`,{method:"POST",headers:l,body:JSON.stringify(c)},"SPA check")).isSPA}};S();z();S();S();function Q(n={},t={}){let e={apiUrl:n.apiUrl||t.apiUrl||H,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 me(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}S();Z();async function At(){let n=JSON.stringify(ce,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await G(t);return{path:W,content:t,size:n.length,md5:e}}async function Ue(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===W))return n;try{if(await t.checkSPA(n,e)){let o=await At();return[...n,o]}}catch{}return n}function ye(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:o,hasAuth:r}=n;return{upload:async(l,c={})=>{await e();let s=o?me(c,o):c;if(r&&!r()&&!s.deployToken&&!s.apiKey)try{let g=t(),{secret:I}=await g.fetchAgentToken();s.deployToken=I}catch(g){throw v(g)&&g.type===f.RateLimit?a.rateLimit("public deploy rate limit exceeded, try again later or run 'ship config' for a free account with higher limits"):g}if(!i)throw a.config("processInput function is not provided.");let p=t(),u=await i(l,s);return u=await Ue(u,p,s),p.deploy(u,s)},list:async()=>(await e(),t().listDeployments()),get:async l=>(await e(),t().getDeployment(l)),set:async(l,c)=>(await e(),t().updateDeploymentLabels(l,c.labels)),remove:async l=>{await e(),await t().removeDeployment(l)}}}function ge(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 De(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function Se(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 ee=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 F({...t,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=ye({...i,processInput:(o,r)=>this.processInput(o,r),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=ge(i),this._account=De(i),this._tokens=Se(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=L(),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}};S();$();var _=require("zod");S();$();var Ee="ship",wt=_.z.object({apiUrl:_.z.string().url().optional(),apiKey:_.z.string().min(1).optional(),deployToken:_.z.string().min(1).optional()}).strict();function Me(n){try{return wt.parse(n)}catch(t){if(t instanceof _.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 Tt(n){try{if(R()!=="node")return{};let{cosmiconfigSync:t}=await import("cosmiconfig"),e=await import("os"),i=t(Ee,{searchPlaces:[`.${Ee}rc`,"package.json",`${e.homedir()}/.${Ee}rc`],stopDir:e.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return Me(o.config)}catch(t){if(v(t))throw t}return{}}async function te(n){if(R()!=="node")return{};let t={apiUrl:process.env.SHIP_API_URL||void 0,apiKey:process.env.SHIP_API_KEY||void 0,deployToken:process.env.SHIP_DEPLOY_TOKEN||void 0},e=await Tt(n),i={apiUrl:t.apiUrl??e.apiUrl,apiKey:t.apiKey??e.apiKey,deployToken:t.deployToken??e.deployToken};return Me(i)}z();S();async function Be(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:o}=await import("form-data-encoder"),{labels:r,via:l,password:c,flags:s}=t,p=new e,u=[];for(let D of n){if(!Buffer.isBuffer(D.content)&&!(typeof Blob<"u"&&D.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${D.path}`,D.path);if(!D.md5)throw a.file(`File missing md5 checksum: ${D.path}`,D.path);let d=new i([D.content],D.path,{type:"application/octet-stream"});p.append("files[]",d),u.push(D.md5)}p.append("checksums",JSON.stringify(u)),r&&r.length>0&&p.append("labels",JSON.stringify(r)),l&&p.append("via",l),c&&p.append("password",c),s?.build&&p.append("build","true"),s?.prerender&&p.append("prerender","true"),s?.spa&&p.append("spa","true");let g=new o(p),I=[];for await(let D of g.encode())I.push(Buffer.from(D));let P=Buffer.concat(I);return{body:P.buffer.slice(P.byteOffset,P.byteOffset+P.byteLength),headers:{"Content-Type":g.contentType,"Content-Length":Buffer.byteLength(P).toString()}}}Z();function vt(n,t,e,i=!0){let o=n===1?t:e;return i?`${n} ${o}`:o}we();Re();$();xe();Pe();S();z();Ne();var re=class extends ee{constructor(t={}){if(R()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");super(t)}resolveInitialConfig(t){return Q(t,{})}async loadFullConfig(){try{let t=await te(this.clientOptions.configFile),e=Q(this.clientOptions,t);e.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(e.deployToken):e.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(e.apiKey);let i=new F({...this.clientOptions,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();J(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(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:o}=await Promise.resolve().then(()=>(Ne(),Ve));return o(i,e)}getDeployBodyCreator(){return Be}},qe=re;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,PASSWORD_CONSTRAINTS,SPA_DEFAULT_CONFIG,Ship,ShipError,UNBUILT_PROJECT_MARKERS,UNSAFE_FILENAME_CHARS,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getCurrentConfig,getENV,getValidFiles,hasUnbuiltMarker,hasUnsafeChars,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;