@shipstatic/ship 2.2.0-beta.7 → 2.2.0-beta.9

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