@shipstatic/ship 2.2.0-beta.4 → 2.2.0-beta.6

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