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

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.d.cts CHANGED
@@ -788,12 +788,30 @@ declare class ShipError extends Error {
788
788
  *
789
789
  * Routing:
790
790
  * - Already a `ShipError` → returned as-is (caller's intent preserved)
791
- * - `AbortError` → `ShipError.cancelled(...)`
791
+ * - `AbortError` → `ShipError.cancelled(...)` — someone stopped it on purpose
792
+ * - `TimeoutError` → `ShipError.network(...)` — a deadline expired, so
793
+ * nothing was exchanged; the message names the timeout
792
794
  * - A transport failure → `ShipError.network(...)` — see `isTransportFailure`
793
795
  * for what each runtime offers as evidence
794
796
  * - Any other `Error` → `ShipError(Api, ...)` (no HTTP status — fetch never reached the server)
795
797
  * - Anything else (string, undefined, etc.) → `ShipError(Api, ...)`
796
798
  *
799
+ * **Abort and timeout are read from `name` BEFORE any `instanceof Error`
800
+ * gate.** A `DOMException` satisfies that gate in every runtime measured
801
+ * (Node, Bun, Chromium, Firefox, WebKit, workerd — all six), but the
802
+ * inheritance is a comparatively recent spec change and this classification
803
+ * has no reason to depend on it: `name` is where the meaning lives, and
804
+ * reading it first costs nothing. The suite plants a non-`Error`
805
+ * `DOMException` shape to hold the arm, since no runtime on the table
806
+ * produces one.
807
+ *
808
+ * A caller's own `AbortSignal.timeout()` is the reachable source of
809
+ * `TimeoutError` — and the two are NOT interchangeable per runtime: WebKit
810
+ * reports a fired `AbortSignal.timeout()` as `AbortError`, so on Safari a
811
+ * deadline is indistinguishable from a cancellation and lands on
812
+ * `Cancelled`. Recorded rather than worked around; `Cancelled` is honest
813
+ * there, since the caller's signal is what stopped it.
814
+ *
797
815
  * The optional `operationName` is composed into the message for context:
798
816
  * `"Get account was cancelled"`, `"Get account failed: ..."`. Defaults to
799
817
  * `"Request"` when omitted.
package/dist/index.d.ts CHANGED
@@ -788,12 +788,30 @@ declare class ShipError extends Error {
788
788
  *
789
789
  * Routing:
790
790
  * - Already a `ShipError` → returned as-is (caller's intent preserved)
791
- * - `AbortError` → `ShipError.cancelled(...)`
791
+ * - `AbortError` → `ShipError.cancelled(...)` — someone stopped it on purpose
792
+ * - `TimeoutError` → `ShipError.network(...)` — a deadline expired, so
793
+ * nothing was exchanged; the message names the timeout
792
794
  * - A transport failure → `ShipError.network(...)` — see `isTransportFailure`
793
795
  * for what each runtime offers as evidence
794
796
  * - Any other `Error` → `ShipError(Api, ...)` (no HTTP status — fetch never reached the server)
795
797
  * - Anything else (string, undefined, etc.) → `ShipError(Api, ...)`
796
798
  *
799
+ * **Abort and timeout are read from `name` BEFORE any `instanceof Error`
800
+ * gate.** A `DOMException` satisfies that gate in every runtime measured
801
+ * (Node, Bun, Chromium, Firefox, WebKit, workerd — all six), but the
802
+ * inheritance is a comparatively recent spec change and this classification
803
+ * has no reason to depend on it: `name` is where the meaning lives, and
804
+ * reading it first costs nothing. The suite plants a non-`Error`
805
+ * `DOMException` shape to hold the arm, since no runtime on the table
806
+ * produces one.
807
+ *
808
+ * A caller's own `AbortSignal.timeout()` is the reachable source of
809
+ * `TimeoutError` — and the two are NOT interchangeable per runtime: WebKit
810
+ * reports a fired `AbortSignal.timeout()` as `AbortError`, so on Safari a
811
+ * deadline is indistinguishable from a cancellation and lands on
812
+ * `Cancelled`. Recorded rather than worked around; `Cancelled` is honest
813
+ * there, since the caller's signal is what stopped it.
814
+ *
797
815
  * The optional `operationName` is composed into the message for context:
798
816
  * `"Get account was cancelled"`, `"Get account failed: ..."`. Defaults to
799
817
  * `"Request"` when omitted.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Ke=Object.defineProperty;var P=(n,t)=>()=>(n&&(t=n(n=0)),t);var je=(n,t)=>{for(var e in t)Ke(n,e,{get:t[e],enumerable:!0})};function Rt(n){if(!n||typeof n!="string")return;let t=n.trim().toLowerCase();return Object.values(Ye).includes(t)?t:void 0}function fe(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>B.MAX_LENGTH)throw a.validation(`Idempotency key must be at most ${B.MAX_LENGTH} characters.`);return t}function Je(n){return typeof n.code=="string"?!0:n instanceof TypeError&&n.message.includes("fetch")}function F(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function Qe(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 H(n,t){let e=Qe(n);return e===null?!1:Array.isArray(t)?t.includes(e):t.has(e)}function he(n){return et.test(n)}function G(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>J.has(e))}function tt(n){return n.startsWith(ye.PREFIX)?b.API_KEY:n.startsWith(ge.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:N})}if(e===null||typeof e!="object"||Array.isArray(e))throw a.config(`${N} must contain a JSON object`,{filePath:N})}function Ae(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 nt(n){Ae(n,ye,"API key")}function it(n){Ae(n,ge,"Deploy token")}function Q(n){switch(tt(n)){case b.API_KEY:nt(n);return;case b.DEPLOY_TOKEN:it(n);return;case b.OPAQUE:if(!n)throw a.validation("Token must be a non-empty string")}}function Te(n){if(!n||n.length>_.MAX_LENGTH||!_.PATTERN.test(n))throw a.validation(`Caller must be 1-${_.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function wt(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 xt(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function Se(n,t){return n.endsWith(`.${t}`)}function vt(n,t){return!Se(n,t)}function Ct(n,t){return Se(n,t)?n.slice(0,-(t.length+1)):null}function _t(n){return`https://${n}`}function Ft(n){return`https://${n}`}function $t(n){return!n||n.length===0?null:JSON.stringify(n)}function kt(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}function ee(n){if(n==null)return;if(typeof n!="string")throw a.validation("Password must be a string");let t=n.trim();if(t.length<M.MIN_LENGTH||t.length>M.MAX_LENGTH)throw a.validation(`Password must be between ${M.MIN_LENGTH} and ${M.MAX_LENGTH} characters`);return t}var Tt,Ye,St,B,It,f,I,d,qe,W,Xe,We,a,Ze,Pt,et,J,Nt,me,ye,ge,_,b,Lt,N,Ee,z,Z,$,bt,Ot,y,w,Re,M,g=P(()=>{"use strict";Tt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Ye={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc"},St={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},B={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};It={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"},I={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"},qe=new Set([d.Network,d.Cancelled,d.File,d.Config]),W={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])},Xe=new Set(Object.values(d).filter(n=>!qe.has(n))),We=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"&&Xe.has(p.error)&&(r=p.error)}}else{let c=(await t.text()).trim();c&&!c.startsWith("<")&&c.length<=We&&(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(F(t))return t;let i=e||"Request";return t instanceof Error?t.name==="AbortError"?n.cancelled(`${i} was cancelled`):Je(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 W.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return W.network.has(this.type)}isAuthError(){return W.auth.has(this.type)}isType(t){return this.type===t}};Ze=["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"],Pt=Ze.map(n=>`.${n}`).join(","),et=/[\x00-\x1f\x7f#?%\\<>"]/;J=new Set(["node_modules","package.json"]);Nt="/auth",me={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},ye={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},ge={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},_={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},b={API_KEY:me.API_KEY,DEPLOY_TOKEN:me.TOKEN,OPAQUE:"opaque"};Lt={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},N="ship.json",Ee={rewrites:[{source:"/(.*)",destination:"/index.html"}]},z={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};Z="https://api.shipstatic.com",$={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},bt="https://my.shipstatic.com/api-key",Ot=4320*60,y={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:"._-"},Re=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;M={MIN_LENGTH:6,MAX_LENGTH:128}});async function lt(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 pt(n){let{createHash:t}=await import("crypto"),e=t("md5");return e.update(n),{md5:e.digest("hex")}}async function ct(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 j(n){if(n instanceof Blob)return lt(n);if(typeof Buffer<"u"&&Buffer.isBuffer(n))return pt(n);if(typeof n=="string")return ct(n);throw a.business("Invalid input for MD5 calculation")}var Y=P(()=>{"use strict";g()});function on(n){ne=n}function dt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function O(){return ne||dt()}var ne,U=P(()=>{"use strict";ne=null});function $e(n){if(!n||n.length===0)return"";let t=n.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let e=t.map(r=>r.split("/").filter(Boolean)),i=[],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 X(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ie=P(()=>{"use strict"});function ke(n,t={}){if(t.flatten===!1)return n.map(i=>({path:X(i),name:se(i)}));let e=ht(n);return n.map(i=>{let s=X(i);if(e){let r=e.endsWith("/")?e:`${e}/`;s.startsWith(r)&&(s=s.substring(r.length))}return s||(s=se(i)),{path:s,name:se(i)}})}function ht(n){if(!n.length)return"";let e=n.map(r=>X(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 se(n){return n.split(/[/\\]/).pop()||n}var re=P(()=>{"use strict";ie()});function oe(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 ae(n){if(he(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 Rn(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(G(o.name))return e.push({file:o.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(c=>({...c,status:y.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let o={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(o),{files:n.map(c=>({...c,status:y.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let r=0;for(let o of n){let c=y.READY,p="Ready for upload",R=o.name?ae(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===y.PROCESSING_ERROR)c=y.VALIDATION_FAILED,p=o.statusMessage||"File failed during processing",e.push({file:o.name,message:p});else if(o.size===0){c=y.EXCLUDED,p="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:p}),s.push({...o,status:c,statusMessage:p});continue}else o.size<0?(c=y.VALIDATION_FAILED,p="File size must be positive",e.push({file:o.name,message:p})):!o.name||o.name.trim().length===0?(c=y.VALIDATION_FAILED,p="File name cannot be empty",e.push({file:o.name||"(empty)",message:p})):o.name.includes("\0")?(c=y.VALIDATION_FAILED,p="File name contains invalid characters (null byte)",e.push({file:o.name,message:p})):R.valid?H(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 (${oe(o.size)}) exceeds limit of ${oe(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 ${oe(t.maxTotalSize)}`,e.push({file:o.name,message:p}))):(c=y.VALIDATION_FAILED,p=R.reason||"Invalid file name",e.push({file:o.name,message:p}));s.push({...o,status:c,statusMessage:p})}e.length>0&&(s=s.map(o=>o.status===y.EXCLUDED?o:{...o,status:y.VALIDATION_FAILED,statusMessage:o.status===y.VALIDATION_FAILED?o.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=e.length===0?s.filter(o=>o.status===y.READY):[],u=e.length===0;return{files:s,validFiles:l,errors:e,warnings:i,canDeploy:u}}function yt(n){return n.filter(t=>t.status===y.READY)}function In(n){return yt(n).length>0}var le=P(()=>{"use strict";g()});import{isJunk as gt}from"junk";function Ue(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&G(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(gt(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(Et.some(u=>l.toLowerCase()===u.toLowerCase()))return!1;return!0})}var Et,pe=P(()=>{"use strict";g();Et=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Me(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 Be(n,t,e){let i=ae(n);if(!i.valid)throw a.business(i.reason||"Invalid file name");if(H(n,e))throw a.business(`File extension not allowed: "${t}"`)}var ce=P(()=>{"use strict";g();le()});var ze={};je(ze,{processFilesForNode:()=>Ge});import*as D from"fs";import*as A from"path";function He(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=He(l,t);e.push(...o)}else u.isFile()&&e.push(l)}return e}async function Ge(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=>J.has(S));if(T)throw a.business(`"${T}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(T){if(F(T))throw T}}let i=n.flatMap(m=>{let h=A.resolve(m);try{return D.statSync(h).isDirectory()?He(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=$e(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=ke(u,{flatten:t.pathDetect!==!1}).map(m=>m.path),p=new Set(Ue(c));if(p.size===0)return[];let R=[],v=[];for(let m=0;m<s.length;m++)p.has(c[m])&&(R.push(s[m]),v.push(c[m]));let x=[],L=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<R.length;m++){let h=R[m],T=v[m];try{Me(T,h);let S=D.statSync(h);if(S.size===0)continue;if(Be(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(L+=S.size,L>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let C=D.readFileSync(h),{md5:Ve}=await j(C);x.push({path:T,content:C,size:C.length,md5:Ve})}catch(S){if(F(S))throw S;let C=S instanceof Error?S.message:String(S);throw a.file(`Failed to read file "${h}": ${C}`,{filePath:h})}}if(x.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return x}var ue=P(()=>{"use strict";g();re();U();pe();Y();ie();ce()});g();g();g();var V=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 k(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((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<w.MIN_LENGTH)throw a.validation(`Labels must be at least ${w.MIN_LENGTH} characters long`);if(r.length>w.MAX_LENGTH)throw a.validation(`Labels must be no more than ${w.MAX_LENGTH} characters long`);if(!Re.test(r))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${w.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 Ie(n){let t=n.find(s=>s.path===N||s.path===`/${N}`);if(!t)return;let e=t.content,i=typeof e.text=="function"?await e.text():t.content.toString("utf8");De(i)}var st=3e4,Pe=3e5,rt=3e5,ot=Pe+rt,at="sdk";function te(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 K=class extends V{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||Z,this.getAuthHeadersCallback=e.getAuthHeaders,this.session=e.session??!1,this.caller=e.caller,this.timeout=e.timeout??st,this.deployTimeout=e.timeout??Pe,this.deployBuildTimeout=e.timeout??ot,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?{[_.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});ee(i.password);let s=fe(i.idempotencyKey),r=k(i.labels);await Ie(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??at,password:i.password,flags:l,captcha:i.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:u,headers:s?{...o,[B.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}${te(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=k(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=k(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}${te(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=k(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}${te(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===z.INDEX_FILE||o.path===`/${z.INDEX_FILE}`);if(!s||s.size>z.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();Y();async function ut(){let n=JSON.stringify(Ee,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await j(t);return{path:N,content:t,size:n.length,md5:e}}async function Ne(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===N))return n;try{if(await t.checkSPA(n,e)){let s=await ut();return[...n,s]}}catch{}return n}function Le(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 Ne(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 we(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 xe(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function be(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 q=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&&Te(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 K({...t,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=Le({...e,processInput:(i,s)=>this.processInput(i,s)}),this.domains=we(e),this.account=xe(e),this.tokens=be(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}`}}};U();g();import{z as Ce}from"zod";import{z as Oe}from"zod";var ve={apiUrl:Oe.string().url().optional(),token:Oe.string().min(1).optional()};U();var mt=Ce.object(ve).strict(),ft={apiUrl:$.API_URL,token:$.TOKEN};function _e(){if(O()!=="node")return{};let n={apiUrl:process.env[$.API_URL]||void 0,token:process.env[$.TOKEN]||void 0};try{return mt.parse(n)}catch(t){if(t instanceof Ce.ZodError){let e=t.issues[0],i=e.path[0],s=(i&&ft[i])??"SHIP environment configuration";throw a.config(`Invalid ${s}: ${e.message}`)}throw a.config("Invalid environment configuration")}}g();async function Fe(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,R=[];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(I.FILES,m),R.push(E.md5)}p.append(I.CHECKSUMS,JSON.stringify(R)),r&&r.length>0&&p.append(I.LABELS,JSON.stringify(r)),l&&p.append(I.VIA,l),u&&p.append(I.PASSWORD,u),o?.build&&p.append(I.BUILD,"true"),o?.prerender&&p.append(I.PRERENDER,"true"),o?.spa&&p.append(I.SPA,"true"),c&&p.append(I.CAPTCHA,c);let v=new s(p),x=[];for await(let E of v.encode())x.push(Buffer.from(E));let L=Buffer.concat(x);return{body:L.buffer.slice(L.byteOffset,L.byteOffset+L.byteLength),headers:{"Content-Type":v.contentType,"Content-Length":Buffer.byteLength(L).toString()}}}g();g();re();U();le();pe();Y();ce();function vn(n,t,e,i=!0){let s=n===1?t:e;return i?`${n} ${s}`:s}ue();var de=class extends q{constructor(t={}){if(O()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=_e();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(()=>(ue(),ze));return s(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return Fe}},Dt=de;export{ye as API_KEY,f as API_PATHS,Nt as AUTH_BASE_PATH,It as AccountPlan,K as ApiHttp,me as AuthMethod,_ as CALLER,Z as DEFAULT_API,N as DEPLOYMENT_CONFIG_FILENAME,I as DEPLOY_FIELDS,ge as DEPLOY_TOKEN,Tt as DeploymentStatus,Ye as DeploymentVia,St as DomainStatus,d as ErrorType,y as FILE_VALIDATION_STATUS,y as FileValidationStatus,B as IDEMPOTENCY_KEY_CONSTRAINTS,Et as JUNK_DIRECTORIES,w as LABEL_CONSTRAINTS,Re as LABEL_PATTERN,bt as MY_API_KEY_URL,Lt as OAuthScope,M as PASSWORD_CONSTRAINTS,Ot as PUBLIC_DEPLOYMENT_TTL_SECONDS,$ as SHIP_ENV,z as SPA_CHECK_CONSTRAINTS,Ee as SPA_DEFAULT_CONFIG,de as Ship,a as ShipError,b as TokenKind,J as UNBUILT_PROJECT_MARKERS,et as UNSAFE_FILENAME_CHARS,Pt as WEB_FILE_ACCEPT,on as __setTestEnvironment,In as allValidFilesReady,De as assertShipJsonSyntax,j as calculateMD5,tt as classifyToken,xe as createAccountResource,Le as createDeploymentResource,we as createDomainResource,be as createTokenResource,Dt as default,kt as deserializeLabels,Ct as extractSubdomain,Ue as filterJunk,oe as formatFileSize,_t as generateDeploymentUrl,Ft as generateDomainUrl,O as getENV,yt as getValidFiles,G as hasUnbuiltMarker,he as hasUnsafeChars,H as isBlockedExtension,vt as isCustomDomain,xt as isDeployment,Se as isPlatformDomain,F as isShipError,Rt as normalizeVia,ke as optimizeDeployPaths,vn as pluralize,Ge as processFilesForNode,$t as serializeLabels,nt as validateApiKey,wt as validateApiUrl,Te as validateCaller,Be as validateDeployFile,Me as validateDeployPath,it as validateDeployToken,ae as validateFileName,Rn as validateFiles,fe as validateIdempotencyKey,ee as validatePassword,Q as validateToken};
1
+ var Ke=Object.defineProperty;var P=(n,t)=>()=>(n&&(t=n(n=0)),t);var je=(n,t)=>{for(var e in t)Ke(n,e,{get:t[e],enumerable:!0})};function Rt(n){if(!n||typeof n!="string")return;let t=n.trim().toLowerCase();return Object.values(Ye).includes(t)?t:void 0}function fe(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>B.MAX_LENGTH)throw a.validation(`Idempotency key must be at most ${B.MAX_LENGTH} characters.`);return t}function Je(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 Qe(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 H(n,t){let e=Qe(n);return e===null?!1:Array.isArray(t)?t.includes(e):t.has(e)}function he(n){return et.test(n)}function G(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>J.has(e))}function tt(n){return n.startsWith(ye.PREFIX)?b.API_KEY:n.startsWith(ge.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:N})}if(e===null||typeof e!="object"||Array.isArray(e))throw a.config(`${N} must contain a JSON object`,{filePath:N})}function Ae(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 nt(n){Ae(n,ye,"API key")}function it(n){Ae(n,ge,"Deploy token")}function Q(n){switch(tt(n)){case b.API_KEY:nt(n);return;case b.DEPLOY_TOKEN:it(n);return;case b.OPAQUE:if(!n)throw a.validation("Token must be a non-empty string")}}function Te(n){if(!n||n.length>_.MAX_LENGTH||!_.PATTERN.test(n))throw a.validation(`Caller must be 1-${_.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function wt(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 xt(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function Se(n,t){return n.endsWith(`.${t}`)}function vt(n,t){return!Se(n,t)}function Ct(n,t){return Se(n,t)?n.slice(0,-(t.length+1)):null}function _t(n){return`https://${n}`}function Ft(n){return`https://${n}`}function $t(n){return!n||n.length===0?null:JSON.stringify(n)}function kt(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}function ee(n){if(n==null)return;if(typeof n!="string")throw a.validation("Password must be a string");let t=n.trim();if(t.length<M.MIN_LENGTH||t.length>M.MAX_LENGTH)throw a.validation(`Password must be between ${M.MIN_LENGTH} and ${M.MAX_LENGTH} characters`);return t}var Tt,Ye,St,B,It,f,I,d,qe,W,Xe,We,a,Ze,Pt,et,J,Nt,me,ye,ge,_,b,Lt,N,Ee,z,Z,$,bt,Ot,y,w,Re,M,g=P(()=>{"use strict";Tt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Ye={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc"},St={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},B={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};It={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"},I={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"},qe=new Set([d.Network,d.Cancelled,d.File,d.Config]),W={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])},Xe=new Set(Object.values(d).filter(n=>!qe.has(n))),We=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"&&Xe.has(p.error)&&(r=p.error)}}else{let c=(await t.text()).trim();c&&!c.startsWith("<")&&c.length<=We&&(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(F(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?Je(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 W.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return W.network.has(this.type)}isAuthError(){return W.auth.has(this.type)}isType(t){return this.type===t}};Ze=["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"],Pt=Ze.map(n=>`.${n}`).join(","),et=/[\x00-\x1f\x7f#?%\\<>"]/;J=new Set(["node_modules","package.json"]);Nt="/auth",me={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},ye={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},ge={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},_={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},b={API_KEY:me.API_KEY,DEPLOY_TOKEN:me.TOKEN,OPAQUE:"opaque"};Lt={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},N="ship.json",Ee={rewrites:[{source:"/(.*)",destination:"/index.html"}]},z={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};Z="https://api.shipstatic.com",$={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},bt="https://my.shipstatic.com/api-key",Ot=4320*60,y={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:"._-"},Re=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;M={MIN_LENGTH:6,MAX_LENGTH:128}});async function lt(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 pt(n){let{createHash:t}=await import("crypto"),e=t("md5");return e.update(n),{md5:e.digest("hex")}}async function ct(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 j(n){if(n instanceof Blob)return lt(n);if(typeof Buffer<"u"&&Buffer.isBuffer(n))return pt(n);if(typeof n=="string")return ct(n);throw a.business("Invalid input for MD5 calculation")}var Y=P(()=>{"use strict";g()});function on(n){ne=n}function dt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function O(){return ne||dt()}var ne,U=P(()=>{"use strict";ne=null});function $e(n){if(!n||n.length===0)return"";let t=n.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let e=t.map(r=>r.split("/").filter(Boolean)),i=[],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 X(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ie=P(()=>{"use strict"});function ke(n,t={}){if(t.flatten===!1)return n.map(i=>({path:X(i),name:se(i)}));let e=ht(n);return n.map(i=>{let s=X(i);if(e){let r=e.endsWith("/")?e:`${e}/`;s.startsWith(r)&&(s=s.substring(r.length))}return s||(s=se(i)),{path:s,name:se(i)}})}function ht(n){if(!n.length)return"";let e=n.map(r=>X(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 se(n){return n.split(/[/\\]/).pop()||n}var re=P(()=>{"use strict";ie()});function oe(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 ae(n){if(he(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 Rn(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(G(o.name))return e.push({file:o.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(c=>({...c,status:y.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let o={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(o),{files:n.map(c=>({...c,status:y.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let r=0;for(let o of n){let c=y.READY,p="Ready for upload",R=o.name?ae(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===y.PROCESSING_ERROR)c=y.VALIDATION_FAILED,p=o.statusMessage||"File failed during processing",e.push({file:o.name,message:p});else if(o.size===0){c=y.EXCLUDED,p="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:p}),s.push({...o,status:c,statusMessage:p});continue}else o.size<0?(c=y.VALIDATION_FAILED,p="File size must be positive",e.push({file:o.name,message:p})):!o.name||o.name.trim().length===0?(c=y.VALIDATION_FAILED,p="File name cannot be empty",e.push({file:o.name||"(empty)",message:p})):o.name.includes("\0")?(c=y.VALIDATION_FAILED,p="File name contains invalid characters (null byte)",e.push({file:o.name,message:p})):R.valid?H(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 (${oe(o.size)}) exceeds limit of ${oe(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 ${oe(t.maxTotalSize)}`,e.push({file:o.name,message:p}))):(c=y.VALIDATION_FAILED,p=R.reason||"Invalid file name",e.push({file:o.name,message:p}));s.push({...o,status:c,statusMessage:p})}e.length>0&&(s=s.map(o=>o.status===y.EXCLUDED?o:{...o,status:y.VALIDATION_FAILED,statusMessage:o.status===y.VALIDATION_FAILED?o.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=e.length===0?s.filter(o=>o.status===y.READY):[],u=e.length===0;return{files:s,validFiles:l,errors:e,warnings:i,canDeploy:u}}function yt(n){return n.filter(t=>t.status===y.READY)}function In(n){return yt(n).length>0}var le=P(()=>{"use strict";g()});import{isJunk as gt}from"junk";function Ue(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&G(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(gt(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(Et.some(u=>l.toLowerCase()===u.toLowerCase()))return!1;return!0})}var Et,pe=P(()=>{"use strict";g();Et=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Me(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 Be(n,t,e){let i=ae(n);if(!i.valid)throw a.business(i.reason||"Invalid file name");if(H(n,e))throw a.business(`File extension not allowed: "${t}"`)}var ce=P(()=>{"use strict";g();le()});var ze={};je(ze,{processFilesForNode:()=>Ge});import*as D from"fs";import*as A from"path";function He(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=He(l,t);e.push(...o)}else u.isFile()&&e.push(l)}return e}async function Ge(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=>J.has(S));if(T)throw a.business(`"${T}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(T){if(F(T))throw T}}let i=n.flatMap(m=>{let h=A.resolve(m);try{return D.statSync(h).isDirectory()?He(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=$e(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=ke(u,{flatten:t.pathDetect!==!1}).map(m=>m.path),p=new Set(Ue(c));if(p.size===0)return[];let R=[],v=[];for(let m=0;m<s.length;m++)p.has(c[m])&&(R.push(s[m]),v.push(c[m]));let x=[],L=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<R.length;m++){let h=R[m],T=v[m];try{Me(T,h);let S=D.statSync(h);if(S.size===0)continue;if(Be(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(L+=S.size,L>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let C=D.readFileSync(h),{md5:Ve}=await j(C);x.push({path:T,content:C,size:C.length,md5:Ve})}catch(S){if(F(S))throw S;let C=S instanceof Error?S.message:String(S);throw a.file(`Failed to read file "${h}": ${C}`,{filePath:h})}}if(x.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return x}var ue=P(()=>{"use strict";g();re();U();pe();Y();ie();ce()});g();g();g();var V=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 k(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((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<w.MIN_LENGTH)throw a.validation(`Labels must be at least ${w.MIN_LENGTH} characters long`);if(r.length>w.MAX_LENGTH)throw a.validation(`Labels must be no more than ${w.MAX_LENGTH} characters long`);if(!Re.test(r))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${w.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 Ie(n){let t=n.find(s=>s.path===N||s.path===`/${N}`);if(!t)return;let e=t.content,i=typeof e.text=="function"?await e.text():t.content.toString("utf8");De(i)}var st=3e4,Pe=3e5,rt=3e5,ot=Pe+rt,at="sdk";function te(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 K=class extends V{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||Z,this.getAuthHeadersCallback=e.getAuthHeaders,this.session=e.session??!1,this.caller=e.caller,this.timeout=e.timeout??st,this.deployTimeout=e.timeout??Pe,this.deployBuildTimeout=e.timeout??ot,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?{[_.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});ee(i.password);let s=fe(i.idempotencyKey),r=k(i.labels);await Ie(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??at,password:i.password,flags:l,captcha:i.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:u,headers:s?{...o,[B.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}${te(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=k(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=k(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}${te(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=k(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}${te(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===z.INDEX_FILE||o.path===`/${z.INDEX_FILE}`);if(!s||s.size>z.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();Y();async function ut(){let n=JSON.stringify(Ee,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await j(t);return{path:N,content:t,size:n.length,md5:e}}async function Ne(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===N))return n;try{if(await t.checkSPA(n,e)){let s=await ut();return[...n,s]}}catch{}return n}function Le(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 Ne(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 we(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 xe(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function be(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 q=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&&Te(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 K({...t,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=Le({...e,processInput:(i,s)=>this.processInput(i,s)}),this.domains=we(e),this.account=xe(e),this.tokens=be(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}`}}};U();g();import{z as Ce}from"zod";import{z as Oe}from"zod";var ve={apiUrl:Oe.string().url().optional(),token:Oe.string().min(1).optional()};U();var mt=Ce.object(ve).strict(),ft={apiUrl:$.API_URL,token:$.TOKEN};function _e(){if(O()!=="node")return{};let n={apiUrl:process.env[$.API_URL]||void 0,token:process.env[$.TOKEN]||void 0};try{return mt.parse(n)}catch(t){if(t instanceof Ce.ZodError){let e=t.issues[0],i=e.path[0],s=(i&&ft[i])??"SHIP environment configuration";throw a.config(`Invalid ${s}: ${e.message}`)}throw a.config("Invalid environment configuration")}}g();async function Fe(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,R=[];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(I.FILES,m),R.push(E.md5)}p.append(I.CHECKSUMS,JSON.stringify(R)),r&&r.length>0&&p.append(I.LABELS,JSON.stringify(r)),l&&p.append(I.VIA,l),u&&p.append(I.PASSWORD,u),o?.build&&p.append(I.BUILD,"true"),o?.prerender&&p.append(I.PRERENDER,"true"),o?.spa&&p.append(I.SPA,"true"),c&&p.append(I.CAPTCHA,c);let v=new s(p),x=[];for await(let E of v.encode())x.push(Buffer.from(E));let L=Buffer.concat(x);return{body:L.buffer.slice(L.byteOffset,L.byteOffset+L.byteLength),headers:{"Content-Type":v.contentType,"Content-Length":Buffer.byteLength(L).toString()}}}g();g();re();U();le();pe();Y();ce();function vn(n,t,e,i=!0){let s=n===1?t:e;return i?`${n} ${s}`:s}ue();var de=class extends q{constructor(t={}){if(O()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=_e();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(()=>(ue(),ze));return s(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return Fe}},Dt=de;export{ye as API_KEY,f as API_PATHS,Nt as AUTH_BASE_PATH,It as AccountPlan,K as ApiHttp,me as AuthMethod,_ as CALLER,Z as DEFAULT_API,N as DEPLOYMENT_CONFIG_FILENAME,I as DEPLOY_FIELDS,ge as DEPLOY_TOKEN,Tt as DeploymentStatus,Ye as DeploymentVia,St as DomainStatus,d as ErrorType,y as FILE_VALIDATION_STATUS,y as FileValidationStatus,B as IDEMPOTENCY_KEY_CONSTRAINTS,Et as JUNK_DIRECTORIES,w as LABEL_CONSTRAINTS,Re as LABEL_PATTERN,bt as MY_API_KEY_URL,Lt as OAuthScope,M as PASSWORD_CONSTRAINTS,Ot as PUBLIC_DEPLOYMENT_TTL_SECONDS,$ as SHIP_ENV,z as SPA_CHECK_CONSTRAINTS,Ee as SPA_DEFAULT_CONFIG,de as Ship,a as ShipError,b as TokenKind,J as UNBUILT_PROJECT_MARKERS,et as UNSAFE_FILENAME_CHARS,Pt as WEB_FILE_ACCEPT,on as __setTestEnvironment,In as allValidFilesReady,De as assertShipJsonSyntax,j as calculateMD5,tt as classifyToken,xe as createAccountResource,Le as createDeploymentResource,we as createDomainResource,be as createTokenResource,Dt as default,kt as deserializeLabels,Ct as extractSubdomain,Ue as filterJunk,oe as formatFileSize,_t as generateDeploymentUrl,Ft as generateDomainUrl,O as getENV,yt as getValidFiles,G as hasUnbuiltMarker,he as hasUnsafeChars,H as isBlockedExtension,vt as isCustomDomain,xt as isDeployment,Se as isPlatformDomain,F as isShipError,Rt as normalizeVia,ke as optimizeDeployPaths,vn as pluralize,Ge as processFilesForNode,$t as serializeLabels,nt as validateApiKey,wt as validateApiUrl,Te as validateCaller,Be as validateDeployFile,Me as validateDeployPath,it as validateDeployToken,ae as validateFileName,Rn as validateFiles,fe as validateIdempotencyKey,ee as validatePassword,Q as validateToken};
2
2
  //# sourceMappingURL=index.js.map