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