@shipstatic/ship 2.0.0-beta.0 → 2.0.0-beta.2
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 +101 -94
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +25 -25
- 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 +106 -94
- package/dist/index.d.ts +106 -94
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +6 -4
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Ye=Object.create;var B=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var Qe=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty;var w=(n,t)=>()=>(n&&(t=n(n=0)),t);var be=(n,t)=>{for(var e in t)B(n,e,{get:t[e],enumerable:!0})},Ne=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Je(t))!Ze.call(n,r)&&r!==e&&B(n,r,{get:()=>t[r],enumerable:!(i=We(t,r))||i.enumerable});return n};var v=(n,t,e)=>(e=n!=null?Ye(Qe(n)):{},Ne(t||!n||!n.__esModule?B(e,"default",{value:n,enumerable:!0}):e,n)),et=n=>Ne(B({},"__esModule",{value:!0}),n);function N(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function F(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return Le.has(e)}function te(n){return Oe.test(n)}function $(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>G.has(e))}function Ce(n){return n.startsWith(ne.PREFIX)?x.API_KEY:n.startsWith(ie.PREFIX)?x.DEPLOY_TOKEN:x.OPAQUE}function Fe(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){Fe(n,ne,"API key")}function _e(n){Fe(n,ie,"Deploy token")}function V(n){switch(Ce(n)){case x.API_KEY:return $e(n);case x.DEPLOY_TOKEN:return _e(n);case x.OPAQUE:if(!n)throw a.validation("Token must be a non-empty string")}}function se(n){if(!n||n.length>H.MAX_LENGTH||!H.PATTERN.test(n))throw a.validation(`Caller must be 1-${H.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function at(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 lt(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function ae(n,t){return n.endsWith(`.${t}`)}function pt(n,t){return!ae(n,t)}function ct(n,t){return ae(n,t)?n.slice(0,-(t.length+1)):null}function ut(n){return`https://${n}`}function dt(n){return`https://${n}`}function mt(n){return!n||n.length===0?null:JSON.stringify(n)}function ft(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<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 tt,nt,it,m,rt,Z,st,a,Le,Oe,G,ee,ne,ie,H,x,ot,z,re,oe,y,R,le,C,g=w(()=>{"use strict";tt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},nt={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},it={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"},rt=new Set([m.Network,m.Cancelled,m.File,m.Config]),Z={client:new Set([m.Business,m.Config,m.File,m.Forbidden,m.Validation]),network:new Set([m.Network]),auth:new Set([m.Authentication])},st=new Set(Object.values(m).filter(n=>!rt.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 o=await t.json();if(o&&typeof o=="object"){let p=o;typeof p.message=="string"?i=p.message:typeof p.error=="string"&&(i=p.error),r=p.details,typeof p.error=="string"&&st.has(p.error)&&(s=p.error)}}else{let o=await t.text();o&&(i=o)}}catch{}i=i||`${e||"Request"} failed with status ${t.status}`;let l=s??(t.status===401?m.Authentication:t.status===403?m.Forbidden:t.status===429?m.RateLimit:m.Api);return new n(l,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 Z.client.has(this.type)}isNetworkError(){return Z.network.has(this.type)}isAuthError(){return Z.auth.has(this.type)}isType(t){return this.type===t}};Le=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"]);Oe=/[\x00-\x1f\x7f#?%\\<>"]/;G=new Set(["node_modules","package.json"]);ee={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},ne={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},ie={PREFIX:"deploy-",HEX_LENGTH:64,TOTAL_LENGTH:71},H={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},x={API_KEY:ee.API_KEY,DEPLOY_TOKEN:ee.TOKEN,OPAQUE:"opaque"};ot={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},z="ship.json",re={rewrites:[{source:"/(.*)",destination:"/index.html"}]};oe="https://api.shipstatic.com",y={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};R={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},le=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;C={MIN_LENGTH:6,MAX_LENGTH:128}});async function yt(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 gt(n){let{createHash:t}=await import("crypto"),e=t("md5");return e.update(n),{md5:e.digest("hex")}}async function Et(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",u=>r(a.business(`Failed to read file for MD5: ${u.message}`))),l.on("data",u=>s.update(u)),l.on("end",()=>i({md5:s.digest("hex")}))})}async function U(n){if(n instanceof Blob)return yt(n);if(typeof Buffer<"u"&&Buffer.isBuffer(n))return gt(n);if(typeof n=="string")return Et(n);throw a.business("Invalid input for MD5 calculation")}var K=w(()=>{"use strict";g()});function St(n){fe=n}function Tt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function I(){return fe||Tt()}var fe,M=w(()=>{"use strict";fe=null});function ge(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,He.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(Ge.some(u=>l.toLowerCase()===u.toLowerCase()))return!1;return!0})}var He,Ge,Ee=w(()=>{"use strict";He=require("junk");g();Ge=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});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(u=>u[s]===l))i.push(l);else break}return i.join("/")}function Y(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var De=w(()=>{"use strict"});function Te(n,t={}){if(t.flatten===!1)return n.map(i=>({path:Y(i),name:Se(i)}));let e=Pt(n);return n.map(i=>{let r=Y(i);if(e){let s=e.endsWith("/")?e:`${e}/`;r.startsWith(s)&&(r=r.substring(s.length))}return r||(r=Se(i)),{path:r,name:Se(i)}})}function Pt(n){if(!n.length)return"";let e=n.map(s=>Y(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(u=>u[s]===l))i.push(l);else break}return i.join("/")}function Se(n){return n.split(/[/\\]/).pop()||n}var Ae=w(()=>{"use strict";De()});function W(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/Math.pow(e,r)).toFixed(t))+" "+i[r]}function J(n){if(te(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 vt(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(p=>({...p,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(p=>({...p,status:y.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let o of n){let p=y.READY,d="Ready for upload",A=o.name?J(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===y.PROCESSING_ERROR)p=y.VALIDATION_FAILED,d=o.statusMessage||"File failed during processing",e.push({file:o.name,message:d});else if(o.size===0){p=y.EXCLUDED,d="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:d}),r.push({...o,status:p,statusMessage:d});continue}else o.size<0?(p=y.VALIDATION_FAILED,d="File size must be positive",e.push({file:o.name,message:d})):!o.name||o.name.trim().length===0?(p=y.VALIDATION_FAILED,d="File name cannot be empty",e.push({file:o.name||"(empty)",message:d})):o.name.includes("\0")?(p=y.VALIDATION_FAILED,d="File name contains invalid characters (null byte)",e.push({file:o.name,message:d})):A.valid?F(o.name)?(p=y.VALIDATION_FAILED,d=`File extension not allowed: "${o.name}"`,e.push({file:o.name,message:d})):o.size>t.maxFileSize?(p=y.VALIDATION_FAILED,d=`File size (${W(o.size)}) exceeds limit of ${W(t.maxFileSize)}`,e.push({file:o.name,message:d})):(s+=o.size,s>t.maxTotalSize&&(p=y.VALIDATION_FAILED,d=`Total size would exceed limit of ${W(t.maxTotalSize)}`,e.push({file:o.name,message:d}))):(p=y.VALIDATION_FAILED,d=A.reason||"Invalid file name",e.push({file:o.name,message:d}));r.push({...o,status:p,statusMessage:d})}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):[],u=e.length===0;return{files:r,validFiles:l,errors:e,warnings:i,canDeploy:u}}function Ve(n){return n.filter(t=>t.status===y.READY)}function xt(n){return Ve(n).length>0}var we=w(()=>{"use strict";g()});function Re(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=J(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if(F(n))throw a.business(`File extension not allowed: "${t}"`)}var ve=w(()=>{"use strict";g();we()});var qe={};be(qe,{processFilesForNode:()=>xe});function je(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),u=E.statSync(l);if(u.isDirectory()){let o=je(l,t);e.push(...o)}else u.isFile()&&e.push(l)}return e}async function xe(n,t={},e){if(I()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let c of n){let f=D.resolve(c);try{if(E.statSync(f).isDirectory()){let S=E.readdirSync(f).find(T=>G.has(T));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(c=>{let f=D.resolve(c);try{return E.statSync(f).isDirectory()?je(f):[f]}catch{throw a.file(`Path does not exist: ${c}`,{filePath:c})}}),r=[...new Set(i)],s=n.map(c=>D.resolve(c)),l=ze(s.map(c=>{try{return E.statSync(c).isDirectory()?c:D.dirname(c)}catch{return D.dirname(c)}})),u=r.map(c=>{if(l&&l.length>0){let f=D.relative(l,c);if(f&&typeof f=="string"&&!f.startsWith(".."))return f.replace(/\\/g,"/")}return D.basename(c)}),p=Te(u,{flatten:t.pathDetect!==!1}).map(c=>c.path),d=new Set(ge(p));if(d.size===0)return[];let A=[],L=[];for(let c=0;c<r.length;c++)d.has(p[c])&&(A.push(r[c]),L.push(p[c]));let b=[],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<A.length;c++){let f=A[c],S=L[c];try{Re(S,f);let T=E.statSync(f);if(T.size===0)continue;if(Pe(S,f),T.size>e.maxFileSize)throw a.business(`File ${f} is too large. Maximum allowed size is ${e.maxFileSize/(1024*1024)}MB.`);if(P+=T.size,P>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let O=E.readFileSync(f),{md5:Xe}=await U(O);b.push({path:S,content:O,size:O.length,md5:Xe})}catch(T){if(N(T))throw T;let O=T instanceof Error?T.message:String(T);throw a.file(`Failed to read file "${f}": ${O}`,{filePath:f})}}if(b.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return b}var E,D,Ie=w(()=>{"use strict";M();K();Ee();ve();g();Ae();De();E=v(require("fs"),1),D=v(require("path"),1)});var It={};be(It,{API_KEY:()=>ne,AccountPlan:()=>it,ApiHttp:()=>k,AuthMethod:()=>ee,BLOCKED_EXTENSIONS:()=>Le,CALLER:()=>H,DEFAULT_API:()=>oe,DEPLOYMENT_CONFIG_FILENAME:()=>z,DEPLOY_TOKEN:()=>ie,DeploymentStatus:()=>tt,DomainStatus:()=>nt,ErrorType:()=>m,FILE_VALIDATION_STATUS:()=>y,FileValidationStatus:()=>y,JUNK_DIRECTORIES:()=>Ge,LABEL_CONSTRAINTS:()=>R,LABEL_PATTERN:()=>le,OAuthScope:()=>ot,PASSWORD_CONSTRAINTS:()=>C,SPA_DEFAULT_CONFIG:()=>re,Ship:()=>Q,ShipError:()=>a,TokenKind:()=>x,UNBUILT_PROJECT_MARKERS:()=>G,UNSAFE_FILENAME_CHARS:()=>Oe,__setTestEnvironment:()=>St,allValidFilesReady:()=>xt,calculateMD5:()=>U,classifyToken:()=>Ce,createAccountResource:()=>de,createDeploymentResource:()=>ce,createDomainResource:()=>ue,createTokenResource:()=>me,default:()=>Ke,deserializeLabels:()=>ft,extractSubdomain:()=>ct,filterJunk:()=>ge,formatFileSize:()=>W,generateDeploymentUrl:()=>ut,generateDomainUrl:()=>dt,getENV:()=>I,getValidFiles:()=>Ve,hasUnbuiltMarker:()=>$,hasUnsafeChars:()=>te,isBlockedExtension:()=>F,isCustomDomain:()=>pt,isDeployment:()=>lt,isPlatformDomain:()=>ae,isShipError:()=>N,mergeDeployOptions:()=>pe,optimizeDeployPaths:()=>Te,pluralize:()=>Rt,processFilesForNode:()=>xe,serializeLabels:()=>mt,validateApiKey:()=>$e,validateApiUrl:()=>at,validateCaller:()=>se,validateDeployFile:()=>Pe,validateDeployPath:()=>Re,validateDeployToken:()=>_e,validateFileName:()=>J,validateFiles:()=>vt,validatePassword:()=>j,validateToken:()=>V});module.exports=et(It);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 u=l instanceof Error?l:new Error(String(l));this.emit("error",u,String(t))},0)}}};g();g();function _(n){if(n==null)return;if(n.length===0)return n;if(n.length>R.MAX_COUNT)throw a.validation(`Maximum ${R.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<R.MIN_LENGTH)throw a.validation(`Labels must be at least ${R.MIN_LENGTH} characters long`);if(s.length>R.MAX_LENGTH)throw a.validation(`Labels must be no more than ${R.MAX_LENGTH} characters long`);if(!le.test(s))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${R.SEPARATORS}) between segments`);return s}),e=[...new Set(t)];if(e.length!==t.length)throw a.validation("Duplicate labels are not allowed");return e}var h={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},ht=3e4,k=class extends q{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||oe,this.getAuthHeadersCallback=e.getAuthHeaders,this.session=e.session??!1,this.caller=e.caller,this.timeout=e.timeout??ht,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),u=this.createTimeoutSignal(i.signal);s=u.cleanup;let o={...i,headers:l,credentials:this.session&&!l.Authorization?"include":void 0,signal:u.signal};this.emit("request",e,o);let p=await this.fetch(e,o);if(s(),!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(l){s();let u=a.fromFetchError(l,r);throw this.emit("error",u,e),u}}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});j(i.password);let r=_(i.labels),s=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:l,headers:u}=await this.createDeployBody(e,{labels:r,via:i.via,password:i.password,flags:s,captcha:i.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:l,headers:u,signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}`,{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=_(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=_(r),l={};i&&(l.deployment=i),s!==void 0&&(l.labels=s);let{data:u,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{...u,isCreate:o===201}}async listDomains(){return this.request(`${this.apiUrl}${h.DOMAINS}`,{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=_(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(){return this.request(`${this.apiUrl}${h.TOKENS}`,{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();function pe(n,t){let e={...n};return e.timeout===void 0&&t.timeout!==void 0&&(e.timeout=t.timeout),e.maxConcurrency===void 0&&t.maxConcurrency!==void 0&&(e.maxConcurrency=t.maxConcurrency),e.onProgress===void 0&&t.onProgress!==void 0&&(e.onProgress=t.onProgress),e}g();K();async function Dt(){let n=JSON.stringify(re,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await U(t);return{path:z,content:t,size:n.length,md5:e}}async function ke(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===z))return n;try{if(await t.checkSPA(n,e)){let r=await Dt();return[...n,r]}}catch{}return n}function ce(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:r}=n;return{upload:async(s,l={})=>{await e();let u=r?pe(l,r):l;if(!i)throw a.config("processInput function is not provided.");let o=t(),p=await i(s,u);return p=await ke(p,o,u),o.deploy(p,u)},list:async()=>(await e(),t().listDeployments()),get:async s=>(await e(),t().getDeployment(s)),set:async(s,l)=>(await e(),t().updateDeploymentLabels(s,l.labels)),remove:async s=>{await e(),await t().removeDeployment(s)}}}function ue(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,r={})=>(await e(),t().setDomain(i,r.deployment,r.labels)),list:async()=>(await e(),t().listDomains()),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 de(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function me(n){let{getApi:t,ensureInit:e}=n;return{create:async(i={})=>(await e(),t().createToken(i.ttl,i.labels)),list:async()=>(await e(),t().listTokens()),remove:async i=>{await e(),await 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&&se(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 k({...t,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=ce({...e,processInput:(i,r)=>this.processInput(i,r),clientDefaults:this.clientOptions}),this.domains=ue(e),this.account=de(e),this.tokens=me(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}`}}};g();M();var ye=require("zod");g();M();var he=require("zod"),Ue={apiUrl:he.z.string().url().optional(),token:he.z.string().min(1).optional()};var At=ye.z.object(Ue).strict(),wt={apiUrl:"SHIP_API_URL",token:"SHIP_TOKEN"};function Me(){if(I()!=="node")return{};let n={apiUrl:process.env.SHIP_API_URL||void 0,token:process.env.SHIP_TOKEN||void 0};try{return At.parse(n)}catch(t){if(t instanceof ye.z.ZodError){let e=t.issues[0],i=e.path[0],r=(i&&wt[i])??"SHIP environment configuration";throw a.config(`Invalid ${r}: ${e.message}`)}throw a.config("Invalid environment configuration")}}g();async function Be(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),{labels:s,via:l,password:u,flags:o,captcha:p}=t,d=new e,A=[];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 f=new i([c.content],c.path,{type:"application/octet-stream"});d.append("files[]",f),A.push(c.md5)}d.append("checksums",JSON.stringify(A)),s&&s.length>0&&d.append("labels",JSON.stringify(s)),l&&d.append("via",l),u&&d.append("password",u),o?.build&&d.append("build","true"),o?.prerender&&d.append("prerender","true"),o?.spa&&d.append("spa","true"),p&&d.append("captcha",p);let L=new r(d),b=[];for await(let c of L.encode())b.push(Buffer.from(c));let P=Buffer.concat(b);return{body:P.buffer.slice(P.byteOffset,P.byteOffset+P.byteLength),headers:{"Content-Type":L.contentType,"Content-Length":Buffer.byteLength(P).toString()}}}K();function Rt(n,t,e,i=!0){let r=n===1?t:e;return i?`${n} ${r}`:r}Ee();Ae();M();we();ve();g();Ie();var Q=class extends X{constructor(t={}){if(I()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=Me();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(()=>(Ie(),qe));return r(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return Be}},Ke=Q;0&&(module.exports={API_KEY,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,calculateMD5,classifyToken,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getENV,getValidFiles,hasUnbuiltMarker,hasUnsafeChars,isBlockedExtension,isCustomDomain,isDeployment,isPlatformDomain,isShipError,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,serializeLabels,validateApiKey,validateApiUrl,validateCaller,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles,validatePassword,validateToken});
|
|
1
|
+
"use strict";var Ye=Object.create;var B=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var Qe=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty;var w=(n,t)=>()=>(n&&(t=n(n=0)),t);var be=(n,t)=>{for(var e in t)B(n,e,{get:t[e],enumerable:!0})},Ne=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Je(t))!Ze.call(n,r)&&r!==e&&B(n,r,{get:()=>t[r],enumerable:!(i=We(t,r))||i.enumerable});return n};var v=(n,t,e)=>(e=n!=null?Ye(Qe(n)):{},Ne(t||!n||!n.__esModule?B(e,"default",{value:n,enumerable:!0}):e,n)),et=n=>Ne(B({},"__esModule",{value:!0}),n);function N(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function C(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return Le.has(e)}function ne(n){return Oe.test(n)}function $(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>G.has(e))}function Fe(n){return n.startsWith(ie.PREFIX)?x.API_KEY:n.startsWith(re.PREFIX)?x.DEPLOY_TOKEN:x.OPAQUE}function Ce(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){Ce(n,ie,"API key")}function _e(n){Ce(n,re,"Deploy token")}function V(n){switch(Fe(n)){case x.API_KEY:$e(n);return;case x.DEPLOY_TOKEN:_e(n);return;case x.OPAQUE:if(!n)throw a.validation("Token must be a non-empty string")}}function oe(n){if(!n||n.length>H.MAX_LENGTH||!H.PATTERN.test(n))throw a.validation(`Caller must be 1-${H.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function at(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 lt(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function ae(n,t){return n.endsWith(`.${t}`)}function pt(n,t){return!ae(n,t)}function ct(n,t){return ae(n,t)?n.slice(0,-(t.length+1)):null}function ut(n){return`https://${n}`}function dt(n){return`https://${n}`}function mt(n){return!n||n.length===0?null:JSON.stringify(n)}function ft(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<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 tt,nt,it,m,rt,ee,st,a,Le,Oe,G,te,ie,re,H,x,ot,z,se,j,y,R,le,F,g=w(()=>{"use strict";tt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},nt={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},it={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"},rt=new Set([m.Network,m.Cancelled,m.File,m.Config]),ee={client:new Set([m.Business,m.Config,m.File,m.Forbidden,m.Validation]),network:new Set([m.Network]),auth:new Set([m.Authentication])},st=new Set(Object.values(m).filter(n=>!rt.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 o=await t.json();if(o&&typeof o=="object"){let p=o;typeof p.message=="string"?i=p.message:typeof p.error=="string"&&(i=p.error),r=p.details,typeof p.error=="string"&&st.has(p.error)&&(s=p.error)}}else{let o=await t.text();o&&(i=o)}}catch{}i=i||`${e||"Request"} failed with status ${t.status}`;let l=s??(t.status===401?m.Authentication:t.status===403?m.Forbidden:t.status===429?m.RateLimit:m.Api);return new n(l,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)}isNetworkError(){return ee.network.has(this.type)}isAuthError(){return ee.auth.has(this.type)}isType(t){return this.type===t}};Le=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"]);Oe=/[\x00-\x1f\x7f#?%\\<>"]/;G=new Set(["node_modules","package.json"]);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},H={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},x={API_KEY:te.API_KEY,DEPLOY_TOKEN:te.TOKEN,OPAQUE:"opaque"};ot={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},z="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"};R={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},le=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;F={MIN_LENGTH:6,MAX_LENGTH:128}});async function yt(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 gt(n){let{createHash:t}=await import("crypto"),e=t("md5");return e.update(n),{md5:e.digest("hex")}}async function Et(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",u=>r(a.business(`Failed to read file for MD5: ${u.message}`))),l.on("data",u=>s.update(u)),l.on("end",()=>i({md5:s.digest("hex")}))})}async function U(n){if(n instanceof Blob)return yt(n);if(typeof Buffer<"u"&&Buffer.isBuffer(n))return gt(n);if(typeof n=="string")return Et(n);throw a.business("Invalid input for MD5 calculation")}var X=w(()=>{"use strict";g()});function St(n){fe=n}function Tt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function I(){return fe||Tt()}var fe,M=w(()=>{"use strict";fe=null});function He(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(u=>u[s]===l))i.push(l);else break}return i.join("/")}function W(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ge=w(()=>{"use strict"});function De(n,t={}){if(t.flatten===!1)return n.map(i=>({path:W(i),name:Ee(i)}));let e=Rt(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=Ee(i)),{path:r,name:Ee(i)}})}function Rt(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(u=>u[s]===l))i.push(l);else break}return i.join("/")}function Ee(n){return n.split(/[/\\]/).pop()||n}var Se=w(()=>{"use strict";ge()});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 Pt(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(p=>({...p,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(p=>({...p,status:y.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let o of n){let p=y.READY,d="Ready for upload",A=o.name?Q(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===y.PROCESSING_ERROR)p=y.VALIDATION_FAILED,d=o.statusMessage||"File failed during processing",e.push({file:o.name,message:d});else if(o.size===0){p=y.EXCLUDED,d="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:d}),r.push({...o,status:p,statusMessage:d});continue}else o.size<0?(p=y.VALIDATION_FAILED,d="File size must be positive",e.push({file:o.name,message:d})):!o.name||o.name.trim().length===0?(p=y.VALIDATION_FAILED,d="File name cannot be empty",e.push({file:o.name||"(empty)",message:d})):o.name.includes("\0")?(p=y.VALIDATION_FAILED,d="File name contains invalid characters (null byte)",e.push({file:o.name,message:d})):A.valid?C(o.name)?(p=y.VALIDATION_FAILED,d=`File extension not allowed: "${o.name}"`,e.push({file:o.name,message:d})):o.size>t.maxFileSize?(p=y.VALIDATION_FAILED,d=`File size (${J(o.size)}) exceeds limit of ${J(t.maxFileSize)}`,e.push({file:o.name,message:d})):(s+=o.size,s>t.maxTotalSize&&(p=y.VALIDATION_FAILED,d=`Total size would exceed limit of ${J(t.maxTotalSize)}`,e.push({file:o.name,message:d}))):(p=y.VALIDATION_FAILED,d=A.reason||"Invalid file name",e.push({file:o.name,message:d}));r.push({...o,status:p,statusMessage:d})}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):[],u=e.length===0;return{files:r,validFiles:l,errors:e,warnings:i,canDeploy:u}}function Ge(n){return n.filter(t=>t.status===y.READY)}function vt(n){return Ge(n).length>0}var Te=w(()=>{"use strict";g()});function Ae(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,ze.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(Ve.some(u=>l.toLowerCase()===u.toLowerCase()))return!1;return!0})}var ze,Ve,we=w(()=>{"use strict";g();ze=require("junk"),Ve=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Re(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(C(n))throw a.business(`File extension not allowed: "${t}"`)}var ve=w(()=>{"use strict";g();Te()});var qe={};be(qe,{processFilesForNode:()=>xe});function je(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),u=E.statSync(l);if(u.isDirectory()){let o=je(l,t);e.push(...o)}else u.isFile()&&e.push(l)}return e}async function xe(n,t={},e){if(I()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let c of n){let f=D.resolve(c);try{if(E.statSync(f).isDirectory()){let S=E.readdirSync(f).find(T=>G.has(T));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(c=>{let f=D.resolve(c);try{return E.statSync(f).isDirectory()?je(f):[f]}catch{throw a.file(`Path does not exist: ${c}`,{filePath:c})}}),r=[...new Set(i)],s=n.map(c=>D.resolve(c)),l=He(s.map(c=>{try{return E.statSync(c).isDirectory()?c:D.dirname(c)}catch{return D.dirname(c)}})),u=r.map(c=>{if(l&&l.length>0){let f=D.relative(l,c);if(f&&typeof f=="string"&&!f.startsWith(".."))return f.replace(/\\/g,"/")}return D.basename(c)}),p=De(u,{flatten:t.pathDetect!==!1}).map(c=>c.path),d=new Set(Ae(p));if(d.size===0)return[];let A=[],L=[];for(let c=0;c<r.length;c++)d.has(p[c])&&(A.push(r[c]),L.push(p[c]));let b=[],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<A.length;c++){let f=A[c],S=L[c];try{Re(S,f);let T=E.statSync(f);if(T.size===0)continue;if(Pe(S,f),T.size>e.maxFileSize)throw a.business(`File ${f} is too large. Maximum allowed size is ${e.maxFileSize/(1024*1024)}MB.`);if(P+=T.size,P>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let O=E.readFileSync(f),{md5:Xe}=await U(O);b.push({path:S,content:O,size:O.length,md5:Xe})}catch(T){if(N(T))throw T;let O=T instanceof Error?T.message:String(T);throw a.file(`Failed to read file "${f}": ${O}`,{filePath:f})}}if(b.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return b}var E,D,Ie=w(()=>{"use strict";E=v(require("fs"),1),D=v(require("path"),1);g();Se();M();we();X();ge();ve()});var It={};be(It,{API_KEY:()=>ie,AccountPlan:()=>it,ApiHttp:()=>k,AuthMethod:()=>te,BLOCKED_EXTENSIONS:()=>Le,CALLER:()=>H,DEFAULT_API:()=>j,DEPLOYMENT_CONFIG_FILENAME:()=>z,DEPLOY_TOKEN:()=>re,DeploymentStatus:()=>tt,DomainStatus:()=>nt,ErrorType:()=>m,FILE_VALIDATION_STATUS:()=>y,FileValidationStatus:()=>y,JUNK_DIRECTORIES:()=>Ve,LABEL_CONSTRAINTS:()=>R,LABEL_PATTERN:()=>le,OAuthScope:()=>ot,PASSWORD_CONSTRAINTS:()=>F,SPA_DEFAULT_CONFIG:()=>se,Ship:()=>Z,ShipError:()=>a,TokenKind:()=>x,UNBUILT_PROJECT_MARKERS:()=>G,UNSAFE_FILENAME_CHARS:()=>Oe,__setTestEnvironment:()=>St,allValidFilesReady:()=>vt,calculateMD5:()=>U,classifyToken:()=>Fe,createAccountResource:()=>de,createDeploymentResource:()=>ce,createDomainResource:()=>ue,createTokenResource:()=>me,default:()=>Ke,deserializeLabels:()=>ft,extractSubdomain:()=>ct,filterJunk:()=>Ae,formatFileSize:()=>J,generateDeploymentUrl:()=>ut,generateDomainUrl:()=>dt,getENV:()=>I,getValidFiles:()=>Ge,hasUnbuiltMarker:()=>$,hasUnsafeChars:()=>ne,isBlockedExtension:()=>C,isCustomDomain:()=>pt,isDeployment:()=>lt,isPlatformDomain:()=>ae,isShipError:()=>N,mergeDeployOptions:()=>pe,optimizeDeployPaths:()=>De,pluralize:()=>xt,processFilesForNode:()=>xe,serializeLabels:()=>mt,validateApiKey:()=>$e,validateApiUrl:()=>at,validateCaller:()=>oe,validateDeployFile:()=>Pe,validateDeployPath:()=>Re,validateDeployToken:()=>_e,validateFileName:()=>Q,validateFiles:()=>Pt,validatePassword:()=>q,validateToken:()=>V});module.exports=et(It);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 u=l instanceof Error?l:new Error(String(l));this.emit("error",u,String(t))},0)}}};g();g();function _(n){if(n==null)return;if(n.length===0)return n;if(n.length>R.MAX_COUNT)throw a.validation(`Maximum ${R.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<R.MIN_LENGTH)throw a.validation(`Labels must be at least ${R.MIN_LENGTH} characters long`);if(s.length>R.MAX_LENGTH)throw a.validation(`Labels must be no more than ${R.MAX_LENGTH} characters long`);if(!le.test(s))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${R.SEPARATORS}) between segments`);return s}),e=[...new Set(t)];if(e.length!==t.length)throw a.validation("Duplicate labels are not allowed");return e}var h={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},ht=3e4,k=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??ht,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),u=this.createTimeoutSignal(i.signal);s=u.cleanup;let o={...i,headers:l,credentials:this.session&&!l.Authorization?"include":void 0,signal:u.signal};this.emit("request",e,o);let p=await this.fetch(e,o);if(s(),!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(l){s();let u=a.fromFetchError(l,r);throw this.emit("error",u,e),u}}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=_(i.labels),s=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:l,headers:u}=await this.createDeployBody(e,{labels:r,via:i.via,password:i.password,flags:s,captcha:i.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:l,headers:u,signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}`,{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=_(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=_(r),l={};i&&(l.deployment=i),s!==void 0&&(l.labels=s);let{data:u,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{...u,isCreate:o===201}}async listDomains(){return this.request(`${this.apiUrl}${h.DOMAINS}`,{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=_(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(){return this.request(`${this.apiUrl}${h.TOKENS}`,{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();function pe(n,t){let e={...n};return e.timeout===void 0&&t.timeout!==void 0&&(e.timeout=t.timeout),e.maxConcurrency===void 0&&t.maxConcurrency!==void 0&&(e.maxConcurrency=t.maxConcurrency),e.onProgress===void 0&&t.onProgress!==void 0&&(e.onProgress=t.onProgress),e}g();X();async function Dt(){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 U(t);return{path:z,content:t,size:n.length,md5:e}}async function ke(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===z))return n;try{if(await t.checkSPA(n,e)){let r=await Dt();return[...n,r]}}catch{}return n}function ce(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:r}=n;return{upload:async(s,l={})=>{await e();let u=r?pe(l,r):l;if(!i)throw a.config("processInput function is not provided.");let o=t(),p=await i(s,u);return p=await ke(p,o,u),o.deploy(p,u)},list:async()=>(await e(),t().listDeployments()),get:async s=>(await e(),t().getDeployment(s)),set:async(s,l)=>(await e(),t().updateDeploymentLabels(s,l.labels)),remove:async s=>{await e(),await t().removeDeployment(s)}}}function ue(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,r={})=>(await e(),t().setDomain(i,r.deployment,r.labels)),list:async()=>(await e(),t().listDomains()),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 de(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function me(n){let{getApi:t,ensureInit:e}=n;return{create:async(i={})=>(await e(),t().createToken(i.ttl,i.labels)),list:async()=>(await e(),t().listTokens()),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&&oe(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 k({...t,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=ce({...e,processInput:(i,r)=>this.processInput(i,r),clientDefaults:this.clientOptions}),this.domains=ue(e),this.account=de(e),this.tokens=me(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}`}}};M();g();var ye=require("zod");var he=require("zod"),Ue={apiUrl:he.z.string().url().optional(),token:he.z.string().min(1).optional()};M();var At=ye.z.object(Ue).strict(),wt={apiUrl:"SHIP_API_URL",token:"SHIP_TOKEN"};function Me(){if(I()!=="node")return{};let n={apiUrl:process.env.SHIP_API_URL||void 0,token:process.env.SHIP_TOKEN||void 0};try{return At.parse(n)}catch(t){if(t instanceof ye.z.ZodError){let e=t.issues[0],i=e.path[0],r=(i&&wt[i])??"SHIP environment configuration";throw a.config(`Invalid ${r}: ${e.message}`)}throw a.config("Invalid environment configuration")}}g();async function Be(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),{labels:s,via:l,password:u,flags:o,captcha:p}=t,d=new e,A=[];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 f=new i([c.content],c.path,{type:"application/octet-stream"});d.append("files[]",f),A.push(c.md5)}d.append("checksums",JSON.stringify(A)),s&&s.length>0&&d.append("labels",JSON.stringify(s)),l&&d.append("via",l),u&&d.append("password",u),o?.build&&d.append("build","true"),o?.prerender&&d.append("prerender","true"),o?.spa&&d.append("spa","true"),p&&d.append("captcha",p);let L=new r(d),b=[];for await(let c of L.encode())b.push(Buffer.from(c));let P=Buffer.concat(b);return{body:P.buffer.slice(P.byteOffset,P.byteOffset+P.byteLength),headers:{"Content-Type":L.contentType,"Content-Length":Buffer.byteLength(P).toString()}}}g();g();Se();M();Te();we();X();ve();function xt(n,t,e,i=!0){let r=n===1?t:e;return i?`${n} ${r}`:r}Ie();var Z=class extends Y{constructor(t={}){if(I()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=Me();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(()=>(Ie(),qe));return r(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return Be}},Ke=Z;0&&(module.exports={API_KEY,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,calculateMD5,classifyToken,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getENV,getValidFiles,hasUnbuiltMarker,hasUnsafeChars,isBlockedExtension,isCustomDomain,isDeployment,isPlatformDomain,isShipError,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,serializeLabels,validateApiKey,validateApiUrl,validateCaller,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles,validatePassword,validateToken});
|
|
2
2
|
|
|
3
3
|
// Ship SDK: Enable axios-style CommonJS imports
|
|
4
4
|
const originalExports = module.exports;
|