@shipstatic/ship 1.0.1 → 1.0.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.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +14 -14
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var He=Object.create;var z=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Ve=Object.prototype.hasOwnProperty;var x=(n,t)=>()=>(n&&(t=n(n=0)),t);var ve=(n,t)=>{for(var e in t)z(n,e,{get:t[e],enumerable:!0})},Ie=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ke(t))!Ve.call(n,r)&&r!==e&&z(n,r,{get:()=>t[r],enumerable:!(i=ze(t,r))||i.enumerable});return n};var b=(n,t,e)=>(e=n!=null?He(Ge(n)):{},Ie(t||!n||!n.__esModule?z(e,"default",{value:n,enumerable:!0}):e,n)),je=n=>Ie(z({},"__esModule",{value:!0}),n);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 xe.has(e)}function te(n){return Pe.test(n)}function k(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>K.has(e))}function Ze(n){if(!n.startsWith(R.PREFIX))throw a.validation(`API key must start with "${R.PREFIX}"`);if(n.length!==R.TOTAL_LENGTH)throw a.validation(`API key must be ${R.TOTAL_LENGTH} characters total (${R.PREFIX} + ${R.HEX_LENGTH} hex chars)`);let t=n.slice(R.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`API key must contain ${R.HEX_LENGTH} hexadecimal characters after "${R.PREFIX}" prefix`)}function et(n){if(!n.startsWith(v.PREFIX))throw a.validation(`Deploy token must start with "${v.PREFIX}"`);if(n.length!==v.TOTAL_LENGTH)throw a.validation(`Deploy token must be ${v.TOTAL_LENGTH} characters total (${v.PREFIX} + ${v.HEX_LENGTH} hex chars)`);let t=n.slice(v.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`Deploy token must contain ${v.HEX_LENGTH} hexadecimal characters after "${v.PREFIX}" prefix`)}function tt(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 nt(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function ie(n,t){return n.endsWith(`.${t}`)}function it(n,t){return!ie(n,t)}function rt(n,t){return ie(n,t)?n.slice(0,-(t.length+1)):null}function st(n){return`https://${n}`}function ot(n){return`https://${n}`}function at(n){return!n||n.length===0?null:JSON.stringify(n)}function lt(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}function V(n){if(n==null)return;if(typeof n!="string")throw a.validation("Password must be a string");let t=n.trim();if(t.length<O.MIN_LENGTH||t.length>O.MAX_LENGTH)throw a.validation(`Password must be between ${O.MIN_LENGTH} and ${O.MAX_LENGTH} characters`);return t}var qe,Xe,Ye,d,We,ee,Je,a,xe,Pe,K,R,v,Qe,G,ne,U,y,P,re,O,g=x(()=>{"use strict";qe={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Xe={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Ye={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},d={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"},We=new Set([d.Network,d.Cancelled,d.File,d.Config]),ee={client:new Set([d.Business,d.Config,d.File,d.Forbidden,d.Validation]),network:new Set([d.Network]),auth:new Set([d.Authentication])},Je=new Set(Object.values(d).filter(n=>!We.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===d.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static async fromHttpResponse(t,e){let i,r,s;try{if(t.headers.get("content-type")?.includes("application/json")){let o=await t.json();if(o&&typeof o=="object"){let l=o;typeof l.message=="string"?i=l.message:typeof l.error=="string"&&(i=l.error),r=l.details,typeof l.error=="string"&&Je.has(l.error)&&(s=l.error)}}else{let o=await t.text();o&&(i=o)}}catch{}i=i||`${e||"Request"} failed with status ${t.status}`;let p=s??(t.status===401?d.Authentication:t.status===403?d.Forbidden:t.status===429?d.RateLimit:d.Api);return new n(p,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(d.Api,`${i} failed: ${t.message}`):new n(d.Api,`${i} failed: Unknown error`)}static validation(t,e){return new n(d.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(d.NotFound,i,404)}static forbidden(t,e){return new n(d.Forbidden,t,403,e)}static rateLimit(t="Too many requests",e){return new n(d.RateLimit,t,429,e)}static authentication(t="Authentication required",e){return new n(d.Authentication,t,401,e)}static business(t,e=400,i){return new n(d.Business,t,e,i)}static network(t,e){return new n(d.Network,t,void 0,e)}static cancelled(t,e){return new n(d.Cancelled,t,void 0,e)}static file(t,e){return new n(d.File,t,void 0,e)}static config(t,e){return new n(d.Config,t,void 0,e)}static api(t,e=500,i){return new n(d.Api,t,e,i)}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}};xe=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"]);Pe=/[\x00-\x1f\x7f#?%\\<>"]/;K=new Set(["node_modules","package.json"]);R={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},v={PREFIX:"token-",HEX_LENGTH:64,TOTAL_LENGTH:70},Qe={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},G="ship.json",ne={rewrites:[{source:"/(.*)",destination:"/index.html"}]};U="https://api.shipstatic.com",y={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};P={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},re=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;O={MIN_LENGTH:6,MAX_LENGTH:128}});async function ct(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 ut(n){let{createHash:t}=await import("crypto"),e=t("md5");return e.update(n),{md5:e.digest("hex")}}async function dt(n){let{createHash:t}=await import("crypto"),{createReadStream:e}=await import("fs");return new Promise((i,r)=>{let s=t("md5"),p=e(n);p.on("error",c=>r(a.business(`Failed to read file for MD5: ${c.message}`))),p.on("data",c=>s.update(c)),p.on("end",()=>i({md5:s.digest("hex")}))})}async function M(n){if(n instanceof Blob)return ct(n);if(typeof Buffer<"u"&&Buffer.isBuffer(n))return ut(n);if(typeof n=="string")return dt(n);throw a.business("Invalid input for MD5 calculation")}var q=x(()=>{"use strict";g()});function ft(n){ue=n}function ht(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function C(){return ue||ht()}var ue,H=x(()=>{"use strict";ue=null});function me(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&k(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,Fe.isJunk)(r))return!1;for(let p of i)if(p!==".well-known"&&(p.startsWith(".")||p.length>255))return!1;let s=i.slice(0,-1);for(let p of s)if(Oe.some(c=>p.toLowerCase()===c.toLowerCase()))return!1;return!0})}var Fe,Oe,fe=x(()=>{"use strict";Fe=require("junk");g();Oe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function $e(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 p=e[0][s];if(e.every(c=>c[s]===p))i.push(p);else break}return i.join("/")}function W(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var he=x(()=>{"use strict"});function ge(n,t={}){if(t.flatten===!1)return n.map(i=>({path:W(i),name:ye(i)}));let e=Dt(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=ye(i)),{path:r,name:ye(i)}})}function Dt(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 p=e[0][s];if(e.every(c=>c[s]===p))i.push(p);else break}return i.join("/")}function ye(n){return n.split(/[/\\]/).pop()||n}var Ee=x(()=>{"use strict";he()});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/Math.pow(e,r)).toFixed(t))+" "+i[r]}function Q(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 St(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(k(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(l=>({...l,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(l=>({...l,status:y.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let o of n){let l=y.READY,u="Ready for upload",E=o.name?Q(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===y.PROCESSING_ERROR)l=y.VALIDATION_FAILED,u=o.statusMessage||"File failed during processing",e.push({file:o.name,message:u});else if(o.size===0){l=y.EXCLUDED,u="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:u}),r.push({...o,status:l,statusMessage:u});continue}else o.size<0?(l=y.VALIDATION_FAILED,u="File size must be positive",e.push({file:o.name,message:u})):!o.name||o.name.trim().length===0?(l=y.VALIDATION_FAILED,u="File name cannot be empty",e.push({file:o.name||"(empty)",message:u})):o.name.includes("\0")?(l=y.VALIDATION_FAILED,u="File name contains invalid characters (null byte)",e.push({file:o.name,message:u})):E.valid?$(o.name)?(l=y.VALIDATION_FAILED,u=`File extension not allowed: "${o.name}"`,e.push({file:o.name,message:u})):o.size>t.maxFileSize?(l=y.VALIDATION_FAILED,u=`File size (${J(o.size)}) exceeds limit of ${J(t.maxFileSize)}`,e.push({file:o.name,message:u})):(s+=o.size,s>t.maxTotalSize&&(l=y.VALIDATION_FAILED,u=`Total size would exceed limit of ${J(t.maxTotalSize)}`,e.push({file:o.name,message:u}))):(l=y.VALIDATION_FAILED,u=E.reason||"Invalid file name",e.push({file:o.name,message:u}));r.push({...o,status:l,statusMessage:u})}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 p=e.length===0?r.filter(o=>o.status===y.READY):[],c=e.length===0;return{files:r,validFiles:p,errors:e,warnings:i,canDeploy:c}}function ke(n){return n.filter(t=>t.status===y.READY)}function Tt(n){return ke(n).length>0}var De=x(()=>{"use strict";g()});function Se(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 Te(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 Ae=x(()=>{"use strict";g();De()});var _e={};ve(_e,{processFilesForNode:()=>we});function Ue(n,t=new Set){let e=[],i=S.realpathSync(n);if(t.has(i))return e;t.add(i);let r=S.readdirSync(n);for(let s of r){let p=T.join(n,s),c=S.statSync(p);if(c.isDirectory()){let o=Ue(p,t);e.push(...o)}else c.isFile()&&e.push(p)}return e}async function we(n,t={},e){if(C()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let m of n){let h=T.resolve(m);try{if(S.statSync(h).isDirectory()){let A=S.readdirSync(h).find(w=>K.has(w));if(A)throw a.business(`"${A}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(A){if(L(A))throw A}}let i=n.flatMap(m=>{let h=T.resolve(m);try{return S.statSync(h).isDirectory()?Ue(h):[h]}catch{throw a.file(`Path does not exist: ${m}`,{filePath:m})}}),r=[...new Set(i)],s=n.map(m=>T.resolve(m)),p=$e(s.map(m=>{try{return S.statSync(m).isDirectory()?m:T.dirname(m)}catch{return T.dirname(m)}})),c=r.map(m=>{if(p&&p.length>0){let h=T.relative(p,m);if(h&&typeof h=="string"&&!h.startsWith(".."))return h.replace(/\\/g,"/")}return T.basename(m)}),l=ge(c,{flatten:t.pathDetect!==!1}).map(m=>m.path),u=new Set(me(l));if(u.size===0)return[];let E=[],N=[];for(let m=0;m<r.length;m++)u.has(l[m])&&(E.push(r[m]),N.push(l[m]));let I=[],D=0;if(!e)throw a.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let m=0;m<E.length;m++){let h=E[m],A=N[m];try{Se(A,h);let w=S.statSync(h);if(w.size===0)continue;if(Te(A,h),w.size>e.maxFileSize)throw a.business(`File ${h} is too large. Maximum allowed size is ${e.maxFileSize/(1024*1024)}MB.`);if(D+=w.size,D>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let F=S.readFileSync(h),{md5:Me}=await M(F);I.push({path:A,content:F,size:F.length,md5:Me})}catch(w){if(L(w))throw w;let F=w instanceof Error?w.message:String(w);throw a.file(`Failed to read file "${h}": ${F}`,{filePath:h})}}if(I.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return I}var S,T,Re=x(()=>{"use strict";H();q();fe();Ae();g();Ee();he();S=b(require("fs"),1),T=b(require("path"),1)});var At={};ve(At,{API_KEY:()=>R,AccountPlan:()=>Ye,ApiHttp:()=>B,AuthMethod:()=>Qe,BLOCKED_EXTENSIONS:()=>xe,DEFAULT_API:()=>U,DEPLOYMENT_CONFIG_FILENAME:()=>G,DEPLOY_TOKEN:()=>v,DeploymentStatus:()=>qe,DomainStatus:()=>Xe,ErrorType:()=>d,FILE_VALIDATION_STATUS:()=>y,FileValidationStatus:()=>y,JUNK_DIRECTORIES:()=>Oe,LABEL_CONSTRAINTS:()=>P,LABEL_PATTERN:()=>re,PASSWORD_CONSTRAINTS:()=>O,SPA_DEFAULT_CONFIG:()=>ne,Ship:()=>Z,ShipError:()=>a,UNBUILT_PROJECT_MARKERS:()=>K,UNSAFE_FILENAME_CHARS:()=>Pe,__setTestEnvironment:()=>ft,allValidFilesReady:()=>Tt,calculateMD5:()=>M,createAccountResource:()=>pe,createDeploymentResource:()=>ae,createDomainResource:()=>le,createTokenResource:()=>ce,default:()=>Be,deserializeLabels:()=>lt,extractSubdomain:()=>rt,filterJunk:()=>me,formatFileSize:()=>J,generateDeploymentUrl:()=>st,generateDomainUrl:()=>ot,getENV:()=>C,getValidFiles:()=>ke,hasUnbuiltMarker:()=>k,hasUnsafeChars:()=>te,isBlockedExtension:()=>$,isCustomDomain:()=>it,isDeployment:()=>nt,isPlatformDomain:()=>ie,isShipError:()=>L,mergeDeployOptions:()=>oe,optimizeDeployPaths:()=>ge,pluralize:()=>Et,processFilesForNode:()=>we,resolveConfig:()=>se,serializeLabels:()=>at,validateApiKey:()=>Ze,validateApiUrl:()=>tt,validateDeployFile:()=>Te,validateDeployPath:()=>Se,validateDeployToken:()=>et,validateFileName:()=>Q,validateFiles:()=>St,validatePassword:()=>V});module.exports=je(At);g();g();var j=class{constructor(){this.handlers=new Map}on(t,e){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e)}off(t,e){let 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(p){i.delete(s),t!=="error"&&setTimeout(()=>{let c=p instanceof Error?p:new Error(String(p));this.emit("error",c,String(t))},0)}}};g();g();function _(n){if(n==null)return;if(n.length===0)return n;if(n.length>P.MAX_COUNT)throw a.validation(`Maximum ${P.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<P.MIN_LENGTH)throw a.validation(`Labels must be at least ${P.MIN_LENGTH} characters long`);if(s.length>P.MAX_LENGTH)throw a.validation(`Labels must be no more than ${P.MAX_LENGTH} characters long`);if(!re.test(s))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${P.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 f={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},pt=3e4,B=class extends j{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||U,this.getAuthHeadersCallback=e.getAuthHeaders,this.useCredentials=e.useCredentials??!1,this.timeout=e.timeout??pt,this.fetch=e.fetch??globalThis.fetch,this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||f.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}async executeRequest(e,i,r){let s=this.mergeHeaders(i.headers),{signal:p,cleanup:c}=this.createTimeoutSignal(i.signal),o={...i,headers:s,credentials:this.useCredentials&&!s.Authorization?"include":void 0,signal:p};this.emit("request",e,o);try{let l=await this.fetch(e,o);if(c(),!l.ok)throw await a.fromHttpResponse(l,r);return this.emit("response",this.safeClone(l),e),{data:await this.parseResponse(this.safeClone(l)),status:l.status}}catch(l){c();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)}mergeHeaders(e={}){return{...this.globalHeaders,...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 l of e)if(!l.md5)throw a.file(`MD5 checksum missing for file: ${l.path}`,{filePath:l.path});V(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:p,headers:c}=await this.createDeployBody(e,{labels:r,via:i.via,password:i.password,flags:s}),o={};return i.deployToken?o.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(o.Authorization=`Bearer ${i.apiKey}`),i.caller&&(o["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:p,headers:{...c,...o},signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){let r=_(i);return this.request(`${this.apiUrl}${f.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}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,r){let s=_(r),p={};i&&(p.deployment=i),s!==void 0&&(p.labels=s);let{data:c,status:o}=await this.requestWithStatus(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)},"Set domain");return{...c,isCreate:o===201}}async listDomains(){return this.request(`${this.apiUrl}${f.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/share`,{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=_(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(){return this.request(`${this.apiUrl}${f.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${f.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async fetchAgentToken(){return this.request(`${this.apiUrl}${f.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent 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(l=>l.path==="index.html"||l.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 p={"Content-Type":"application/json"};i.deployToken?p.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(p.Authorization=`Bearer ${i.apiKey}`);let c={files:e.map(l=>l.path),index:s};return(await this.request(`${this.apiUrl}${f.SPA_CHECK}`,{method:"POST",headers:p,body:JSON.stringify(c)},"SPA check")).isSPA}};g();function se(n={}){let t={apiUrl:n.apiUrl||U};return n.apiKey!==void 0&&(t.apiKey=n.apiKey),n.deployToken!==void 0&&(t.deployToken=n.deployToken),t}function oe(n,t){let e={...n};return e.apiUrl===void 0&&t.apiUrl!==void 0&&(e.apiUrl=t.apiUrl),e.apiKey===void 0&&t.apiKey!==void 0&&(e.apiKey=t.apiKey),e.deployToken===void 0&&t.deployToken!==void 0&&(e.deployToken=t.deployToken),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.caller===void 0&&t.caller!==void 0&&(e.caller=t.caller),e}g();g();q();async function mt(){let n=JSON.stringify(ne,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:G,content:t,size:n.length,md5:e}}async function be(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===G))return n;try{if(await t.checkSPA(n,e)){let r=await mt();return[...n,r]}}catch{}return n}function ae(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:r,hasAuth:s}=n;return{upload:async(p,c={})=>{await e();let o=r?oe(c,r):c;if(s&&!s()&&!o.deployToken&&!o.apiKey)try{let E=t(),{secret:N}=await E.fetchAgentToken();o.deployToken=N}catch(E){throw L(E)&&E.type===d.RateLimit?a.rateLimit("public deploy rate limit exceeded, try again later or run 'ship config' for a free account with higher limits"):E}if(!i)throw a.config("processInput function is not provided.");let l=t(),u=await i(p,o);return u=await be(u,l,o),l.deploy(u,o)},list:async()=>(await e(),t().listDeployments()),get:async p=>(await e(),t().getDeployment(p)),set:async(p,c)=>(await e(),t().updateDeploymentLabels(p,c.labels)),remove:async p=>{await e(),await t().removeDeployment(p)}}}function le(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 pe(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function ce(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.auth=null;t={...t,apiUrl:t.apiUrl||void 0,apiKey:t.apiKey||void 0,deployToken:t.deployToken||void 0},this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.http=new B({...t,...se(t),getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=ae({...e,processInput:(i,r)=>this.processInput(i,r),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this.domains=le(e),this.account=pe(e),this.tokens=ce(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({})}setDeployToken(t){if(!t||typeof t!="string")throw a.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:t}}setApiKey(t){if(!t||typeof t!="string")throw a.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:t}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};g();H();var de=require("zod");g();H();var Y=require("zod"),Le={apiUrl:Y.z.string().url().optional(),apiKey:Y.z.string().min(1).optional(),deployToken:Y.z.string().min(1).optional()};var yt=de.z.object(Le).strict(),gt={apiUrl:"SHIP_API_URL",apiKey:"SHIP_API_KEY",deployToken:"SHIP_DEPLOY_TOKEN"};function Ne(){if(C()!=="node")return{};let n={apiUrl:process.env.SHIP_API_URL||void 0,apiKey:process.env.SHIP_API_KEY||void 0,deployToken:process.env.SHIP_DEPLOY_TOKEN||void 0};try{return yt.parse(n)}catch(t){if(t instanceof de.z.ZodError){let e=t.issues[0],i=e.path[0],r=(i&>[i])??"SHIP environment configuration";throw a.config(`Invalid ${r}: ${e.message}`)}throw a.config("Invalid environment configuration")}}g();async function Ce(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),{labels:s,via:p,password:c,flags:o}=t,l=new e,u=[];for(let D of n){if(!Buffer.isBuffer(D.content)&&!(typeof Blob<"u"&&D.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${D.path}`,{filePath:D.path});if(!D.md5)throw a.file(`File missing md5 checksum: ${D.path}`,{filePath:D.path});let m=new i([D.content],D.path,{type:"application/octet-stream"});l.append("files[]",m),u.push(D.md5)}l.append("checksums",JSON.stringify(u)),s&&s.length>0&&l.append("labels",JSON.stringify(s)),p&&l.append("via",p),c&&l.append("password",c),o?.build&&l.append("build","true"),o?.prerender&&l.append("prerender","true"),o?.spa&&l.append("spa","true");let E=new r(l),N=[];for await(let D of E.encode())N.push(Buffer.from(D));let I=Buffer.concat(N);return{body:I.buffer.slice(I.byteOffset,I.byteOffset+I.byteLength),headers:{"Content-Type":E.contentType,"Content-Length":Buffer.byteLength(I).toString()}}}q();function Et(n,t,e,i=!0){let r=n===1?t:e;return i?`${n} ${r}`:r}fe();Ee();H();De();Ae();g();Re();var Z=class extends X{constructor(t={}){if(C()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=Ne();super({...t,apiUrl:t.apiUrl||e.apiUrl,apiKey:t.apiKey||e.apiKey,deployToken:t.deployToken||e.deployToken})}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(()=>(Re(),_e));return r(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return Ce}},Be=Z;0&&(module.exports={API_KEY,AccountPlan,ApiHttp,AuthMethod,BLOCKED_EXTENSIONS,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_TOKEN,DeploymentStatus,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,PASSWORD_CONSTRAINTS,SPA_DEFAULT_CONFIG,Ship,ShipError,UNBUILT_PROJECT_MARKERS,UNSAFE_FILENAME_CHARS,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getENV,getValidFiles,hasUnbuiltMarker,hasUnsafeChars,isBlockedExtension,isCustomDomain,isDeployment,isPlatformDomain,isShipError,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,serializeLabels,validateApiKey,validateApiUrl,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles,validatePassword});
|
|
1
|
+
"use strict";var He=Object.create;var z=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Ve=Object.prototype.hasOwnProperty;var x=(n,t)=>()=>(n&&(t=n(n=0)),t);var ve=(n,t)=>{for(var e in t)z(n,e,{get:t[e],enumerable:!0})},Ie=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ke(t))!Ve.call(n,r)&&r!==e&&z(n,r,{get:()=>t[r],enumerable:!(i=ze(t,r))||i.enumerable});return n};var b=(n,t,e)=>(e=n!=null?He(Ge(n)):{},Ie(t||!n||!n.__esModule?z(e,"default",{value:n,enumerable:!0}):e,n)),je=n=>Ie(z({},"__esModule",{value:!0}),n);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 xe.has(e)}function te(n){return Pe.test(n)}function k(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>K.has(e))}function Ze(n){if(!n.startsWith(R.PREFIX))throw a.validation(`API key must start with "${R.PREFIX}"`);if(n.length!==R.TOTAL_LENGTH)throw a.validation(`API key must be ${R.TOTAL_LENGTH} characters total (${R.PREFIX} + ${R.HEX_LENGTH} hex chars)`);let t=n.slice(R.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`API key must contain ${R.HEX_LENGTH} hexadecimal characters after "${R.PREFIX}" prefix`)}function et(n){if(!n.startsWith(v.PREFIX))throw a.validation(`Deploy token must start with "${v.PREFIX}"`);if(n.length!==v.TOTAL_LENGTH)throw a.validation(`Deploy token must be ${v.TOTAL_LENGTH} characters total (${v.PREFIX} + ${v.HEX_LENGTH} hex chars)`);let t=n.slice(v.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`Deploy token must contain ${v.HEX_LENGTH} hexadecimal characters after "${v.PREFIX}" prefix`)}function tt(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 nt(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function ie(n,t){return n.endsWith(`.${t}`)}function it(n,t){return!ie(n,t)}function rt(n,t){return ie(n,t)?n.slice(0,-(t.length+1)):null}function st(n){return`https://${n}`}function ot(n){return`https://${n}`}function at(n){return!n||n.length===0?null:JSON.stringify(n)}function lt(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}function V(n){if(n==null)return;if(typeof n!="string")throw a.validation("Password must be a string");let t=n.trim();if(t.length<O.MIN_LENGTH||t.length>O.MAX_LENGTH)throw a.validation(`Password must be between ${O.MIN_LENGTH} and ${O.MAX_LENGTH} characters`);return t}var qe,Xe,Ye,d,We,ee,Je,a,xe,Pe,K,R,v,Qe,G,ne,U,y,P,re,O,g=x(()=>{"use strict";qe={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Xe={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Ye={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},d={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"},We=new Set([d.Network,d.Cancelled,d.File,d.Config]),ee={client:new Set([d.Business,d.Config,d.File,d.Forbidden,d.Validation]),network:new Set([d.Network]),auth:new Set([d.Authentication])},Je=new Set(Object.values(d).filter(n=>!We.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===d.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static async fromHttpResponse(t,e){let i,r,s;try{if(t.headers.get("content-type")?.includes("application/json")){let o=await t.json();if(o&&typeof o=="object"){let l=o;typeof l.message=="string"?i=l.message:typeof l.error=="string"&&(i=l.error),r=l.details,typeof l.error=="string"&&Je.has(l.error)&&(s=l.error)}}else{let o=await t.text();o&&(i=o)}}catch{}i=i||`${e||"Request"} failed with status ${t.status}`;let p=s??(t.status===401?d.Authentication:t.status===403?d.Forbidden:t.status===429?d.RateLimit:d.Api);return new n(p,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(d.Api,`${i} failed: ${t.message}`):new n(d.Api,`${i} failed: Unknown error`)}static validation(t,e){return new n(d.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(d.NotFound,i,404)}static forbidden(t,e){return new n(d.Forbidden,t,403,e)}static rateLimit(t="Too many requests",e){return new n(d.RateLimit,t,429,e)}static authentication(t="Authentication required",e){return new n(d.Authentication,t,401,e)}static business(t,e=400,i){return new n(d.Business,t,e,i)}static network(t,e){return new n(d.Network,t,void 0,e)}static cancelled(t,e){return new n(d.Cancelled,t,void 0,e)}static file(t,e){return new n(d.File,t,void 0,e)}static config(t,e){return new n(d.Config,t,void 0,e)}static api(t,e=500,i){return new n(d.Api,t,e,i)}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}};xe=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"]);Pe=/[\x00-\x1f\x7f#?%\\<>"]/;K=new Set(["node_modules","package.json"]);R={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},v={PREFIX:"token-",HEX_LENGTH:64,TOTAL_LENGTH:70},Qe={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},G="ship.json",ne={rewrites:[{source:"/(.*)",destination:"/index.html"}]};U="https://api.shipstatic.com",y={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};P={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},re=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;O={MIN_LENGTH:6,MAX_LENGTH:128}});async function ct(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 ut(n){let{createHash:t}=await import("crypto"),e=t("md5");return e.update(n),{md5:e.digest("hex")}}async function dt(n){let{createHash:t}=await import("crypto"),{createReadStream:e}=await import("fs");return new Promise((i,r)=>{let s=t("md5"),p=e(n);p.on("error",c=>r(a.business(`Failed to read file for MD5: ${c.message}`))),p.on("data",c=>s.update(c)),p.on("end",()=>i({md5:s.digest("hex")}))})}async function M(n){if(n instanceof Blob)return ct(n);if(typeof Buffer<"u"&&Buffer.isBuffer(n))return ut(n);if(typeof n=="string")return dt(n);throw a.business("Invalid input for MD5 calculation")}var q=x(()=>{"use strict";g()});function ft(n){ue=n}function ht(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function C(){return ue||ht()}var ue,H=x(()=>{"use strict";ue=null});function me(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&k(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,Fe.isJunk)(r))return!1;for(let p of i)if(p!==".well-known"&&(p.startsWith(".")||p.length>255))return!1;let s=i.slice(0,-1);for(let p of s)if(Oe.some(c=>p.toLowerCase()===c.toLowerCase()))return!1;return!0})}var Fe,Oe,fe=x(()=>{"use strict";Fe=require("junk");g();Oe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function $e(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 p=e[0][s];if(e.every(c=>c[s]===p))i.push(p);else break}return i.join("/")}function W(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var he=x(()=>{"use strict"});function ge(n,t={}){if(t.flatten===!1)return n.map(i=>({path:W(i),name:ye(i)}));let e=Dt(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=ye(i)),{path:r,name:ye(i)}})}function Dt(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 p=e[0][s];if(e.every(c=>c[s]===p))i.push(p);else break}return i.join("/")}function ye(n){return n.split(/[/\\]/).pop()||n}var Ee=x(()=>{"use strict";he()});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/Math.pow(e,r)).toFixed(t))+" "+i[r]}function Q(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 St(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(k(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(l=>({...l,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(l=>({...l,status:y.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let o of n){let l=y.READY,u="Ready for upload",E=o.name?Q(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===y.PROCESSING_ERROR)l=y.VALIDATION_FAILED,u=o.statusMessage||"File failed during processing",e.push({file:o.name,message:u});else if(o.size===0){l=y.EXCLUDED,u="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:u}),r.push({...o,status:l,statusMessage:u});continue}else o.size<0?(l=y.VALIDATION_FAILED,u="File size must be positive",e.push({file:o.name,message:u})):!o.name||o.name.trim().length===0?(l=y.VALIDATION_FAILED,u="File name cannot be empty",e.push({file:o.name||"(empty)",message:u})):o.name.includes("\0")?(l=y.VALIDATION_FAILED,u="File name contains invalid characters (null byte)",e.push({file:o.name,message:u})):E.valid?$(o.name)?(l=y.VALIDATION_FAILED,u=`File extension not allowed: "${o.name}"`,e.push({file:o.name,message:u})):o.size>t.maxFileSize?(l=y.VALIDATION_FAILED,u=`File size (${J(o.size)}) exceeds limit of ${J(t.maxFileSize)}`,e.push({file:o.name,message:u})):(s+=o.size,s>t.maxTotalSize&&(l=y.VALIDATION_FAILED,u=`Total size would exceed limit of ${J(t.maxTotalSize)}`,e.push({file:o.name,message:u}))):(l=y.VALIDATION_FAILED,u=E.reason||"Invalid file name",e.push({file:o.name,message:u}));r.push({...o,status:l,statusMessage:u})}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 p=e.length===0?r.filter(o=>o.status===y.READY):[],c=e.length===0;return{files:r,validFiles:p,errors:e,warnings:i,canDeploy:c}}function ke(n){return n.filter(t=>t.status===y.READY)}function Tt(n){return ke(n).length>0}var De=x(()=>{"use strict";g()});function Se(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 Te(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 Ae=x(()=>{"use strict";g();De()});var _e={};ve(_e,{processFilesForNode:()=>we});function Ue(n,t=new Set){let e=[],i=S.realpathSync(n);if(t.has(i))return e;t.add(i);let r=S.readdirSync(n);for(let s of r){let p=T.join(n,s),c=S.statSync(p);if(c.isDirectory()){let o=Ue(p,t);e.push(...o)}else c.isFile()&&e.push(p)}return e}async function we(n,t={},e){if(C()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let m of n){let h=T.resolve(m);try{if(S.statSync(h).isDirectory()){let A=S.readdirSync(h).find(w=>K.has(w));if(A)throw a.business(`"${A}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(A){if(L(A))throw A}}let i=n.flatMap(m=>{let h=T.resolve(m);try{return S.statSync(h).isDirectory()?Ue(h):[h]}catch{throw a.file(`Path does not exist: ${m}`,{filePath:m})}}),r=[...new Set(i)],s=n.map(m=>T.resolve(m)),p=$e(s.map(m=>{try{return S.statSync(m).isDirectory()?m:T.dirname(m)}catch{return T.dirname(m)}})),c=r.map(m=>{if(p&&p.length>0){let h=T.relative(p,m);if(h&&typeof h=="string"&&!h.startsWith(".."))return h.replace(/\\/g,"/")}return T.basename(m)}),l=ge(c,{flatten:t.pathDetect!==!1}).map(m=>m.path),u=new Set(me(l));if(u.size===0)return[];let E=[],N=[];for(let m=0;m<r.length;m++)u.has(l[m])&&(E.push(r[m]),N.push(l[m]));let I=[],D=0;if(!e)throw a.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let m=0;m<E.length;m++){let h=E[m],A=N[m];try{Se(A,h);let w=S.statSync(h);if(w.size===0)continue;if(Te(A,h),w.size>e.maxFileSize)throw a.business(`File ${h} is too large. Maximum allowed size is ${e.maxFileSize/(1024*1024)}MB.`);if(D+=w.size,D>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let F=S.readFileSync(h),{md5:Me}=await M(F);I.push({path:A,content:F,size:F.length,md5:Me})}catch(w){if(L(w))throw w;let F=w instanceof Error?w.message:String(w);throw a.file(`Failed to read file "${h}": ${F}`,{filePath:h})}}if(I.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return I}var S,T,Re=x(()=>{"use strict";H();q();fe();Ae();g();Ee();he();S=b(require("fs"),1),T=b(require("path"),1)});var At={};ve(At,{API_KEY:()=>R,AccountPlan:()=>Ye,ApiHttp:()=>B,AuthMethod:()=>Qe,BLOCKED_EXTENSIONS:()=>xe,DEFAULT_API:()=>U,DEPLOYMENT_CONFIG_FILENAME:()=>G,DEPLOY_TOKEN:()=>v,DeploymentStatus:()=>qe,DomainStatus:()=>Xe,ErrorType:()=>d,FILE_VALIDATION_STATUS:()=>y,FileValidationStatus:()=>y,JUNK_DIRECTORIES:()=>Oe,LABEL_CONSTRAINTS:()=>P,LABEL_PATTERN:()=>re,PASSWORD_CONSTRAINTS:()=>O,SPA_DEFAULT_CONFIG:()=>ne,Ship:()=>Z,ShipError:()=>a,UNBUILT_PROJECT_MARKERS:()=>K,UNSAFE_FILENAME_CHARS:()=>Pe,__setTestEnvironment:()=>ft,allValidFilesReady:()=>Tt,calculateMD5:()=>M,createAccountResource:()=>pe,createDeploymentResource:()=>ae,createDomainResource:()=>le,createTokenResource:()=>ce,default:()=>Be,deserializeLabels:()=>lt,extractSubdomain:()=>rt,filterJunk:()=>me,formatFileSize:()=>J,generateDeploymentUrl:()=>st,generateDomainUrl:()=>ot,getENV:()=>C,getValidFiles:()=>ke,hasUnbuiltMarker:()=>k,hasUnsafeChars:()=>te,isBlockedExtension:()=>$,isCustomDomain:()=>it,isDeployment:()=>nt,isPlatformDomain:()=>ie,isShipError:()=>L,mergeDeployOptions:()=>oe,optimizeDeployPaths:()=>ge,pluralize:()=>Et,processFilesForNode:()=>we,resolveConfig:()=>se,serializeLabels:()=>at,validateApiKey:()=>Ze,validateApiUrl:()=>tt,validateDeployFile:()=>Te,validateDeployPath:()=>Se,validateDeployToken:()=>et,validateFileName:()=>Q,validateFiles:()=>St,validatePassword:()=>V});module.exports=je(At);g();g();var j=class{constructor(){this.handlers=new Map}on(t,e){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e)}off(t,e){let 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(p){i.delete(s),t!=="error"&&setTimeout(()=>{let c=p instanceof Error?p:new Error(String(p));this.emit("error",c,String(t))},0)}}};g();g();function _(n){if(n==null)return;if(n.length===0)return n;if(n.length>P.MAX_COUNT)throw a.validation(`Maximum ${P.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<P.MIN_LENGTH)throw a.validation(`Labels must be at least ${P.MIN_LENGTH} characters long`);if(s.length>P.MAX_LENGTH)throw a.validation(`Labels must be no more than ${P.MAX_LENGTH} characters long`);if(!re.test(s))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${P.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 f={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},pt=3e4,B=class extends j{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||U,this.getAuthHeadersCallback=e.getAuthHeaders,this.useCredentials=e.useCredentials??!1,this.timeout=e.timeout??pt,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){let s=this.mergeHeaders(i.headers),{signal:p,cleanup:c}=this.createTimeoutSignal(i.signal),o={...i,headers:s,credentials:this.useCredentials&&!s.Authorization?"include":void 0,signal:p};this.emit("request",e,o);try{let l=await this.fetch(e,o);if(c(),!l.ok)throw await a.fromHttpResponse(l,r);return this.emit("response",this.safeClone(l),e),{data:await this.parseResponse(this.safeClone(l)),status:l.status}}catch(l){c();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)}mergeHeaders(e={}){return{...this.globalHeaders,...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 l of e)if(!l.md5)throw a.file(`MD5 checksum missing for file: ${l.path}`,{filePath:l.path});V(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:p,headers:c}=await this.createDeployBody(e,{labels:r,via:i.via,password:i.password,flags:s}),o={};return i.deployToken?o.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(o.Authorization=`Bearer ${i.apiKey}`),i.caller&&(o["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:p,headers:{...c,...o},signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){let r=_(i);return this.request(`${this.apiUrl}${f.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}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,r){let s=_(r),p={};i&&(p.deployment=i),s!==void 0&&(p.labels=s);let{data:c,status:o}=await this.requestWithStatus(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)},"Set domain");return{...c,isCreate:o===201}}async listDomains(){return this.request(`${this.apiUrl}${f.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/share`,{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=_(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(){return this.request(`${this.apiUrl}${f.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${f.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async fetchAgentToken(){return this.request(`${this.apiUrl}${f.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent 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(l=>l.path==="index.html"||l.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 p={"Content-Type":"application/json"};i.deployToken?p.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(p.Authorization=`Bearer ${i.apiKey}`);let c={files:e.map(l=>l.path),index:s};return(await this.request(`${this.apiUrl}${f.SPA_CHECK}`,{method:"POST",headers:p,body:JSON.stringify(c)},"SPA check")).isSPA}};g();function se(n={}){let t={apiUrl:n.apiUrl||U};return n.apiKey!==void 0&&(t.apiKey=n.apiKey),n.deployToken!==void 0&&(t.deployToken=n.deployToken),t}function oe(n,t){let e={...n};return e.apiUrl===void 0&&t.apiUrl!==void 0&&(e.apiUrl=t.apiUrl),e.apiKey===void 0&&t.apiKey!==void 0&&(e.apiKey=t.apiKey),e.deployToken===void 0&&t.deployToken!==void 0&&(e.deployToken=t.deployToken),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.caller===void 0&&t.caller!==void 0&&(e.caller=t.caller),e}g();g();q();async function mt(){let n=JSON.stringify(ne,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:G,content:t,size:n.length,md5:e}}async function be(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===G))return n;try{if(await t.checkSPA(n,e)){let r=await mt();return[...n,r]}}catch{}return n}function ae(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:r,hasAuth:s}=n;return{upload:async(p,c={})=>{await e();let o=r?oe(c,r):c;if(s&&!s()&&!o.deployToken&&!o.apiKey)try{let E=t(),{secret:N}=await E.fetchAgentToken();o.deployToken=N}catch(E){throw L(E)&&E.type===d.RateLimit?a.rateLimit("public deploy rate limit exceeded, try again later or run 'ship config' for a free account with higher limits"):E}if(!i)throw a.config("processInput function is not provided.");let l=t(),u=await i(p,o);return u=await be(u,l,o),l.deploy(u,o)},list:async()=>(await e(),t().listDeployments()),get:async p=>(await e(),t().getDeployment(p)),set:async(p,c)=>(await e(),t().updateDeploymentLabels(p,c.labels)),remove:async p=>{await e(),await t().removeDeployment(p)}}}function le(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 pe(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function ce(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.auth=null;t={...t,apiUrl:t.apiUrl||void 0,apiKey:t.apiKey||void 0,deployToken:t.deployToken||void 0},this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.http=new B({...t,...se(t),getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=ae({...e,processInput:(i,r)=>this.processInput(i,r),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this.domains=le(e),this.account=pe(e),this.tokens=ce(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({})}setDeployToken(t){if(!t||typeof t!="string")throw a.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:t}}setApiKey(t){if(!t||typeof t!="string")throw a.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:t}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};g();H();var de=require("zod");g();H();var Y=require("zod"),Le={apiUrl:Y.z.string().url().optional(),apiKey:Y.z.string().min(1).optional(),deployToken:Y.z.string().min(1).optional()};var yt=de.z.object(Le).strict(),gt={apiUrl:"SHIP_API_URL",apiKey:"SHIP_API_KEY",deployToken:"SHIP_DEPLOY_TOKEN"};function Ne(){if(C()!=="node")return{};let n={apiUrl:process.env.SHIP_API_URL||void 0,apiKey:process.env.SHIP_API_KEY||void 0,deployToken:process.env.SHIP_DEPLOY_TOKEN||void 0};try{return yt.parse(n)}catch(t){if(t instanceof de.z.ZodError){let e=t.issues[0],i=e.path[0],r=(i&>[i])??"SHIP environment configuration";throw a.config(`Invalid ${r}: ${e.message}`)}throw a.config("Invalid environment configuration")}}g();async function Ce(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),{labels:s,via:p,password:c,flags:o}=t,l=new e,u=[];for(let D of n){if(!Buffer.isBuffer(D.content)&&!(typeof Blob<"u"&&D.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${D.path}`,{filePath:D.path});if(!D.md5)throw a.file(`File missing md5 checksum: ${D.path}`,{filePath:D.path});let m=new i([D.content],D.path,{type:"application/octet-stream"});l.append("files[]",m),u.push(D.md5)}l.append("checksums",JSON.stringify(u)),s&&s.length>0&&l.append("labels",JSON.stringify(s)),p&&l.append("via",p),c&&l.append("password",c),o?.build&&l.append("build","true"),o?.prerender&&l.append("prerender","true"),o?.spa&&l.append("spa","true");let E=new r(l),N=[];for await(let D of E.encode())N.push(Buffer.from(D));let I=Buffer.concat(N);return{body:I.buffer.slice(I.byteOffset,I.byteOffset+I.byteLength),headers:{"Content-Type":E.contentType,"Content-Length":Buffer.byteLength(I).toString()}}}q();function Et(n,t,e,i=!0){let r=n===1?t:e;return i?`${n} ${r}`:r}fe();Ee();H();De();Ae();g();Re();var Z=class extends X{constructor(t={}){if(C()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=Ne();super({...t,apiUrl:t.apiUrl||e.apiUrl,apiKey:t.apiKey||e.apiKey,deployToken:t.deployToken||e.deployToken})}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(()=>(Re(),_e));return r(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return Ce}},Be=Z;0&&(module.exports={API_KEY,AccountPlan,ApiHttp,AuthMethod,BLOCKED_EXTENSIONS,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_TOKEN,DeploymentStatus,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,PASSWORD_CONSTRAINTS,SPA_DEFAULT_CONFIG,Ship,ShipError,UNBUILT_PROJECT_MARKERS,UNSAFE_FILENAME_CHARS,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getENV,getValidFiles,hasUnbuiltMarker,hasUnsafeChars,isBlockedExtension,isCustomDomain,isDeployment,isPlatformDomain,isShipError,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,serializeLabels,validateApiKey,validateApiUrl,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles,validatePassword});
|
|
2
2
|
|
|
3
3
|
// Ship SDK: Enable axios-style CommonJS imports
|
|
4
4
|
const originalExports = module.exports;
|