@shipstatic/ship 2.1.0 → 2.2.0-beta.1

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