@shipstatic/ship 2.9.3 → 2.9.4-beta.2

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 ut=Object.create;var G=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var mt=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,ht=Object.prototype.hasOwnProperty;var A=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ge=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})},Be=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of mt(t))!ht.call(e,i)&&i!==n&&G(e,i,{get:()=>t[i],enumerable:!(r=dt(t,i))||r.enumerable});return e};var P=(e,t,n)=>(n=e!=null?ut(ft(e)):{},Be(t||!e||!e.__esModule?G(n,"default",{value:e,enumerable:!0}):n,e)),yt=e=>Be(G({},"__esModule",{value:!0}),e);function Tt(e){if(!e||typeof e!="string")return;let t=e.trim().toLowerCase();return Object.values(ze).includes(t)?t:void 0}function se(e){if(e==null)return;if(typeof e!="string")throw s.validation("Idempotency key must be a string.");let t=e.trim();if(!t)throw s.validation("Idempotency key must not be empty.");if(t.length>N.MAX_LENGTH)throw s.validation(`Idempotency key must be at most ${N.MAX_LENGTH} characters.`);return t}function Nt(e){let t=e.code;return t==="ERR_INVALID_URL"?!1:typeof t=="string"?!0:e instanceof TypeError?!/\burl\b/i.test(e.message):!1}function C(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function Lt(e){let t=e.replace(/\\/g,"/").split("/").pop()??"",n=t.lastIndexOf(".");return n<=0||n===t.length-1?null:t.slice(n+1).toLowerCase()}function ae(e,t){let n=Lt(e);return n===null?!1:Array.isArray(t)?t.includes(n):t.has(n)}function le(e){return Ve.test(e)}function v(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>z.has(n))}function Ke(e){return e.startsWith(pe.PREFIX)?D.API_KEY:e.startsWith(ce.PREFIX)?D.DEPLOY_TOKEN:e.startsWith(ue.PREFIX)?D.OAUTH:D.OPAQUE}function xt(e){return e.slice(0,oe.length).toLowerCase()!==oe?null:e.slice(oe.length)||null}function me(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n;try{n=JSON.parse(t)}catch(r){throw s.config(`invalid JSON format in config: ${r.message}`,{filePath:S})}if(n===null||typeof n!="object"||Array.isArray(n))throw s.config(`${S} must contain a JSON object`,{filePath:S})}function fe(e,t,n){if(!e.startsWith(t.PREFIX))throw s.validation(`${n} must start with "${t.PREFIX}"`);if(e.length!==t.TOTAL_LENGTH)throw s.validation(`${n} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let r=e.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(r))throw s.validation(`${n} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function qe(e){fe(e,pe,"API key")}function Xe(e){fe(e,ce,"Deploy token")}function Ye(e){fe(e,ue,"OAuth access token")}function V(e){switch(Ke(e)){case D.API_KEY:qe(e);return;case D.DEPLOY_TOKEN:Xe(e);return;case D.OAUTH:Ye(e);return;case D.OPAQUE:if(!e)throw s.validation("Token must be a non-empty string")}}function he(e){if(!e||e.length>b.MAX_LENGTH||!b.PATTERN.test(e))throw s.validation(`Caller must be 1-${b.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function Ct(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw s.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw s.validation("API URL must not contain a path");if(t.search||t.hash)throw s.validation("API URL must not contain query parameters or fragments")}catch(t){throw C(t)?t:s.validation("API URL must be a valid URL")}}function vt(e){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(e)}function K(e){if(e!=null){if(typeof e!="number"||!Number.isFinite(e))throw s.validation("TTL must be a number of seconds");if(!Number.isInteger(e))throw s.validation("TTL must be a whole number of seconds");if(e<x.MIN_SECONDS||e>x.MAX_SECONDS)throw s.validation(`TTL must be between ${x.MIN_SECONDS} and ${x.MAX_SECONDS} seconds`);return e}}function ye(e,t){return e.endsWith(`.${t}`)}function kt(e,t){return!ye(e,t)}function Ht(e,t){return ye(e,t)?e.slice(0,-(t.length+1)):null}function $t(e){return`https://${e}`}function Gt(e){return`https://${e}`}function Bt(e){return!e||e.length===0?null:JSON.stringify(e)}function zt(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function ge(e){if(e==null||e==="")return;if(typeof e!="string")throw s.validation("Build command must be a string");let t=e.trim();if(t.length===0||t.length>O.COMMAND_MAX_LENGTH)throw s.validation(`Build command must be between 1 and ${O.COMMAND_MAX_LENGTH} characters`);if(/[\x00-\x1f\x7f]/.test(t))throw s.validation("Build command must be a single line");return t}function Te(e){if(e==null||e==="")return;if(typeof e!="string")throw s.validation("Output folder must be a string");let t=e.trim().replace(/\/+$/,"");if(t.length===0||t.length>O.OUTPUT_DIR_MAX_LENGTH)throw s.validation(`Output folder must be between 1 and ${O.OUTPUT_DIR_MAX_LENGTH} characters`);if(!O.OUTPUT_DIR_PATTERN.test(t)||t.split("/").some(n=>n===".."||n==="."))throw s.validation("Output folder must be a relative path inside the project, like dist or dist/site");return t}function X(e){if(e==null)return;if(typeof e!="string")throw s.validation("Password must be a string");let t=e.trim();if(t.length<w.MIN_LENGTH||t.length>w.MAX_LENGTH)throw s.validation(`Password must be between ${w.MIN_LENGTH} and ${w.MAX_LENGTH} characters`);return t}var Et,ze,gt,N,At,m,E,St,u,Dt,ie,Rt,It,s,Pt,bt,Ve,z,Ot,_t,B,pe,ce,ue,b,D,oe,wt,S,de,F,x,q,_,Ft,Mt,Ut,h,R,Ee,O,w,f=A(()=>{"use strict";Et={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},ze={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc",CLD:"cld",CRS:"crs",GMN:"gmn",API:"api"},gt={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},N={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};At={FREE:"free",PRO:"pro",TEAM:"team",SCALE:"scale",SPONSORED:"sponsored"},m={DEPLOYMENTS:"/deployments",DEPLOYMENT:e=>`/deployments/${e}`,DEPLOYMENT_CONFIG:e=>`/deployments/${e}/config`,DOMAINS:"/domains",DOMAIN:e=>`/domains/${e}`,DOMAIN_VERIFY:e=>`/domains/${e}/verify`,DOMAIN_DNS:e=>`/domains/${e}/dns`,DOMAIN_RECORDS:e=>`/domains/${e}/records`,DOMAIN_SHARE:e=>`/domains/${e}/share`,DOMAIN_PROPAGATION:e=>`/domains/${e}/propagation`,DOMAINS_VALIDATE:"/domains/validate",TOKENS:"/tokens",TOKEN:e=>`/tokens/${e}`,ACCOUNT:"/account",ACCOUNT_KEY:"/account/key",ACCOUNT_CLAIM:"/account/claim",ACTIVITIES:"/activities",LABELS:"/labels",LIMITS:"/limits",PLANS:"/plans",PING:"/ping",SETUP:"/setup",SPA_CHECK:"/spa-check",UPLOAD:"/upload"},E={FILES:"files[]",CHECKSUMS:"checksums",LABELS:"labels",VIA:"via",PASSWORD:"password",TTL:"ttl",BUILD:"build",PRERENDER:"prerender",SPA:"spa",BUILD_COMMAND:"buildCommand",OUTPUT_DIR:"outputDir",CAPTCHA:"captcha"},St={PATH:"path",CONTENT:"content",ENCODING:"encoding",DEFAULT_ENCODING:"utf-8",ENCODINGS:["utf-8","base64"]},u={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Maintenance:"maintenance",Build:"build_failed",Network:"network_error",Timeout:"timeout_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},Dt=new Set([u.Network,u.Timeout,u.Cancelled,u.File,u.Config]),ie={client:new Set([u.Build,u.Business,u.Cancelled,u.Config,u.File,u.Forbidden,u.NotFound,u.RateLimit,u.Validation]),network:new Set([u.Network,u.Timeout]),auth:new Set([u.Authentication])},Rt=new Set(Object.values(u).filter(e=>!Dt.has(e))),It=200;s=class e extends Error{type;status;details;constructor(t,n,r,i){super(n),this.type=t,this.status=r,this.details=i,this.name="ShipError"}toResponse(){let t=this.details,n=this.type===u.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:n}}static async fromHttpResponse(t,n){let r,i,o;try{if(t.headers.get("content-type")?.includes("application/json")){let d=await t.json();if(d&&typeof d=="object"){let p=d;typeof p.message=="string"?r=p.message:typeof p.error=="string"&&(r=p.error),i=p.details,typeof p.error=="string"&&Rt.has(p.error)&&(o=p.error)}}else{let d=(await t.text()).trim();d&&!d.startsWith("<")&&d.length<=It&&(r=d)}}catch{}let l=t.headers.get("retry-after");if(l!==null){let a=l.trim(),d=/^\d+$/.test(a)?Number(a):Math.ceil((Date.parse(a)-Date.now())/1e3);if(Number.isFinite(d)&&d>=0){let p=i&&typeof i=="object"?i:{};p.retryAfter===void 0&&(i={...p,retryAfter:d})}}r=r||`${n||"Request"} failed with status ${t.status}`;let c=o??(t.status===401?u.Authentication:t.status===403?u.Forbidden:t.status===429?u.RateLimit:u.Api);return new e(c,r,t.status,i)}static fromFetchError(t,n){if(C(t))return t;let r=n||"Request",i=t?.name;return i==="AbortError"?e.cancelled(`${r} was cancelled`):i==="TimeoutError"?e.timeout(`${r} timed out`,{cause:t}):t instanceof Error?Nt(t)?e.network(`${r} failed: ${t.message}`,{cause:t}):new e(u.Api,`${r} failed: ${t.message}`):new e(u.Api,`${r} failed: Unknown error`)}static validation(t,n){return new e(u.Validation,t,400,n)}static notFound(t,n){let r=n?`${t} ${n} not found`:`${t} not found`;return new e(u.NotFound,r,404)}static forbidden(t,n){return new e(u.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(u.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(u.Authentication,t,401,n)}static business(t,n=400,r){return new e(u.Business,t,n,r)}static network(t,n){return new e(u.Network,t,void 0,n)}static timeout(t,n){return new e(u.Timeout,t,void 0,n)}static cancelled(t,n){return new e(u.Cancelled,t,void 0,n)}static file(t,n){return new e(u.File,t,void 0,n)}static config(t,n){return new e(u.Config,t,void 0,n)}static api(t,n=500,r){return new e(u.Api,t,n,r)}static maintenance(t,n){return new e(u.Maintenance,t,503,n)}static build(t,n){return new e(u.Build,t,422,n)}isClientError(){return ie.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return ie.network.has(this.type)}isAuthError(){return ie.auth.has(this.type)}isType(t){return this.type===t}};Pt=["html","htm","xhtml","xml","txt","md","markdown","pdf","csv","json","jsonc","webmanifest","map","toml","yaml","yml","rss","atom","css","scss","sass","less","js","mjs","cjs","jsx","ts","tsx","wasm","vue","svelte","png","jpg","jpeg","gif","webp","avif","svg","ico","bmp","tif","tiff","heic","heif","woff","woff2","ttf","otf","eot","mp3","wav","ogg","oga","opus","m4a","aac","flac","weba","mp4","webm","ogv","mov","m4v","avi","glb","gltf","usdz","vtt","srt","zip"],bt=Pt.map(e=>`.${e}`).join(","),Ve=/[\x00-\x1f\x7f#?%\\<>"]/;z=new Set(["node_modules","package.json"]);Ot="/auth",_t="signing-in",B={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",SYSTEM:"system"},pe={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},ce={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},ue={PREFIX:"oauth-",HEX_LENGTH:32,TOTAL_LENGTH:38},b={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},D={API_KEY:B.API_KEY,DEPLOY_TOKEN:B.TOKEN,OAUTH:B.OAUTH,OPAQUE:"opaque"};oe="bearer ";wt={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},S="ship.json",de={rewrites:[{source:"/(.*)",destination:"/index.html"}]},F={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};x={MIN_SECONDS:1,MAX_SECONDS:365*24*60*60};q="https://api.shipstatic.com",_={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},Ft="SHIP_VIA",Mt="https://my.shipstatic.com/api-key",Ut=4320*60,h={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};R={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},Ee=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;O={COMMAND_MAX_LENGTH:200,OUTPUT_DIR_MAX_LENGTH:100,OUTPUT_DIR_PATTERN:/^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/};w={MIN_LENGTH:6,MAX_LENGTH:128}});async function Qt(e){let t=(await import("spark-md5")).default,n=new t.ArrayBuffer,r=2097152;for(let i=0;i<e.size;i+=r){let o=Math.min(i+r,e.size);n.append(await e.slice(i,o).arrayBuffer())}return{md5:n.end()}}async function Zt(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function en(e){let{createHash:t}=await import("crypto"),{createReadStream:n}=await import("fs");return new Promise((r,i)=>{let o=t("md5"),l=n(e);l.on("error",c=>i(s.file(`Failed to read file for MD5: ${c.message}`,{filePath:e}))),l.on("data",c=>o.update(c)),l.on("end",()=>r({md5:o.digest("hex")}))})}async function U(e){if(e instanceof Blob)return Qt(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return Zt(e);if(typeof e=="string")return en(e);throw s.business("Invalid input for MD5 calculation")}var j=A(()=>{"use strict";f()});function on(e){Ne=e}function sn(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function L(){return Ne||sn()}var Ne,H=A(()=>{"use strict";Ne=null});function tt(e){if(!e||e.length===0)return"";let t=e.filter(o=>o&&typeof o=="string").map(o=>o.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(o=>o.split("/").filter(Boolean)),r=[],i=Math.min(...n.map(o=>o.length));for(let o=0;o<i;o++){let l=n[0][o];if(n.every(c=>c[o]===l))r.push(l);else break}return r.join("/")}function Q(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var be=A(()=>{"use strict"});function _e(e,t={}){if(t.flatten===!1)return e.map(r=>({path:Q(r),name:Oe(r)}));let n=pn(e);return e.map(r=>{let i=Q(r);if(n){let o=n.endsWith("/")?n:`${n}/`;i.startsWith(o)&&(i=i.substring(o.length))}return i||(i=Oe(r)),{path:i,name:Oe(r)}})}function pn(e){if(!e.length)return"";let n=e.map(o=>Q(o)).map(o=>o.split("/")),r=[],i=Math.min(...n.map(o=>o.length));for(let o=0;o<i-1;o++){let l=n[0][o];if(n.every(c=>c[o]===l))r.push(l);else break}return r.join("/")}function Oe(e){return e.split(/[/\\]/).pop()||e}var xe=A(()=>{"use strict";be()});function ee(e,t){return cn.find(n=>n.broken(e,t))}var cn,we=A(()=>{"use strict";f();Ce();cn=[{name:"name",broken:({path:e})=>!Z(e).valid,sentence:({path:e})=>Z(e).reason??"Invalid file name"},{name:"extension",broken:({path:e},t)=>ae(e,t.blockedExtensions??[]),sentence:({path:e})=>`File extension not allowed: "${e}"`},{name:"fileSize",broken:({size:e},t)=>e>t.maxFileSize,sentence:({path:e},t)=>`File "${e}" too large. Maximum ${$(t.maxFileSize)} allowed`},{name:"totalSize",broken:({totalSize:e},t)=>e>t.maxTotalSize,sentence:({totalSize:e},t)=>`Total upload size too large. ${$(e)} exceeds maximum of ${$(t.maxTotalSize)}`}]});function $(e,t=1){if(e===0)return"0 Bytes";let n=1024,r=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(e)/Math.log(n));return`${parseFloat((e/n**i).toFixed(t))} ${r[i]}`}function Z(e){if(le(e))return{valid:!1,reason:"File name contains unsafe characters"};if(e.startsWith(" ")||e.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(e.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,n=e.split("/").pop()||e;return t.test(n)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function un(e,t){let n=[],r=[],i=[];if(e.length===0){let a={file:"(no files)",message:"At least one file must be provided"};return n.push(a),{files:[],validFiles:[],errors:n,warnings:[],canDeploy:!1}}for(let a of e)if(v(a.name))return n.push({file:a.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:e.map(d=>({...d,status:h.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:n,warnings:[],canDeploy:!1};if(e.length>t.maxFilesCount){let a={file:`(${e.length} files)`,message:`File count (${e.length}) exceeds limit of ${t.maxFilesCount}`};return n.push(a),{files:e.map(d=>({...d,status:h.VALIDATION_FAILED,statusMessage:a.message})),validFiles:[],errors:n,warnings:[],canDeploy:!1}}let o=0;for(let a of e){let d=h.READY,p="Ready for upload";if(a.status===h.PROCESSING_ERROR)d=h.VALIDATION_FAILED,p=a.statusMessage||"File failed during processing",n.push({file:a.name,message:p});else if(a.size===0){d=h.EXCLUDED,p="File is empty (0 bytes) and cannot be deployed due to storage limitations",r.push({file:a.name,message:p}),i.push({...a,status:d,statusMessage:p});continue}else if(a.size<0)d=h.VALIDATION_FAILED,p="File size must be positive",n.push({file:a.name,message:p});else if(!a.name||a.name.trim().length===0)d=h.VALIDATION_FAILED,p="File name cannot be empty",n.push({file:a.name||"(empty)",message:p});else if(a.name.includes("\0"))d=h.VALIDATION_FAILED,p="File name contains invalid characters (null byte)",n.push({file:a.name,message:p});else{let y={path:a.name,size:a.size,totalSize:o+a.size},I=ee(y,t);I?(d=h.VALIDATION_FAILED,p=I.sentence(y,t),n.push({file:I.name==="totalSize"?`(${e.length} files)`:a.name,message:p})):o=y.totalSize}i.push({...a,status:d,statusMessage:p})}n.length>0&&(i=i.map(a=>a.status===h.EXCLUDED?a:{...a,status:h.VALIDATION_FAILED,statusMessage:a.status===h.VALIDATION_FAILED?a.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=n.length===0?i.filter(a=>a.status===h.READY):[],c=n.length===0;return{files:i,validFiles:l,errors:n,warnings:r,canDeploy:c}}function nt(e){return e.filter(t=>t.status===h.READY)}function dn(e){return nt(e).length>0}var Ce=A(()=>{"use strict";f();we()});function ve(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(r=>r&&v(r)))throw s.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(n=>{if(!n)return!1;let r=n.replace(/\\/g,"/").split("/").filter(Boolean);if(r.length===0)return!0;let i=r[r.length-1];if((0,rt.isJunk)(i))return!1;for(let l of r)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let o=r.slice(0,-1);for(let l of o)if(it.some(c=>l.toLowerCase()===c.toLowerCase()))return!1;return!0})}var rt,it,Fe=A(()=>{"use strict";f();rt=require("junk"),it=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Me(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw s.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function Ue(e,t){let n=ee(e,t);if(n)throw s.business(n.sentence(e,t))}var ke=A(()=>{"use strict";f();we()});async function ot(e,t={},n){let r=!!(t.build||t.prerender),i=_e(e.map(p=>p.path),{flatten:t.pathDetect!==!1}).map(p=>p.path),o=new Set(ve(i,{allowUnbuilt:r})),l=e.map((p,y)=>({source:p,deployPath:i[y]})).filter(({deployPath:p})=>o.has(p));if(l.length===0)return[];let c=r?null:fn(n),a=[],d=0;for(let{source:p,deployPath:y}of l){if(c&&Me(y,p.origin),p.size===0)continue;c&&(d+=p.size,Ue({path:y,size:p.size,totalSize:d},c));let I=await p.read(),{md5:ne}=await U(I);a.push({path:y,content:I,size:p.size,md5:ne})}if(c&&a.length>c.maxFilesCount)throw s.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return a}function fn(e){if(!e)throw s.config("Platform limits not provided. Deploy-mode validation requires the limits argument \u2014 pass `ship.getLimits()` result.");return e}var st=A(()=>{"use strict";f();xe();Fe();j();ke()});var lt={};Ge(lt,{processFilesForNode:()=>He});function at(e,t=new Set){let n=[],r=T.realpathSync(e);if(t.has(r))return n;t.add(r);for(let i of T.readdirSync(e)){let o=g.join(e,i),l=T.statSync(o);l.isDirectory()?n.push(...at(o,t)):l.isFile()&&n.push({absPath:o,size:l.size})}return n}async function hn(e){try{return T.readFileSync(e)}catch(t){let n=t instanceof Error?t.message:String(t);throw s.file(`Failed to read file "${e}": ${n}`,{filePath:e})}}function yn(e){for(let t of e){let n=g.resolve(t);try{if(T.statSync(n).isDirectory()){let r=T.readdirSync(n).find(i=>z.has(i));if(r)throw s.business(`"${r}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(r){if(C(r))throw r}}}async function He(e,t={},n){if(L()!=="node")throw s.business("processFilesForNode can only be called in Node.js environment.");yn(e);let r=e.flatMap(c=>{let a=g.resolve(c);try{let d=T.statSync(a);return d.isDirectory()?at(a):[{absPath:a,size:d.size}]}catch{throw s.file(`Path does not exist: ${c}`,{filePath:c})}}),i=new Map(r.map(c=>[c.absPath,c.size])),o=tt(e.map(c=>g.resolve(c)).map(c=>{try{return T.statSync(c).isDirectory()?c:g.dirname(c)}catch{return g.dirname(c)}})),l=[...i].map(([c,a])=>({path:En(c,o),origin:c,size:a,read:()=>hn(c)}));return ot(l,t,n)}function En(e,t){if(t&&t.length>0){let n=g.relative(t,e);if(n&&typeof n=="string"&&!n.startsWith(".."))return n.replace(/\\/g,"/")}return g.basename(e)}var T,g,$e=A(()=>{"use strict";T=P(require("fs"),1),g=P(require("path"),1);f();st();H();be()});var gn={};Ge(gn,{API_KEY:()=>pe,API_PATHS:()=>m,AUTH_BASE_PATH:()=>Ot,AccountPlan:()=>At,ApiHttp:()=>M,AuthMethod:()=>B,BUILD_SETTINGS:()=>O,CALLER:()=>b,DEFAULT_API:()=>q,DEPLOYMENT_CONFIG_FILENAME:()=>S,DEPLOY_FIELDS:()=>E,DEPLOY_FILE_GRAMMAR:()=>St,DEPLOY_TOKEN:()=>ce,DeploymentStatus:()=>Et,DeploymentVia:()=>ze,DomainStatus:()=>gt,ErrorType:()=>u,FILE_VALIDATION_STATUS:()=>h,FileValidationStatus:()=>h,IDEMPOTENCY_KEY_CONSTRAINTS:()=>N,JUNK_DIRECTORIES:()=>it,LABEL_CONSTRAINTS:()=>R,LABEL_PATTERN:()=>Ee,MY_API_KEY_URL:()=>Mt,OAUTH_TOKEN:()=>ue,OAuthScope:()=>wt,PASSWORD_CONSTRAINTS:()=>w,PUBLIC_DEPLOYMENT_TTL_SECONDS:()=>Ut,SHIP_ENV:()=>_,SHIP_VIA_ENV:()=>Ft,SIGN_IN_RETURN_PARAM:()=>_t,SPA_CHECK_CONSTRAINTS:()=>F,SPA_DEFAULT_CONFIG:()=>de,Ship:()=>te,ShipError:()=>s,TTL_CONSTRAINTS:()=>x,TokenKind:()=>D,UNBUILT_PROJECT_MARKERS:()=>z,UNSAFE_FILENAME_CHARS:()=>Ve,WEB_FILE_ACCEPT:()=>bt,__setTestEnvironment:()=>on,allValidFilesReady:()=>dn,assertShipJsonSyntax:()=>me,calculateMD5:()=>U,classifyToken:()=>Ke,createAccountResource:()=>Re,createDeploymentResource:()=>Se,createDomainResource:()=>De,createTokenResource:()=>Ie,default:()=>pt,deserializeLabels:()=>zt,extractSubdomain:()=>Ht,filterJunk:()=>ve,formatFileSize:()=>$,generateDeploymentUrl:()=>$t,generateDomainUrl:()=>Gt,getENV:()=>L,getValidFiles:()=>nt,hasUnbuiltMarker:()=>v,hasUnsafeChars:()=>le,isBlockedExtension:()=>ae,isCustomDomain:()=>kt,isDeployment:()=>vt,isPlatformDomain:()=>ye,isShipError:()=>C,normalizeVia:()=>Tt,optimizeDeployPaths:()=>_e,pluralize:()=>mn,processFilesForNode:()=>He,readBearerValue:()=>xt,serializeLabels:()=>Bt,validateApiKey:()=>qe,validateApiUrl:()=>Ct,validateBuildCommand:()=>ge,validateCaller:()=>he,validateDeployFile:()=>Ue,validateDeployPath:()=>Me,validateDeployToken:()=>Xe,validateFileName:()=>Z,validateFiles:()=>un,validateIdempotencyKey:()=>se,validateOAuthToken:()=>Ye,validateOutputDir:()=>Te,validatePassword:()=>X,validateToken:()=>V,validateTtl:()=>K});module.exports=yt(gn);f();f();f();var Y=class{constructor(){this.handlers=new Map}on(t,n){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(n)}off(t,n){let r=this.handlers.get(t);r&&(r.delete(n),r.size===0&&this.handlers.delete(t))}emit(t,...n){let r=this.handlers.get(t);if(!r)return;let i=Array.from(r);for(let o of i)try{o(...n)}catch(l){r.delete(o),t!=="error"&&setTimeout(()=>{let c=l instanceof Error?l:new Error(String(l));this.emit("error",c,String(t))},0)}}};var Vt=3e4,Kt=2,qt=300,Xt=2e3,Yt=new Set([500,502,503,504]);function jt(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let i=()=>{clearTimeout(l),t?.removeEventListener("abort",o)},o=()=>{i(),r(t?.reason)},l=setTimeout(()=>{i(),n()},e);t?.addEventListener("abort",o)})}var je=3e5,Wt=3e5,Jt=je+Wt,M=class extends Y{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||q,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??Vt,this.maxRetries=Math.max(0,n.maxRetries??Kt),this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.deploy={endpoint:n.deployEndpoint||m.DEPLOYMENTS,timeout:n.timeout??je,buildTimeout:n.timeout??Jt}}setGlobalHeaders(n){this.globalHeaders=n}async executeRequest(n,r,i,o=this.timeout){for(let l=0;;l++)try{return await this.attemptOnce(n,r,i,o)}catch(c){let a=s.fromFetchError(c,i);if(l>=this.maxRetries||!this.isRetryable(a,r))throw this.emit("error",a,n),a;this.emit("retry",a,n,l+1);let d=Math.min(Xt,qt*2**l);try{await jt(Math.random()*d,r.signal)}catch(p){let y=s.fromFetchError(p,i);throw this.emit("error",y,n),y}}}isRetryable(n,r){if(r.signal?.aborted||n.isType(u.Maintenance)||n.isType(u.Cancelled)||!(n.isNetworkError()||n.status!==void 0&&Yt.has(n.status)))return!1;let o=(r.method??"GET").toUpperCase();return o==="GET"||o==="HEAD"?!0:o==="PUT"||o==="DELETE"?!1:this.hasIdempotencyKey(r.headers)}hasIdempotencyKey(n){if(!n)return!1;let r=N.HEADER.toLowerCase();return Object.keys(n).some(i=>i.toLowerCase()===r)}async attemptOnce(n,r,i,o=this.timeout){let l=()=>{};try{let c=await this.mergeHeaders(r.headers),a=this.createTimeoutSignal(r.signal,o);l=a.cleanup;let d={...r,headers:c,credentials:this.session&&!c.Authorization?"include":void 0,signal:a.signal};this.emit("request",n,d);let p=await this.fetch(n,d);if(l(),!p.ok)throw await s.fromHttpResponse(p,i);return this.emit("response",this.safeClone(p),n),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(c){throw l(),s.fromFetchError(c,i)}}async request(n,r,i,o){let{data:l}=await this.executeRequest(`${this.apiUrl}${n}`,r,i,o);return l}async requestWithStatus(n,r,i){return this.executeRequest(`${this.apiUrl}${n}`,r,i)}async mergeHeaders(n={}){return{...this.globalHeaders,...this.caller?{[b.HEADER]:this.caller}:{},...await this.getAuthHeadersCallback(),...n}}createTimeoutSignal(n,r=this.timeout){let i=new AbortController,o=setTimeout(()=>i.abort(new DOMException(`Timed out after ${r}ms`,"TimeoutError")),r),l=n?()=>i.abort(n.reason):void 0;return n&&l&&(n.addEventListener("abort",l),n.aborted&&i.abort(n.reason)),{signal:i.signal,cleanup:()=>{clearTimeout(o),n&&l&&n.removeEventListener("abort",l)}}}safeClone(n){try{return n.clone()}catch{return n}}async parseResponse(n){if(!(n.headers.get("Content-Length")==="0"||n.status===204))return n.json()}};f();f();async function We(e,t={}){let{labels:n,via:r,password:i,ttl:o,flags:l,captcha:c}=t,a=new FormData,d=[];for(let p of e){if(typeof p.content=="string"||p.content===null||p.content===void 0)throw s.file(`Unsupported file.content type: ${p.path}`,{filePath:p.path});if(!p.md5)throw s.file(`File missing md5 checksum: ${p.path}`,{filePath:p.path});a.append(E.FILES,new File([p.content],p.path,{type:"application/octet-stream"})),d.push(p.md5)}return a.append(E.CHECKSUMS,JSON.stringify(d)),n&&n.length>0&&a.append(E.LABELS,JSON.stringify(n)),r&&a.append(E.VIA,r),i&&a.append(E.PASSWORD,i),o!==void 0&&a.append(E.TTL,String(o)),l?.build&&a.append(E.BUILD,"true"),l?.prerender&&a.append(E.PRERENDER,"true"),l?.spa&&a.append(E.SPA,"true"),l?.buildCommand&&a.append(E.BUILD_COMMAND,l.buildCommand),l?.outputDir&&a.append(E.OUTPUT_DIR,l.outputDir),c&&a.append(E.CAPTCHA,c),a}f();j();async function tn(){let e=JSON.stringify(de,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await U(t);return{path:S,content:t,size:e.length,md5:n}}async function nn(e,t){let n=e.find(l=>l.path===F.INDEX_FILE||l.path===`/${F.INDEX_FILE}`);if(!n||n.size>F.MAX_INDEX_BYTES)return!1;let r;if(typeof Buffer<"u"&&Buffer.isBuffer(n.content))r=n.content.toString("utf-8");else if(typeof Blob<"u"&&n.content instanceof Blob)r=await n.content.text();else if(typeof File<"u"&&n.content instanceof File)r=await n.content.text();else return!1;let i={files:e.map(l=>l.path),index:r};return(await t.request(m.SPA_CHECK,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA check")).isSPA}async function Je(e,t,n){if(n.spaDetect===!1||n.spa||n.build||n.prerender||e.some(r=>r.path===S))return e;try{if(await nn(e,t)){let i=await tn();return[...e,i]}}catch{}return e}f();f();function k(e){if(e==null)return;if(e.length===0)return e;if(e.length>R.MAX_COUNT)throw s.validation(`Maximum ${R.MAX_COUNT} labels allowed`);let t=e.map((r,i)=>{if(typeof r!="string")throw s.validation(`Label at index ${i} must be a string`);let o=r.trim().toLowerCase();if(o.length<R.MIN_LENGTH)throw s.validation(`Labels must be at least ${R.MIN_LENGTH} characters long`);if(o.length>R.MAX_LENGTH)throw s.validation(`Labels must be no more than ${R.MAX_LENGTH} characters long`);if(!Ee.test(o))throw s.validation(`Labels must start and end with alphanumeric characters, with optional separators (${R.SEPARATORS}) between segments`);return o}),n=[...new Set(t)];if(n.length!==t.length)throw s.validation("Duplicate labels are not allowed");return n}async function Qe(e){let t=e.find(i=>i.path===S||i.path===`/${S}`);if(!t)return;let n=t.content,r=typeof n.text=="function"?await n.text():t.content.toString("utf8");me(r)}var W={"Content-Type":"application/json"},rn="sdk";function Ae(e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor!==void 0&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}function Se(e){let{getApi:t,processInput:n}=e;return{upload:async(r,i={})=>{if(!n)throw s.config("processInput function is not provided.");let o=t(),l=await n(r,i),c=await Je(l,o,i);if(!c.length)throw s.business("No files to deploy");for(let re of c)if(!re.md5)throw s.file(`MD5 checksum missing for file: ${re.path}`,{filePath:re.path});X(i.password);let a=K(i.ttl),d=se(i.idempotencyKey),p=k(i.labels);await Qe(c);let y=ge(i.buildCommand),I=Te(i.outputDir),ne=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa,buildCommand:y,outputDir:I}:void 0,ct=await We(c,{labels:p,via:i.via??rn,password:i.password,ttl:a,flags:ne,captcha:i.captcha});return o.request(o.deploy.endpoint,{method:"POST",body:ct,...d?{headers:{[N.HEADER]:d}}:{},signal:i.signal||null},"Deploy",i.build||i.prerender?o.deploy.buildTimeout:o.deploy.timeout)},list:async r=>t().request(`${m.DEPLOYMENTS}${Ae(r)}`,{method:"GET"},"List deployments"),get:async r=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"GET"},"Get deployment"),set:async(r,i)=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"PATCH",headers:W,body:JSON.stringify({labels:k(i.labels)})},"Update deployment labels"),delete:async r=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"DELETE"},"Delete deployment")}}function De(e){let{getApi:t}=e;return{set:async(n,r={})=>{let i=k(r.labels),o={};r.deployment&&(o.deployment=r.deployment),i!==void 0&&(o.labels=i);let{data:l,status:c}=await t().requestWithStatus(m.DOMAIN(encodeURIComponent(n)),{method:"PUT",headers:W,body:JSON.stringify(o)},"Set domain");return{...l,isCreate:c===201}},list:async n=>t().request(`${m.DOMAINS}${Ae(n)}`,{method:"GET"},"List domains"),get:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"GET"},"Get domain"),delete:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"DELETE"},"Delete domain"),verify:async n=>t().request(m.DOMAIN_VERIFY(encodeURIComponent(n)),{method:"POST"},"Verify domain"),validate:async n=>t().request(m.DOMAINS_VALIDATE,{method:"POST",headers:W,body:JSON.stringify({domain:n})},"Validate domain"),dns:async n=>t().request(m.DOMAIN_DNS(encodeURIComponent(n)),{method:"GET"},"Get domain DNS"),records:async n=>t().request(m.DOMAIN_RECORDS(encodeURIComponent(n)),{method:"GET"},"Get domain records"),share:async n=>t().request(m.DOMAIN_SHARE(encodeURIComponent(n)),{method:"GET"},"Get domain share")}}function Re(e){let{getApi:t}=e;return{get:async()=>t().request(m.ACCOUNT,{method:"GET"},"Get account")}}function Ie(e){let{getApi:t}=e;return{create:async(n={})=>{let r=K(n.ttl),i=k(n.labels),o={};return r!==void 0&&(o.ttl=r),i!==void 0&&(o.labels=i),t().request(m.TOKENS,{method:"POST",headers:W,body:JSON.stringify(o)},"Create token")},list:async n=>t().request(`${m.TOKENS}${Ae(n)}`,{method:"GET"},"List tokens"),get:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"GET"},"Get token"),delete:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"DELETE"},"Delete token")}}var J=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.credential=null;if(t={...t,apiUrl:t.apiUrl||void 0,token:t.token||void 0,caller:t.caller||void 0},this.clientOptions=t,t.caller!==void 0&&he(t.caller),t.token&&t.session)throw s.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(V(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new M({...t,getAuthHeaders:()=>this.getAuthHeaders()});let n={getApi:()=>this.http};this.deployments=Se({...n,processInput:async(r,i)=>(await this.ensureInitialized(),this.processInput(r,i))}),this.domains=De(n),this.account=Re(n),this.tokens=Ie(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.request(m.LIMITS,{method:"GET"},"Get limits")}catch(t){throw this.initPromise=null,t}}async ping(){return this.http.request(m.PING,{method:"GET"},"Ping")}async deploy(t,n){return this.deployments.upload(t,n)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,n){this.http.on(t,n)}off(t,n){this.http.off(t,n)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw s.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw s.business("Invalid token provided. Token must be a non-empty string.");V(t),this.credential=t;return}if(typeof t!="function")throw s.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw s.authentication("Token provider returned no token.");if(typeof t!="string")throw s.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};H();f();var Pe=require("zod");var Le=require("zod"),Ze={apiUrl:Le.z.string().url().optional(),token:Le.z.string().min(1).optional()};H();var an=Pe.z.object(Ze).strict(),ln={apiUrl:_.API_URL,token:_.TOKEN};function et(){if(L()!=="node")return{};let e={apiUrl:process.env[_.API_URL]||void 0,token:process.env[_.TOKEN]||void 0};try{return an.parse(e)}catch(t){if(t instanceof Pe.z.ZodError){let n=t.issues[0],r=n.path[0],i=(r&&ln[r])??"SHIP environment configuration";throw s.config(`Invalid ${i}: ${n.message}`)}throw s.config("Invalid environment configuration")}}f();f();xe();H();Ce();Fe();j();ke();function mn(e,t,n,r=!0){let i=e===1?t:n;return r?`${e} ${i}`:i}$e();var te=class extends J{constructor(t={}){if(L()!=="node")throw s.business("Node.js Ship class can only be used in Node.js environment.");let n=et();super({...t,apiUrl:t.apiUrl||n.apiUrl,token:t.token||(t.session?void 0:n.token)})}async deploy(t,n){return super.deploy(t,n)}async processInput(t,n){let r=typeof t=="string"?[t]:t;if(!Array.isArray(r)||!r.every(o=>typeof o=="string"))throw s.business("Invalid input type for Node.js environment. Expected string or string[].");if(r.length===0)throw s.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>($e(),lt));return i(r,n,this.platformLimits??void 0)}},pt=te;0&&(module.exports={API_KEY,API_PATHS,AUTH_BASE_PATH,AccountPlan,ApiHttp,AuthMethod,BUILD_SETTINGS,CALLER,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_FIELDS,DEPLOY_FILE_GRAMMAR,DEPLOY_TOKEN,DeploymentStatus,DeploymentVia,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,IDEMPOTENCY_KEY_CONSTRAINTS,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,MY_API_KEY_URL,OAUTH_TOKEN,OAuthScope,PASSWORD_CONSTRAINTS,PUBLIC_DEPLOYMENT_TTL_SECONDS,SHIP_ENV,SHIP_VIA_ENV,SIGN_IN_RETURN_PARAM,SPA_CHECK_CONSTRAINTS,SPA_DEFAULT_CONFIG,Ship,ShipError,TTL_CONSTRAINTS,TokenKind,UNBUILT_PROJECT_MARKERS,UNSAFE_FILENAME_CHARS,WEB_FILE_ACCEPT,__setTestEnvironment,allValidFilesReady,assertShipJsonSyntax,calculateMD5,classifyToken,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getENV,getValidFiles,hasUnbuiltMarker,hasUnsafeChars,isBlockedExtension,isCustomDomain,isDeployment,isPlatformDomain,isShipError,normalizeVia,optimizeDeployPaths,pluralize,processFilesForNode,readBearerValue,serializeLabels,validateApiKey,validateApiUrl,validateBuildCommand,validateCaller,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles,validateIdempotencyKey,validateOAuthToken,validateOutputDir,validatePassword,validateToken,validateTtl});
1
+ "use strict";var mt=Object.create;var G=Object.defineProperty;var ft=Object.getOwnPropertyDescriptor;var ht=Object.getOwnPropertyNames;var yt=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var A=(e,t)=>()=>(e&&(t=e(e=0)),t);var Be=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})},ze=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ht(t))!Et.call(e,i)&&i!==n&&G(e,i,{get:()=>t[i],enumerable:!(r=ft(t,i))||r.enumerable});return e};var P=(e,t,n)=>(n=e!=null?mt(yt(e)):{},ze(t||!e||!e.__esModule?G(n,"default",{value:e,enumerable:!0}):n,e)),gt=e=>ze(G({},"__esModule",{value:!0}),e);function St(e){if(!e||typeof e!="string")return;let t=e.trim().toLowerCase();return Object.values(Ve).includes(t)?t:void 0}function ae(e){if(e==null)return;if(typeof e!="string")throw s.validation("Idempotency key must be a string.");let t=e.trim();if(!t)throw s.validation("Idempotency key must not be empty.");if(t.length>N.MAX_LENGTH)throw s.validation(`Idempotency key must be at most ${N.MAX_LENGTH} characters.`);return t}function Pt(e){let t=e.code;return t==="ERR_INVALID_URL"?!1:typeof t=="string"?!0:e instanceof TypeError?!/\burl\b/i.test(e.message):!1}function C(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function bt(e){let t=e.replace(/\\/g,"/").split("/").pop()??"",n=t.lastIndexOf(".");return n<=0||n===t.length-1?null:t.slice(n+1).toLowerCase()}function le(e,t){let n=bt(e);return n===null?!1:Array.isArray(t)?t.includes(n):t.has(n)}function pe(e){return Ke.test(e)}function v(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>z.has(n))}function qe(e){return e.startsWith(ce.PREFIX)?D.API_KEY:e.startsWith(ue.PREFIX)?D.DEPLOY_TOKEN:e.startsWith(de.PREFIX)?D.OAUTH:D.OPAQUE}function Ct(e){return e.slice(0,oe.length).toLowerCase()!==oe?null:e.slice(oe.length)||null}function fe(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n;try{n=JSON.parse(t)}catch(r){throw s.config(`invalid JSON format in config: ${r.message}`,{filePath:S})}if(n===null||typeof n!="object"||Array.isArray(n))throw s.config(`${S} must contain a JSON object`,{filePath:S})}function he(e,t,n){if(!e.startsWith(t.PREFIX))throw s.validation(`${n} must start with "${t.PREFIX}"`);if(e.length!==t.TOTAL_LENGTH)throw s.validation(`${n} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let r=e.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(r))throw s.validation(`${n} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function Xe(e){he(e,ce,"API key")}function Ye(e){he(e,ue,"Deploy token")}function je(e){he(e,de,"OAuth access token")}function V(e){switch(qe(e)){case D.API_KEY:Xe(e);return;case D.DEPLOY_TOKEN:Ye(e);return;case D.OAUTH:je(e);return;case D.OPAQUE:if(!e)throw s.validation("Token must be a non-empty string")}}function ye(e){if(!e||e.length>b.MAX_LENGTH||!b.PATTERN.test(e))throw s.validation(`Caller must be 1-${b.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function Ft(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw s.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw s.validation("API URL must not contain a path");if(t.search||t.hash)throw s.validation("API URL must not contain query parameters or fragments")}catch(t){throw C(t)?t:s.validation("API URL must be a valid URL")}}function Mt(e){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(e)}function K(e){if(e!=null){if(typeof e!="number"||!Number.isFinite(e))throw s.validation("TTL must be a number of seconds");if(!Number.isInteger(e))throw s.validation("TTL must be a whole number of seconds");if(e<x.MIN_SECONDS||e>x.MAX_SECONDS)throw s.validation(`TTL must be between ${x.MIN_SECONDS} and ${x.MAX_SECONDS} seconds`);return e}}function We(e){let t=Math.round(e/60);if(!(t>=1))return"less than a minute";if(t<120)return se(t,"minute");let n=Math.round(e/3600);return n<48?se(n,"hour"):se(Math.round(e/86400),"day")}function $t(e,t=Date.now()/1e3){let n=e-t;return n>0?We(n):null}function se(e,t){return`${e} ${t}${e===1?"":"s"}`}function Ee(e,t){return e.endsWith(`.${t}`)}function Gt(e,t){return!Ee(e,t)}function Bt(e,t){return Ee(e,t)?e.slice(0,-(t.length+1)):null}function zt(e){return`https://${e}`}function Vt(e){return`https://${e}`}function Kt(e){return!e||e.length===0?null:JSON.stringify(e)}function qt(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Te(e){if(e==null||e==="")return;if(typeof e!="string")throw s.validation("Build command must be a string");let t=e.trim();if(t.length===0||t.length>O.COMMAND_MAX_LENGTH)throw s.validation(`Build command must be between 1 and ${O.COMMAND_MAX_LENGTH} characters`);if(/[\x00-\x1f\x7f]/.test(t))throw s.validation("Build command must be a single line");return t}function Ae(e){if(e==null||e==="")return;if(typeof e!="string")throw s.validation("Output folder must be a string");let t=e.trim().replace(/\/+$/,"");if(t.length===0||t.length>O.OUTPUT_DIR_MAX_LENGTH)throw s.validation(`Output folder must be between 1 and ${O.OUTPUT_DIR_MAX_LENGTH} characters`);if(!O.OUTPUT_DIR_PATTERN.test(t)||t.split("/").some(n=>n===".."||n==="."))throw s.validation("Output folder must be a relative path inside the project, like dist or dist/site");return t}function X(e){if(e==null)return;if(typeof e!="string")throw s.validation("Password must be a string");let t=e.trim();if(t.length<w.MIN_LENGTH||t.length>w.MAX_LENGTH)throw s.validation(`Password must be between ${w.MIN_LENGTH} and ${w.MAX_LENGTH} characters`);return t}var Tt,Ve,At,N,Dt,m,E,Rt,u,It,ie,Nt,Lt,s,Ot,_t,Ke,z,xt,wt,B,ce,ue,de,b,D,oe,vt,S,me,F,x,q,_,Ut,kt,Ht,h,R,ge,O,w,f=A(()=>{"use strict";Tt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Ve={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc",CLD:"cld",CRS:"crs",GMN:"gmn",API:"api"},At={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},N={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};Dt={FREE:"free",PRO:"pro",TEAM:"team",SCALE:"scale",SPONSORED:"sponsored"},m={DEPLOYMENTS:"/deployments",DEPLOYMENT:e=>`/deployments/${e}`,DEPLOYMENT_CONFIG:e=>`/deployments/${e}/config`,DOMAINS:"/domains",DOMAIN:e=>`/domains/${e}`,DOMAIN_VERIFY:e=>`/domains/${e}/verify`,DOMAIN_DNS:e=>`/domains/${e}/dns`,DOMAIN_RECORDS:e=>`/domains/${e}/records`,DOMAIN_SHARE:e=>`/domains/${e}/share`,DOMAIN_PROPAGATION:e=>`/domains/${e}/propagation`,DOMAINS_VALIDATE:"/domains/validate",TOKENS:"/tokens",TOKEN:e=>`/tokens/${e}`,ACCOUNT:"/account",ACCOUNT_KEY:"/account/key",ACCOUNT_CLAIM:"/account/claim",ACTIVITIES:"/activities",LABELS:"/labels",LIMITS:"/limits",PLANS:"/plans",PING:"/ping",SETUP:"/setup",SPA_CHECK:"/spa-check",UPLOAD:"/upload"},E={FILES:"files[]",CHECKSUMS:"checksums",LABELS:"labels",VIA:"via",PASSWORD:"password",TTL:"ttl",BUILD:"build",PRERENDER:"prerender",SPA:"spa",BUILD_COMMAND:"buildCommand",OUTPUT_DIR:"outputDir",CAPTCHA:"captcha"},Rt={PATH:"path",CONTENT:"content",ENCODING:"encoding",DEFAULT_ENCODING:"utf-8",ENCODINGS:["utf-8","base64"]},u={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Maintenance:"maintenance",Build:"build_failed",Network:"network_error",Timeout:"timeout_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},It=new Set([u.Network,u.Timeout,u.Cancelled,u.File,u.Config]),ie={client:new Set([u.Build,u.Business,u.Cancelled,u.Config,u.File,u.Forbidden,u.NotFound,u.RateLimit,u.Validation]),network:new Set([u.Network,u.Timeout]),auth:new Set([u.Authentication])},Nt=new Set(Object.values(u).filter(e=>!It.has(e))),Lt=200;s=class e extends Error{type;status;details;constructor(t,n,r,i){super(n),this.type=t,this.status=r,this.details=i,this.name="ShipError"}toResponse(){let t=this.details,n=this.type===u.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:n}}static async fromHttpResponse(t,n){let r,i,o;try{if(t.headers.get("content-type")?.includes("application/json")){let d=await t.json();if(d&&typeof d=="object"){let p=d;typeof p.message=="string"?r=p.message:typeof p.error=="string"&&(r=p.error),i=p.details,typeof p.error=="string"&&Nt.has(p.error)&&(o=p.error)}}else{let d=(await t.text()).trim();d&&!d.startsWith("<")&&d.length<=Lt&&(r=d)}}catch{}let l=t.headers.get("retry-after");if(l!==null){let a=l.trim(),d=/^\d+$/.test(a)?Number(a):Math.ceil((Date.parse(a)-Date.now())/1e3);if(Number.isFinite(d)&&d>=0){let p=i&&typeof i=="object"?i:{};p.retryAfter===void 0&&(i={...p,retryAfter:d})}}r=r||`${n||"Request"} failed with status ${t.status}`;let c=o??(t.status===401?u.Authentication:t.status===403?u.Forbidden:t.status===429?u.RateLimit:u.Api);return new e(c,r,t.status,i)}static fromFetchError(t,n){if(C(t))return t;let r=n||"Request",i=t?.name;return i==="AbortError"?e.cancelled(`${r} was cancelled`):i==="TimeoutError"?e.timeout(`${r} timed out`,{cause:t}):t instanceof Error?Pt(t)?e.network(`${r} failed: ${t.message}`,{cause:t}):new e(u.Api,`${r} failed: ${t.message}`):new e(u.Api,`${r} failed: Unknown error`)}static validation(t,n){return new e(u.Validation,t,400,n)}static notFound(t,n){let r=n?`${t} ${n} not found`:`${t} not found`;return new e(u.NotFound,r,404)}static forbidden(t,n){return new e(u.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(u.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(u.Authentication,t,401,n)}static business(t,n=400,r){return new e(u.Business,t,n,r)}static network(t,n){return new e(u.Network,t,void 0,n)}static timeout(t,n){return new e(u.Timeout,t,void 0,n)}static cancelled(t,n){return new e(u.Cancelled,t,void 0,n)}static file(t,n){return new e(u.File,t,void 0,n)}static config(t,n){return new e(u.Config,t,void 0,n)}static api(t,n=500,r){return new e(u.Api,t,n,r)}static maintenance(t,n){return new e(u.Maintenance,t,503,n)}static build(t,n){return new e(u.Build,t,422,n)}isClientError(){return ie.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return ie.network.has(this.type)}isAuthError(){return ie.auth.has(this.type)}isType(t){return this.type===t}};Ot=["html","htm","xhtml","xml","txt","md","markdown","pdf","csv","json","jsonc","webmanifest","map","toml","yaml","yml","rss","atom","css","scss","sass","less","js","mjs","cjs","jsx","ts","tsx","wasm","vue","svelte","png","jpg","jpeg","gif","webp","avif","svg","ico","bmp","tif","tiff","heic","heif","woff","woff2","ttf","otf","eot","mp3","wav","ogg","oga","opus","m4a","aac","flac","weba","mp4","webm","ogv","mov","m4v","avi","glb","gltf","usdz","vtt","srt","zip"],_t=Ot.map(e=>`.${e}`).join(","),Ke=/[\x00-\x1f\x7f#?%\\<>"]/;z=new Set(["node_modules","package.json"]);xt="/auth",wt="signing-in",B={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",SYSTEM:"system"},ce={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},ue={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},de={PREFIX:"oauth-",HEX_LENGTH:32,TOTAL_LENGTH:38},b={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},D={API_KEY:B.API_KEY,DEPLOY_TOKEN:B.TOKEN,OAUTH:B.OAUTH,OPAQUE:"opaque"};oe="bearer ";vt={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},S="ship.json",me={rewrites:[{source:"/(.*)",destination:"/index.html"}]},F={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};x={MIN_SECONDS:1,MAX_SECONDS:365*24*60*60};q="https://api.shipstatic.com",_={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},Ut="SHIP_VIA",kt="https://my.shipstatic.com/api-key",Ht=4320*60;h={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};R={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},ge=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;O={COMMAND_MAX_LENGTH:200,OUTPUT_DIR_MAX_LENGTH:100,OUTPUT_DIR_PATTERN:/^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/};w={MIN_LENGTH:6,MAX_LENGTH:128}});async function tn(e){let t=(await import("spark-md5")).default,n=new t.ArrayBuffer,r=2097152;for(let i=0;i<e.size;i+=r){let o=Math.min(i+r,e.size);n.append(await e.slice(i,o).arrayBuffer())}return{md5:n.end()}}async function nn(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function rn(e){let{createHash:t}=await import("crypto"),{createReadStream:n}=await import("fs");return new Promise((r,i)=>{let o=t("md5"),l=n(e);l.on("error",c=>i(s.file(`Failed to read file for MD5: ${c.message}`,{filePath:e}))),l.on("data",c=>o.update(c)),l.on("end",()=>r({md5:o.digest("hex")}))})}async function U(e){if(e instanceof Blob)return tn(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return nn(e);if(typeof e=="string")return rn(e);throw s.business("Invalid input for MD5 calculation")}var j=A(()=>{"use strict";f()});function ln(e){Le=e}function pn(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function L(){return Le||pn()}var Le,H=A(()=>{"use strict";Le=null});function rt(e){if(!e||e.length===0)return"";let t=e.filter(o=>o&&typeof o=="string").map(o=>o.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(o=>o.split("/").filter(Boolean)),r=[],i=Math.min(...n.map(o=>o.length));for(let o=0;o<i;o++){let l=n[0][o];if(n.every(c=>c[o]===l))r.push(l);else break}return r.join("/")}function Q(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Oe=A(()=>{"use strict"});function xe(e,t={}){if(t.flatten===!1)return e.map(r=>({path:Q(r),name:_e(r)}));let n=dn(e);return e.map(r=>{let i=Q(r);if(n){let o=n.endsWith("/")?n:`${n}/`;i.startsWith(o)&&(i=i.substring(o.length))}return i||(i=_e(r)),{path:i,name:_e(r)}})}function dn(e){if(!e.length)return"";let n=e.map(o=>Q(o)).map(o=>o.split("/")),r=[],i=Math.min(...n.map(o=>o.length));for(let o=0;o<i-1;o++){let l=n[0][o];if(n.every(c=>c[o]===l))r.push(l);else break}return r.join("/")}function _e(e){return e.split(/[/\\]/).pop()||e}var we=A(()=>{"use strict";Oe()});function ee(e,t){return mn.find(n=>n.broken(e,t))}var mn,Ce=A(()=>{"use strict";f();ve();mn=[{name:"name",broken:({path:e})=>!Z(e).valid,sentence:({path:e})=>Z(e).reason??"Invalid file name"},{name:"extension",broken:({path:e},t)=>le(e,t.blockedExtensions??[]),sentence:({path:e})=>`File extension not allowed: "${e}"`},{name:"fileSize",broken:({size:e},t)=>e>t.maxFileSize,sentence:({path:e},t)=>`File "${e}" too large. Maximum ${$(t.maxFileSize)} allowed`},{name:"totalSize",broken:({totalSize:e},t)=>e>t.maxTotalSize,sentence:({totalSize:e},t)=>`Total upload size too large. ${$(e)} exceeds maximum of ${$(t.maxTotalSize)}`}]});function $(e,t=1){if(e===0)return"0 Bytes";let n=1024,r=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(e)/Math.log(n));return`${parseFloat((e/n**i).toFixed(t))} ${r[i]}`}function Z(e){if(pe(e))return{valid:!1,reason:"File name contains unsafe characters"};if(e.startsWith(" ")||e.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(e.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,n=e.split("/").pop()||e;return t.test(n)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function fn(e,t){let n=[],r=[],i=[];if(e.length===0){let a={file:"(no files)",message:"At least one file must be provided"};return n.push(a),{files:[],validFiles:[],errors:n,warnings:[],canDeploy:!1}}for(let a of e)if(v(a.name))return n.push({file:a.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:e.map(d=>({...d,status:h.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:n,warnings:[],canDeploy:!1};if(e.length>t.maxFilesCount){let a={file:`(${e.length} files)`,message:`File count (${e.length}) exceeds limit of ${t.maxFilesCount}`};return n.push(a),{files:e.map(d=>({...d,status:h.VALIDATION_FAILED,statusMessage:a.message})),validFiles:[],errors:n,warnings:[],canDeploy:!1}}let o=0;for(let a of e){let d=h.READY,p="Ready for upload";if(a.status===h.PROCESSING_ERROR)d=h.VALIDATION_FAILED,p=a.statusMessage||"File failed during processing",n.push({file:a.name,message:p});else if(a.size===0){d=h.EXCLUDED,p="File is empty (0 bytes) and cannot be deployed due to storage limitations",r.push({file:a.name,message:p}),i.push({...a,status:d,statusMessage:p});continue}else if(a.size<0)d=h.VALIDATION_FAILED,p="File size must be positive",n.push({file:a.name,message:p});else if(!a.name||a.name.trim().length===0)d=h.VALIDATION_FAILED,p="File name cannot be empty",n.push({file:a.name||"(empty)",message:p});else if(a.name.includes("\0"))d=h.VALIDATION_FAILED,p="File name contains invalid characters (null byte)",n.push({file:a.name,message:p});else{let y={path:a.name,size:a.size,totalSize:o+a.size},I=ee(y,t);I?(d=h.VALIDATION_FAILED,p=I.sentence(y,t),n.push({file:I.name==="totalSize"?`(${e.length} files)`:a.name,message:p})):o=y.totalSize}i.push({...a,status:d,statusMessage:p})}n.length>0&&(i=i.map(a=>a.status===h.EXCLUDED?a:{...a,status:h.VALIDATION_FAILED,statusMessage:a.status===h.VALIDATION_FAILED?a.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=n.length===0?i.filter(a=>a.status===h.READY):[],c=n.length===0;return{files:i,validFiles:l,errors:n,warnings:r,canDeploy:c}}function it(e){return e.filter(t=>t.status===h.READY)}function hn(e){return it(e).length>0}var ve=A(()=>{"use strict";f();Ce()});function Fe(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(r=>r&&v(r)))throw s.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(n=>{if(!n)return!1;let r=n.replace(/\\/g,"/").split("/").filter(Boolean);if(r.length===0)return!0;let i=r[r.length-1];if((0,ot.isJunk)(i))return!1;for(let l of r)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let o=r.slice(0,-1);for(let l of o)if(st.some(c=>l.toLowerCase()===c.toLowerCase()))return!1;return!0})}var ot,st,Me=A(()=>{"use strict";f();ot=require("junk"),st=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ue(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw s.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function ke(e,t){let n=ee(e,t);if(n)throw s.business(n.sentence(e,t))}var He=A(()=>{"use strict";f();Ce()});async function at(e,t={},n){let r=!!(t.build||t.prerender),i=xe(e.map(p=>p.path),{flatten:t.pathDetect!==!1}).map(p=>p.path),o=new Set(Fe(i,{allowUnbuilt:r})),l=e.map((p,y)=>({source:p,deployPath:i[y]})).filter(({deployPath:p})=>o.has(p));if(l.length===0)return[];let c=r?null:En(n),a=[],d=0;for(let{source:p,deployPath:y}of l){if(c&&Ue(y,p.origin),p.size===0)continue;c&&(d+=p.size,ke({path:y,size:p.size,totalSize:d},c));let I=await p.read(),{md5:ne}=await U(I);a.push({path:y,content:I,size:p.size,md5:ne})}if(c&&a.length>c.maxFilesCount)throw s.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return a}function En(e){if(!e)throw s.config("Platform limits not provided. Deploy-mode validation requires the limits argument \u2014 pass `ship.getLimits()` result.");return e}var lt=A(()=>{"use strict";f();we();Me();j();He()});var ct={};Be(ct,{processFilesForNode:()=>$e});function pt(e,t=new Set){let n=[],r=T.realpathSync(e);if(t.has(r))return n;t.add(r);for(let i of T.readdirSync(e)){let o=g.join(e,i),l=T.statSync(o);l.isDirectory()?n.push(...pt(o,t)):l.isFile()&&n.push({absPath:o,size:l.size})}return n}async function gn(e){try{return T.readFileSync(e)}catch(t){let n=t instanceof Error?t.message:String(t);throw s.file(`Failed to read file "${e}": ${n}`,{filePath:e})}}function Tn(e){for(let t of e){let n=g.resolve(t);try{if(T.statSync(n).isDirectory()){let r=T.readdirSync(n).find(i=>z.has(i));if(r)throw s.business(`"${r}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(r){if(C(r))throw r}}}async function $e(e,t={},n){if(L()!=="node")throw s.business("processFilesForNode can only be called in Node.js environment.");Tn(e);let r=e.flatMap(c=>{let a=g.resolve(c);try{let d=T.statSync(a);return d.isDirectory()?pt(a):[{absPath:a,size:d.size}]}catch{throw s.file(`Path does not exist: ${c}`,{filePath:c})}}),i=new Map(r.map(c=>[c.absPath,c.size])),o=rt(e.map(c=>g.resolve(c)).map(c=>{try{return T.statSync(c).isDirectory()?c:g.dirname(c)}catch{return g.dirname(c)}})),l=[...i].map(([c,a])=>({path:An(c,o),origin:c,size:a,read:()=>gn(c)}));return at(l,t,n)}function An(e,t){if(t&&t.length>0){let n=g.relative(t,e);if(n&&typeof n=="string"&&!n.startsWith(".."))return n.replace(/\\/g,"/")}return g.basename(e)}var T,g,Ge=A(()=>{"use strict";T=P(require("fs"),1),g=P(require("path"),1);f();lt();H();Oe()});var Sn={};Be(Sn,{API_KEY:()=>ce,API_PATHS:()=>m,AUTH_BASE_PATH:()=>xt,AccountPlan:()=>Dt,ApiHttp:()=>M,AuthMethod:()=>B,BUILD_SETTINGS:()=>O,CALLER:()=>b,DEFAULT_API:()=>q,DEPLOYMENT_CONFIG_FILENAME:()=>S,DEPLOY_FIELDS:()=>E,DEPLOY_FILE_GRAMMAR:()=>Rt,DEPLOY_TOKEN:()=>ue,DeploymentStatus:()=>Tt,DeploymentVia:()=>Ve,DomainStatus:()=>At,ErrorType:()=>u,FILE_VALIDATION_STATUS:()=>h,FileValidationStatus:()=>h,IDEMPOTENCY_KEY_CONSTRAINTS:()=>N,JUNK_DIRECTORIES:()=>st,LABEL_CONSTRAINTS:()=>R,LABEL_PATTERN:()=>ge,MY_API_KEY_URL:()=>kt,OAUTH_TOKEN:()=>de,OAuthScope:()=>vt,PASSWORD_CONSTRAINTS:()=>w,PUBLIC_DEPLOYMENT_TTL_SECONDS:()=>Ht,SHIP_ENV:()=>_,SHIP_VIA_ENV:()=>Ut,SIGN_IN_RETURN_PARAM:()=>wt,SPA_CHECK_CONSTRAINTS:()=>F,SPA_DEFAULT_CONFIG:()=>me,Ship:()=>te,ShipError:()=>s,TTL_CONSTRAINTS:()=>x,TokenKind:()=>D,UNBUILT_PROJECT_MARKERS:()=>z,UNSAFE_FILENAME_CHARS:()=>Ke,WEB_FILE_ACCEPT:()=>_t,__setTestEnvironment:()=>ln,allValidFilesReady:()=>hn,assertShipJsonSyntax:()=>fe,calculateMD5:()=>U,classifyToken:()=>qe,createAccountResource:()=>Ie,createDeploymentResource:()=>De,createDomainResource:()=>Re,createTokenResource:()=>Ne,default:()=>ut,deserializeLabels:()=>qt,extractSubdomain:()=>Bt,filterJunk:()=>Fe,formatDuration:()=>We,formatFileSize:()=>$,formatTimeRemaining:()=>$t,generateDeploymentUrl:()=>zt,generateDomainUrl:()=>Vt,getENV:()=>L,getValidFiles:()=>it,hasUnbuiltMarker:()=>v,hasUnsafeChars:()=>pe,isBlockedExtension:()=>le,isCustomDomain:()=>Gt,isDeployment:()=>Mt,isPlatformDomain:()=>Ee,isShipError:()=>C,normalizeVia:()=>St,optimizeDeployPaths:()=>xe,pluralize:()=>yn,processFilesForNode:()=>$e,readBearerValue:()=>Ct,serializeLabels:()=>Kt,validateApiKey:()=>Xe,validateApiUrl:()=>Ft,validateBuildCommand:()=>Te,validateCaller:()=>ye,validateDeployFile:()=>ke,validateDeployPath:()=>Ue,validateDeployToken:()=>Ye,validateFileName:()=>Z,validateFiles:()=>fn,validateIdempotencyKey:()=>ae,validateOAuthToken:()=>je,validateOutputDir:()=>Ae,validatePassword:()=>X,validateToken:()=>V,validateTtl:()=>K});module.exports=gt(Sn);f();f();f();var Y=class{constructor(){this.handlers=new Map}on(t,n){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(n)}off(t,n){let r=this.handlers.get(t);r&&(r.delete(n),r.size===0&&this.handlers.delete(t))}emit(t,...n){let r=this.handlers.get(t);if(!r)return;let i=Array.from(r);for(let o of i)try{o(...n)}catch(l){r.delete(o),t!=="error"&&setTimeout(()=>{let c=l instanceof Error?l:new Error(String(l));this.emit("error",c,String(t))},0)}}};var Xt=3e4,Yt=2,jt=300,Wt=2e3,Jt=new Set([500,502,503,504]);function Qt(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let i=()=>{clearTimeout(l),t?.removeEventListener("abort",o)},o=()=>{i(),r(t?.reason)},l=setTimeout(()=>{i(),n()},e);t?.addEventListener("abort",o)})}var Je=3e5,Zt=3e5,en=Je+Zt,M=class extends Y{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||q,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??Xt,this.maxRetries=Math.max(0,n.maxRetries??Yt),this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.deploy={endpoint:n.deployEndpoint||m.DEPLOYMENTS,timeout:n.timeout??Je,buildTimeout:n.timeout??en}}setGlobalHeaders(n){this.globalHeaders=n}async executeRequest(n,r,i,o=this.timeout){for(let l=0;;l++)try{return await this.attemptOnce(n,r,i,o)}catch(c){let a=s.fromFetchError(c,i);if(l>=this.maxRetries||!this.isRetryable(a,r))throw this.emit("error",a,n),a;this.emit("retry",a,n,l+1);let d=Math.min(Wt,jt*2**l);try{await Qt(Math.random()*d,r.signal)}catch(p){let y=s.fromFetchError(p,i);throw this.emit("error",y,n),y}}}isRetryable(n,r){if(r.signal?.aborted||n.isType(u.Maintenance)||n.isType(u.Cancelled)||!(n.isNetworkError()||n.status!==void 0&&Jt.has(n.status)))return!1;let o=(r.method??"GET").toUpperCase();return o==="GET"||o==="HEAD"?!0:o==="PUT"||o==="DELETE"?!1:this.hasIdempotencyKey(r.headers)}hasIdempotencyKey(n){if(!n)return!1;let r=N.HEADER.toLowerCase();return Object.keys(n).some(i=>i.toLowerCase()===r)}async attemptOnce(n,r,i,o=this.timeout){let l=()=>{};try{let c=await this.mergeHeaders(r.headers),a=this.createTimeoutSignal(r.signal,o);l=a.cleanup;let d={...r,headers:c,credentials:this.session&&!c.Authorization?"include":void 0,signal:a.signal};this.emit("request",n,d);let p=await this.fetch(n,d);if(l(),!p.ok)throw await s.fromHttpResponse(p,i);return this.emit("response",this.safeClone(p),n),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(c){throw l(),s.fromFetchError(c,i)}}async request(n,r,i,o){let{data:l}=await this.executeRequest(`${this.apiUrl}${n}`,r,i,o);return l}async requestWithStatus(n,r,i){return this.executeRequest(`${this.apiUrl}${n}`,r,i)}async mergeHeaders(n={}){return{...this.globalHeaders,...this.caller?{[b.HEADER]:this.caller}:{},...await this.getAuthHeadersCallback(),...n}}createTimeoutSignal(n,r=this.timeout){let i=new AbortController,o=setTimeout(()=>i.abort(new DOMException(`Timed out after ${r}ms`,"TimeoutError")),r),l=n?()=>i.abort(n.reason):void 0;return n&&l&&(n.addEventListener("abort",l),n.aborted&&i.abort(n.reason)),{signal:i.signal,cleanup:()=>{clearTimeout(o),n&&l&&n.removeEventListener("abort",l)}}}safeClone(n){try{return n.clone()}catch{return n}}async parseResponse(n){if(!(n.headers.get("Content-Length")==="0"||n.status===204))return n.json()}};f();f();async function Qe(e,t={}){let{labels:n,via:r,password:i,ttl:o,flags:l,captcha:c}=t,a=new FormData,d=[];for(let p of e){if(typeof p.content=="string"||p.content===null||p.content===void 0)throw s.file(`Unsupported file.content type: ${p.path}`,{filePath:p.path});if(!p.md5)throw s.file(`File missing md5 checksum: ${p.path}`,{filePath:p.path});a.append(E.FILES,new File([p.content],p.path,{type:"application/octet-stream"})),d.push(p.md5)}return a.append(E.CHECKSUMS,JSON.stringify(d)),n&&n.length>0&&a.append(E.LABELS,JSON.stringify(n)),r&&a.append(E.VIA,r),i&&a.append(E.PASSWORD,i),o!==void 0&&a.append(E.TTL,String(o)),l?.build&&a.append(E.BUILD,"true"),l?.prerender&&a.append(E.PRERENDER,"true"),l?.spa&&a.append(E.SPA,"true"),l?.buildCommand&&a.append(E.BUILD_COMMAND,l.buildCommand),l?.outputDir&&a.append(E.OUTPUT_DIR,l.outputDir),c&&a.append(E.CAPTCHA,c),a}f();j();async function on(){let e=JSON.stringify(me,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await U(t);return{path:S,content:t,size:e.length,md5:n}}async function sn(e,t){let n=e.find(l=>l.path===F.INDEX_FILE||l.path===`/${F.INDEX_FILE}`);if(!n||n.size>F.MAX_INDEX_BYTES)return!1;let r;if(typeof Buffer<"u"&&Buffer.isBuffer(n.content))r=n.content.toString("utf-8");else if(typeof Blob<"u"&&n.content instanceof Blob)r=await n.content.text();else if(typeof File<"u"&&n.content instanceof File)r=await n.content.text();else return!1;let i={files:e.map(l=>l.path),index:r};return(await t.request(m.SPA_CHECK,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA check")).isSPA}async function Ze(e,t,n){if(n.spaDetect===!1||n.spa||n.build||n.prerender||e.some(r=>r.path===S))return e;try{if(await sn(e,t)){let i=await on();return[...e,i]}}catch{}return e}f();f();function k(e){if(e==null)return;if(e.length===0)return e;if(e.length>R.MAX_COUNT)throw s.validation(`Maximum ${R.MAX_COUNT} labels allowed`);let t=e.map((r,i)=>{if(typeof r!="string")throw s.validation(`Label at index ${i} must be a string`);let o=r.trim().toLowerCase();if(o.length<R.MIN_LENGTH)throw s.validation(`Labels must be at least ${R.MIN_LENGTH} characters long`);if(o.length>R.MAX_LENGTH)throw s.validation(`Labels must be no more than ${R.MAX_LENGTH} characters long`);if(!ge.test(o))throw s.validation(`Labels must start and end with alphanumeric characters, with optional separators (${R.SEPARATORS}) between segments`);return o}),n=[...new Set(t)];if(n.length!==t.length)throw s.validation("Duplicate labels are not allowed");return n}async function et(e){let t=e.find(i=>i.path===S||i.path===`/${S}`);if(!t)return;let n=t.content,r=typeof n.text=="function"?await n.text():t.content.toString("utf8");fe(r)}var W={"Content-Type":"application/json"},an="sdk";function Se(e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor!==void 0&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}function De(e){let{getApi:t,processInput:n}=e;return{upload:async(r,i={})=>{if(!n)throw s.config("processInput function is not provided.");let o=t(),l=await n(r,i),c=await Ze(l,o,i);if(!c.length)throw s.business("No files to deploy");for(let re of c)if(!re.md5)throw s.file(`MD5 checksum missing for file: ${re.path}`,{filePath:re.path});X(i.password);let a=K(i.ttl),d=ae(i.idempotencyKey),p=k(i.labels);await et(c);let y=Te(i.buildCommand),I=Ae(i.outputDir),ne=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa,buildCommand:y,outputDir:I}:void 0,dt=await Qe(c,{labels:p,via:i.via??an,password:i.password,ttl:a,flags:ne,captcha:i.captcha});return o.request(o.deploy.endpoint,{method:"POST",body:dt,...d?{headers:{[N.HEADER]:d}}:{},signal:i.signal||null},"Deploy",i.build||i.prerender?o.deploy.buildTimeout:o.deploy.timeout)},list:async r=>t().request(`${m.DEPLOYMENTS}${Se(r)}`,{method:"GET"},"List deployments"),get:async r=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"GET"},"Get deployment"),set:async(r,i)=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"PATCH",headers:W,body:JSON.stringify({labels:k(i.labels)})},"Update deployment labels"),delete:async r=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"DELETE"},"Delete deployment")}}function Re(e){let{getApi:t}=e;return{set:async(n,r={})=>{let i=k(r.labels),o={};r.deployment&&(o.deployment=r.deployment),i!==void 0&&(o.labels=i);let{data:l,status:c}=await t().requestWithStatus(m.DOMAIN(encodeURIComponent(n)),{method:"PUT",headers:W,body:JSON.stringify(o)},"Set domain");return{...l,isCreate:c===201}},list:async n=>t().request(`${m.DOMAINS}${Se(n)}`,{method:"GET"},"List domains"),get:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"GET"},"Get domain"),delete:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"DELETE"},"Delete domain"),verify:async n=>t().request(m.DOMAIN_VERIFY(encodeURIComponent(n)),{method:"POST"},"Verify domain"),validate:async n=>t().request(m.DOMAINS_VALIDATE,{method:"POST",headers:W,body:JSON.stringify({domain:n})},"Validate domain"),dns:async n=>t().request(m.DOMAIN_DNS(encodeURIComponent(n)),{method:"GET"},"Get domain DNS"),records:async n=>t().request(m.DOMAIN_RECORDS(encodeURIComponent(n)),{method:"GET"},"Get domain records"),share:async n=>t().request(m.DOMAIN_SHARE(encodeURIComponent(n)),{method:"GET"},"Get domain share")}}function Ie(e){let{getApi:t}=e;return{get:async()=>t().request(m.ACCOUNT,{method:"GET"},"Get account")}}function Ne(e){let{getApi:t}=e;return{create:async(n={})=>{let r=K(n.ttl),i=k(n.labels),o={};return r!==void 0&&(o.ttl=r),i!==void 0&&(o.labels=i),t().request(m.TOKENS,{method:"POST",headers:W,body:JSON.stringify(o)},"Create token")},list:async n=>t().request(`${m.TOKENS}${Se(n)}`,{method:"GET"},"List tokens"),get:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"GET"},"Get token"),delete:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"DELETE"},"Delete token")}}var J=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.credential=null;if(t={...t,apiUrl:t.apiUrl||void 0,token:t.token||void 0,caller:t.caller||void 0},this.clientOptions=t,t.caller!==void 0&&ye(t.caller),t.token&&t.session)throw s.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(V(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new M({...t,getAuthHeaders:()=>this.getAuthHeaders()});let n={getApi:()=>this.http};this.deployments=De({...n,processInput:async(r,i)=>(await this.ensureInitialized(),this.processInput(r,i))}),this.domains=Re(n),this.account=Ie(n),this.tokens=Ne(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.request(m.LIMITS,{method:"GET"},"Get limits")}catch(t){throw this.initPromise=null,t}}async ping(){return this.http.request(m.PING,{method:"GET"},"Ping")}async deploy(t,n){return this.deployments.upload(t,n)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,n){this.http.on(t,n)}off(t,n){this.http.off(t,n)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw s.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw s.business("Invalid token provided. Token must be a non-empty string.");V(t),this.credential=t;return}if(typeof t!="function")throw s.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw s.authentication("Token provider returned no token.");if(typeof t!="string")throw s.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};H();f();var be=require("zod");var Pe=require("zod"),tt={apiUrl:Pe.z.string().url().optional(),token:Pe.z.string().min(1).optional()};H();var cn=be.z.object(tt).strict(),un={apiUrl:_.API_URL,token:_.TOKEN};function nt(){if(L()!=="node")return{};let e={apiUrl:process.env[_.API_URL]||void 0,token:process.env[_.TOKEN]||void 0};try{return cn.parse(e)}catch(t){if(t instanceof be.z.ZodError){let n=t.issues[0],r=n.path[0],i=(r&&un[r])??"SHIP environment configuration";throw s.config(`Invalid ${i}: ${n.message}`)}throw s.config("Invalid environment configuration")}}f();f();we();H();ve();Me();j();He();function yn(e,t,n,r=!0){let i=e===1?t:n;return r?`${e} ${i}`:i}Ge();var te=class extends J{constructor(t={}){if(L()!=="node")throw s.business("Node.js Ship class can only be used in Node.js environment.");let n=nt();super({...t,apiUrl:t.apiUrl||n.apiUrl,token:t.token||(t.session?void 0:n.token)})}async deploy(t,n){return super.deploy(t,n)}async processInput(t,n){let r=typeof t=="string"?[t]:t;if(!Array.isArray(r)||!r.every(o=>typeof o=="string"))throw s.business("Invalid input type for Node.js environment. Expected string or string[].");if(r.length===0)throw s.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(Ge(),ct));return i(r,n,this.platformLimits??void 0)}},ut=te;0&&(module.exports={API_KEY,API_PATHS,AUTH_BASE_PATH,AccountPlan,ApiHttp,AuthMethod,BUILD_SETTINGS,CALLER,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_FIELDS,DEPLOY_FILE_GRAMMAR,DEPLOY_TOKEN,DeploymentStatus,DeploymentVia,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,IDEMPOTENCY_KEY_CONSTRAINTS,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,MY_API_KEY_URL,OAUTH_TOKEN,OAuthScope,PASSWORD_CONSTRAINTS,PUBLIC_DEPLOYMENT_TTL_SECONDS,SHIP_ENV,SHIP_VIA_ENV,SIGN_IN_RETURN_PARAM,SPA_CHECK_CONSTRAINTS,SPA_DEFAULT_CONFIG,Ship,ShipError,TTL_CONSTRAINTS,TokenKind,UNBUILT_PROJECT_MARKERS,UNSAFE_FILENAME_CHARS,WEB_FILE_ACCEPT,__setTestEnvironment,allValidFilesReady,assertShipJsonSyntax,calculateMD5,classifyToken,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatDuration,formatFileSize,formatTimeRemaining,generateDeploymentUrl,generateDomainUrl,getENV,getValidFiles,hasUnbuiltMarker,hasUnsafeChars,isBlockedExtension,isCustomDomain,isDeployment,isPlatformDomain,isShipError,normalizeVia,optimizeDeployPaths,pluralize,processFilesForNode,readBearerValue,serializeLabels,validateApiKey,validateApiUrl,validateBuildCommand,validateCaller,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles,validateIdempotencyKey,validateOAuthToken,validateOutputDir,validatePassword,validateToken,validateTtl});
2
2
 
3
3
  // Ship SDK: Enable axios-style CommonJS imports
4
4
  const originalExports = module.exports;