@shipstatic/ship 0.8.12 → 0.8.14
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/README.md +16 -0
- package/dist/browser.d.ts +27 -6
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +22 -21
- package/dist/cli.cjs.map +1 -1
- package/dist/completions/ship.bash +1 -1
- package/dist/completions/ship.fish +1 -0
- package/dist/completions/ship.zsh +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +27 -6
- package/dist/index.d.ts +27 -6
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.d.cts
CHANGED
|
@@ -54,15 +54,36 @@ interface DeployBody {
|
|
|
54
54
|
body: FormData | ArrayBuffer;
|
|
55
55
|
headers: Record<string, string>;
|
|
56
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Context passed to the deploy body creator — everything that becomes a
|
|
59
|
+
* form field alongside the files themselves.
|
|
60
|
+
*/
|
|
61
|
+
interface DeployBodyContext {
|
|
62
|
+
/**
|
|
63
|
+
* Deployment labels for categorization. Each label must satisfy
|
|
64
|
+
* `LABEL_CONSTRAINTS` (length and pattern, lowercased+trimmed).
|
|
65
|
+
*/
|
|
66
|
+
labels?: string[];
|
|
67
|
+
/** Client identifier (`cli`, `sdk`, `web`). */
|
|
68
|
+
via?: string;
|
|
69
|
+
/**
|
|
70
|
+
* Optional plaintext password to protect the deployment.
|
|
71
|
+
* Length: `PASSWORD_CONSTRAINTS.MIN_LENGTH` to `PASSWORD_CONSTRAINTS.MAX_LENGTH`
|
|
72
|
+
* characters. Whitespace is preserved verbatim — significant.
|
|
73
|
+
*/
|
|
74
|
+
password?: string;
|
|
75
|
+
/** @internal Server-side processing flags. */
|
|
76
|
+
flags?: {
|
|
77
|
+
build?: boolean;
|
|
78
|
+
prerender?: boolean;
|
|
79
|
+
spa?: boolean;
|
|
80
|
+
};
|
|
81
|
+
}
|
|
57
82
|
/**
|
|
58
83
|
* Function that creates a deploy request body from files.
|
|
59
84
|
* Implemented differently for Node.js and Browser.
|
|
60
85
|
*/
|
|
61
|
-
type DeployBodyCreator = (files: StaticFile[],
|
|
62
|
-
build?: boolean;
|
|
63
|
-
prerender?: boolean;
|
|
64
|
-
spa?: boolean;
|
|
65
|
-
}) => Promise<DeployBody>;
|
|
86
|
+
type DeployBodyCreator = (files: StaticFile[], context?: DeployBodyContext) => Promise<DeployBody>;
|
|
66
87
|
/**
|
|
67
88
|
* Options for configuring a `Ship` instance.
|
|
68
89
|
* Sets default API host, authentication credentials, progress callbacks, concurrency, and timeouts for the client.
|
|
@@ -729,4 +750,4 @@ declare class Ship extends Ship$1 {
|
|
|
729
750
|
protected getDeployBodyCreator(): DeployBodyCreator;
|
|
730
751
|
}
|
|
731
752
|
|
|
732
|
-
export { type ApiDeployOptions, ApiHttp, type ApiHttpOptions, type DeployBody, type DeployBodyCreator, type DeployFile, type DeploymentOptions, type DeploymentResourceContext, type DomainSetResult, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ResourceContext, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getCurrentConfig, getENV, getValidFiles, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig as setPlatformConfig, validateDeployFile, validateDeployPath, validateFileName, validateFiles };
|
|
753
|
+
export { type ApiDeployOptions, ApiHttp, type ApiHttpOptions, type DeployBody, type DeployBodyContext, type DeployBodyCreator, type DeployFile, type DeploymentOptions, type DeploymentResourceContext, type DomainSetResult, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ResourceContext, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getCurrentConfig, getENV, getValidFiles, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig as setPlatformConfig, validateDeployFile, validateDeployPath, validateFileName, validateFiles };
|
package/dist/index.d.ts
CHANGED
|
@@ -54,15 +54,36 @@ interface DeployBody {
|
|
|
54
54
|
body: FormData | ArrayBuffer;
|
|
55
55
|
headers: Record<string, string>;
|
|
56
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Context passed to the deploy body creator — everything that becomes a
|
|
59
|
+
* form field alongside the files themselves.
|
|
60
|
+
*/
|
|
61
|
+
interface DeployBodyContext {
|
|
62
|
+
/**
|
|
63
|
+
* Deployment labels for categorization. Each label must satisfy
|
|
64
|
+
* `LABEL_CONSTRAINTS` (length and pattern, lowercased+trimmed).
|
|
65
|
+
*/
|
|
66
|
+
labels?: string[];
|
|
67
|
+
/** Client identifier (`cli`, `sdk`, `web`). */
|
|
68
|
+
via?: string;
|
|
69
|
+
/**
|
|
70
|
+
* Optional plaintext password to protect the deployment.
|
|
71
|
+
* Length: `PASSWORD_CONSTRAINTS.MIN_LENGTH` to `PASSWORD_CONSTRAINTS.MAX_LENGTH`
|
|
72
|
+
* characters. Whitespace is preserved verbatim — significant.
|
|
73
|
+
*/
|
|
74
|
+
password?: string;
|
|
75
|
+
/** @internal Server-side processing flags. */
|
|
76
|
+
flags?: {
|
|
77
|
+
build?: boolean;
|
|
78
|
+
prerender?: boolean;
|
|
79
|
+
spa?: boolean;
|
|
80
|
+
};
|
|
81
|
+
}
|
|
57
82
|
/**
|
|
58
83
|
* Function that creates a deploy request body from files.
|
|
59
84
|
* Implemented differently for Node.js and Browser.
|
|
60
85
|
*/
|
|
61
|
-
type DeployBodyCreator = (files: StaticFile[],
|
|
62
|
-
build?: boolean;
|
|
63
|
-
prerender?: boolean;
|
|
64
|
-
spa?: boolean;
|
|
65
|
-
}) => Promise<DeployBody>;
|
|
86
|
+
type DeployBodyCreator = (files: StaticFile[], context?: DeployBodyContext) => Promise<DeployBody>;
|
|
66
87
|
/**
|
|
67
88
|
* Options for configuring a `Ship` instance.
|
|
68
89
|
* Sets default API host, authentication credentials, progress callbacks, concurrency, and timeouts for the client.
|
|
@@ -729,4 +750,4 @@ declare class Ship extends Ship$1 {
|
|
|
729
750
|
protected getDeployBodyCreator(): DeployBodyCreator;
|
|
730
751
|
}
|
|
731
752
|
|
|
732
|
-
export { type ApiDeployOptions, ApiHttp, type ApiHttpOptions, type DeployBody, type DeployBodyCreator, type DeployFile, type DeploymentOptions, type DeploymentResourceContext, type DomainSetResult, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ResourceContext, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getCurrentConfig, getENV, getValidFiles, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig as setPlatformConfig, validateDeployFile, validateDeployPath, validateFileName, validateFiles };
|
|
753
|
+
export { type ApiDeployOptions, ApiHttp, type ApiHttpOptions, type DeployBody, type DeployBodyContext, type DeployBodyCreator, type DeployFile, type DeploymentOptions, type DeploymentResourceContext, type DomainSetResult, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ResourceContext, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getCurrentConfig, getENV, getValidFiles, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig as setPlatformConfig, validateDeployFile, validateDeployPath, validateFileName, validateFiles };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Ne=Object.defineProperty;var T=(n,t)=>()=>(n&&(t=n(n=0)),t);var $e=(n,t)=>{for(var e in t)Ne(n,e,{get:t[e],enumerable:!0})};function w(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function U(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 me(n){return Ue.test(n)}function _(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>Y.has(e))}function nt(n){if(!n.startsWith(b))throw a.validation(`API key must start with "${b}"`);if(n.length!==de)throw a.validation(`API key must be ${de} characters total (${b} + ${G} hex chars)`);let t=n.slice(b.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`API key must contain ${G} hexadecimal characters after "${b}" prefix`)}function it(n){if(!n.startsWith(I))throw a.validation(`Deploy token must start with "${I}"`);if(n.length!==fe)throw a.validation(`Deploy token must be ${fe} characters total (${I} + ${q} hex chars)`);let t=n.slice(I.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`Deploy token must contain ${q} hexadecimal characters after "${I}" prefix`)}function ot(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 w(t)?t:a.validation("API URL must be a valid URL")}}function st(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function ye(n,t){return n.endsWith(`.${t}`)}function rt(n,t){return!ye(n,t)}function at(n,t){return ye(n,t)?n.slice(0,-(t.length+1)):null}function lt(n){return`https://${n}`}function pt(n){return`https://${n}`}function dt(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[]}}var Xe,Qe,Ze,f,V,a,Le,Ue,Y,b,G,de,et,I,q,fe,tt,W,he,B,g,ct,ut,S=T(()=>{"use strict";Xe={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Qe={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Ze={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"};(function(n){n.Validation="validation_failed",n.NotFound="not_found",n.RateLimit="rate_limit_exceeded",n.Authentication="authentication_failed",n.Business="business_logic_error",n.Api="internal_server_error",n.Network="network_error",n.Cancelled="operation_cancelled",n.File="file_error",n.Config="config_error"})(f||(f={}));V={client:new Set([f.Business,f.Config,f.File,f.Validation]),network:new Set([f.Network]),auth:new Set([f.Authentication])},a=class n extends Error{type;status;details;constructor(t,e,i,o){super(e),this.type=t,this.status=i,this.details=o,this.name="ShipError"}toResponse(){let t=this.type===f.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:t}}static fromResponse(t){return new n(t.error,t.message,t.status,t.details)}static validation(t,e){return new n(f.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(f.NotFound,i,404)}static rateLimit(t="Too many requests"){return new n(f.RateLimit,t,429)}static authentication(t="Authentication required",e){return new n(f.Authentication,t,401,e)}static business(t,e=400){return new n(f.Business,t,e)}static network(t,e){return new n(f.Network,t,void 0,{cause:e})}static cancelled(t){return new n(f.Cancelled,t)}static file(t,e){return new n(f.File,t,void 0,{filePath:e})}static config(t,e){return new n(f.Config,t,void 0,e)}static api(t,e=500){return new n(f.Api,t,e)}static database(t,e=500){return new n(f.Api,t,e)}static storage(t,e=500){return new n(f.Api,t,e)}get filePath(){return this.details?.filePath}isClientError(){return V.client.has(this.type)}isNetworkError(){return V.network.has(this.type)}isAuthError(){return V.auth.has(this.type)}isValidationError(){return this.type===f.Validation}isFileError(){return this.type===f.File}isConfigError(){return this.type===f.Config}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"]);Ue=/[\x00-\x1f\x7f#?%\\<>"]/;Y=new Set(["node_modules","package.json"]);b="ship-",G=64,de=b.length+G,et=4,I="token-",q=64,fe=I.length+q,tt={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},W="ship.json",he={rewrites:[{source:"/(.*)",destination:"/index.html"}]};B="https://api.shipstatic.com",g={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};ct={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},ut=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function X(n){J=n}function k(){if(J===null)throw a.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return J}var J,N=T(()=>{"use strict";S();J=null});function vt(n){Z=n}function Be(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function R(){return Z||Be()}var Z,F=T(()=>{"use strict";Z=null});async function Me(n){let t=(await import("spark-md5")).default;return new Promise((e,i)=>{let s=Math.ceil(n.size/2097152),l=0,p=new t.ArrayBuffer,r=new FileReader,c=()=>{let u=l*2097152,y=Math.min(u+2097152,n.size);r.readAsArrayBuffer(n.slice(u,y))};r.onload=u=>{let y=u.target?.result;if(!y){i(a.business("Failed to read file chunk"));return}p.append(y),l++,l<s?c():e({md5:p.end()})},r.onerror=()=>{i(a.business("Failed to calculate MD5: FileReader error"))},c()})}async function Ke(n){let t=await import("crypto");if(Buffer.isBuffer(n)){let i=t.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let e=await import("fs");return new Promise((i,o)=>{let s=t.createHash("md5"),l=e.createReadStream(n);l.on("error",p=>o(a.business(`Failed to read file for MD5: ${p.message}`))),l.on("data",p=>s.update(p)),l.on("end",()=>i({md5:s.digest("hex")}))})}async function K(n){let t=R();if(t==="browser"){if(!(n instanceof Blob))throw a.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Me(n)}if(t==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw a.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Ke(n)}throw a.business("Unknown or unsupported execution environment for MD5 calculation.")}var z=T(()=>{"use strict";F();S()});import{isJunk as Ve}from"junk";function Re(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 o=i[i.length-1];if(Ve(o))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(p=>l.toLowerCase()===p.toLowerCase()))return!1;return!0})}var Ge,ne=T(()=>{"use strict";S();Ge=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function we(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=[],o=Math.min(...e.map(s=>s.length));for(let s=0;s<o;s++){let l=e[0][s];if(e.every(p=>p[s]===l))i.push(l);else break}return i.join("/")}function j(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ie=T(()=>{"use strict"});function xe(n,t={}){if(t.flatten===!1)return n.map(i=>({path:j(i),name:oe(i)}));let e=qe(n);return n.map(i=>{let o=j(i);if(e){let s=e.endsWith("/")?e:`${e}/`;o.startsWith(s)&&(o=o.substring(s.length))}return o||(o=oe(i)),{path:o,name:oe(i)}})}function qe(n){if(!n.length)return"";let e=n.map(s=>j(s)).map(s=>s.split("/")),i=[],o=Math.min(...e.map(s=>s.length));for(let s=0;s<o-1;s++){let l=e[0][s];if(e.every(p=>p[s]===l))i.push(l);else break}return i.join("/")}function oe(n){return n.split(/[/\\]/).pop()||n}var se=T(()=>{"use strict";ie()});function re(n,t=1){if(n===0)return"0 Bytes";let e=1024,i=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,o)).toFixed(t))+" "+i[o]}function ae(n){if(me(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 tn(n,t){let e=[],i=[],o=[];if(n.length===0){let r={file:"(no files)",message:"At least one file must be provided"};return e.push(r),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let r of n)if(_(r.name))return e.push({file:r.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(c=>({...c,status:g.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let r={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(r),{files:n.map(c=>({...c,status:g.VALIDATION_FAILED,statusMessage:r.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let r of n){let c=g.READY,u="Ready for upload",y=r.name?ae(r.name):{valid:!1,reason:"File name cannot be empty"};if(r.status===g.PROCESSING_ERROR)c=g.VALIDATION_FAILED,u=r.statusMessage||"File failed during processing",e.push({file:r.name,message:u});else if(r.size===0){c=g.EXCLUDED,u="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:r.name,message:u}),o.push({...r,status:c,statusMessage:u});continue}else r.size<0?(c=g.VALIDATION_FAILED,u="File size must be positive",e.push({file:r.name,message:u})):!r.name||r.name.trim().length===0?(c=g.VALIDATION_FAILED,u="File name cannot be empty",e.push({file:r.name||"(empty)",message:u})):r.name.includes("\0")?(c=g.VALIDATION_FAILED,u="File name contains invalid characters (null byte)",e.push({file:r.name,message:u})):y.valid?U(r.name)?(c=g.VALIDATION_FAILED,u=`File extension not allowed: "${r.name}"`,e.push({file:r.name,message:u})):r.size>t.maxFileSize?(c=g.VALIDATION_FAILED,u=`File size (${re(r.size)}) exceeds limit of ${re(t.maxFileSize)}`,e.push({file:r.name,message:u})):(s+=r.size,s>t.maxTotalSize&&(c=g.VALIDATION_FAILED,u=`Total size would exceed limit of ${re(t.maxTotalSize)}`,e.push({file:r.name,message:u}))):(c=g.VALIDATION_FAILED,u=y.reason||"Invalid file name",e.push({file:r.name,message:u}));o.push({...r,status:c,statusMessage:u})}e.length>0&&(o=o.map(r=>r.status===g.EXCLUDED?r:{...r,status:g.VALIDATION_FAILED,statusMessage:r.status===g.VALIDATION_FAILED?r.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=e.length===0?o.filter(r=>r.status===g.READY):[],p=e.length===0;return{files:o,validFiles:l,errors:e,warnings:i,canDeploy:p}}function Ye(n){return n.filter(t=>t.status===g.READY)}function nn(n){return Ye(n).length>0}var le=T(()=>{"use strict";S()});function be(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 Ie(n,t){let e=ae(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if(U(n))throw a.business(`File extension not allowed: "${t}"`)}var pe=T(()=>{"use strict";S();le()});var Oe={};$e(Oe,{processFilesForNode:()=>Fe});import*as E from"fs";import*as A from"path";function Pe(n,t=new Set){let e=[],i=E.realpathSync(n);if(t.has(i))return e;t.add(i);let o=E.readdirSync(n);for(let s of o){let l=A.join(n,s),p=E.statSync(l);if(p.isDirectory()){let r=Pe(l,t);e.push(...r)}else p.isFile()&&e.push(l)}return e}async function Fe(n,t={}){if(R()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let d of n){let h=A.resolve(d);try{if(E.statSync(h).isDirectory()){let C=E.readdirSync(h).find(v=>Y.has(v));if(C)throw a.business(`"${C}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(C){if(w(C))throw C}}let e=n.flatMap(d=>{let h=A.resolve(d);try{return E.statSync(h).isDirectory()?Pe(h):[h]}catch{throw a.file(`Path does not exist: ${d}`,d)}}),i=[...new Set(e)],o=n.map(d=>A.resolve(d)),s=we(o.map(d=>{try{return E.statSync(d).isDirectory()?d:A.dirname(d)}catch{return A.dirname(d)}})),l=i.map(d=>{if(s&&s.length>0){let h=A.relative(s,d);if(h&&typeof h=="string"&&!h.startsWith(".."))return h.replace(/\\/g,"/")}return A.basename(d)}),r=xe(l,{flatten:t.pathDetect!==!1}).map(d=>d.path),c=new Set(Re(r));if(c.size===0)return[];let u=[],y=[];for(let d=0;d<i.length;d++)c.has(r[d])&&(u.push(i[d]),y.push(r[d]));let D=[],L=0,x=k();for(let d=0;d<u.length;d++){let h=u[d],C=y[d];try{be(C,h);let v=E.statSync(h);if(v.size===0)continue;if(Ie(C,h),v.size>x.maxFileSize)throw a.business(`File ${h} is too large. Maximum allowed size is ${x.maxFileSize/(1024*1024)}MB.`);if(L+=v.size,L>x.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${x.maxTotalSize/(1024*1024)}MB.`);let O=E.readFileSync(h),{md5:ke}=await K(O);D.push({path:C,content:O,size:O.length,md5:ke})}catch(v){if(w(v))throw v;let O=v instanceof Error?v.message:String(v);throw a.file(`Failed to read file "${h}": ${O}`,h)}}if(D.length>x.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${x.maxFilesCount} files.`);return D}var ce=T(()=>{"use strict";F();z();ne();pe();S();N();se();ie()});S();var M=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 o=Array.from(i);for(let s of o)try{s(...e)}catch(l){i.delete(s),t!=="error"&&setTimeout(()=>{l instanceof Error?this.emit("error",l,String(t)):this.emit("error",new Error(String(l)),String(t))},0)}}transfer(t){this.handlers.forEach((e,i)=>{e.forEach(o=>{t.on(i,o)})})}clear(){this.handlers.clear()}};var m={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},_e=3e4,P=class extends M{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||B,this.getAuthHeadersCallback=e.getAuthHeaders,this.useCredentials=e.useCredentials??!1,this.timeout=e.timeout??_e,this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||m.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}transferEventsTo(e){this.transfer(e)}async executeRequest(e,i,o){let s=this.mergeHeaders(i.headers),{signal:l,cleanup:p}=this.createTimeoutSignal(i.signal),r={...i,headers:s,credentials:this.useCredentials&&!s.Authorization?"include":void 0,signal:l};this.emit("request",e,r);try{let c=await fetch(e,r);return p(),c.ok||await this.handleResponseError(c,o),this.emit("response",this.safeClone(c),e),{data:await this.parseResponse(this.safeClone(c)),status:c.status}}catch(c){p();let u=c instanceof Error?c:new Error(String(c));this.emit("error",u,e),this.handleFetchError(c,o)}}async request(e,i,o){let{data:s}=await this.executeRequest(e,i,o);return s}async requestWithStatus(e,i,o){return this.executeRequest(e,i,o)}mergeHeaders(e={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...e}}createTimeoutSignal(e){let i=new AbortController,o=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(o)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,i){let o={};try{if(e.headers.get("content-type")?.includes("application/json")){let p=await e.json();if(p&&typeof p=="object"){let r=p;typeof r.message=="string"&&(o.message=r.message),typeof r.error=="string"&&(o.error=r.error)}}else o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}let s=o.message||o.error||`${i} failed`;throw e.status===401?a.authentication(s):a.api(s,e.status)}handleFetchError(e,i){throw w(e)?e:e instanceof Error&&e.name==="AbortError"?a.cancelled(`${i} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?a.network(`${i} failed: ${e.message}`,e):e instanceof Error?a.business(`${i} failed: ${e.message}`):a.business(`${i} failed: Unknown error`)}async deploy(e,i={}){if(!e.length)throw a.business("No files to deploy");for(let r of e)if(!r.md5)throw a.file(`MD5 checksum missing for file: ${r.path}`,r.path);let o=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:s,headers:l}=await this.createDeployBody(e,i.labels,i.via,o),p={};return i.deployToken?p.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(p.Authorization=`Bearer ${i.apiKey}`),i.caller&&(p["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:s,headers:{...l,...p},signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:i})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,o){let s={};i&&(s.deployment=i),o!==void 0&&(s.labels=o);let{data:l,status:p}=await this.requestWithStatus(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Set domain");return{...l,isCreate:p===201}}async listDomains(){return this.request(`${this.apiUrl}${m.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,i){let o={};return e!==void 0&&(o.ttl=e),i!==void 0&&(o.labels=i),this.request(`${this.apiUrl}${m.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${m.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${m.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async fetchAgentToken(){return this.request(`${this.apiUrl}${m.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent token")}async getAccount(){return this.request(`${this.apiUrl}${m.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${m.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${m.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e,i={}){let o=e.find(c=>c.path==="index.html"||c.path==="/index.html");if(!o||o.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(o.content))s=o.content.toString("utf-8");else if(typeof Blob<"u"&&o.content instanceof Blob)s=await o.content.text();else if(typeof File<"u"&&o.content instanceof File)s=await o.content.text();else return!1;let l={"Content-Type":"application/json"};i.deployToken?l.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(l.Authorization=`Bearer ${i.apiKey}`);let p={files:e.map(c=>c.path),index:s};return(await this.request(`${this.apiUrl}${m.SPA_CHECK}`,{method:"POST",headers:l,body:JSON.stringify(p)},"SPA check")).isSPA}};S();N();S();S();function Q(n={},t={}){let e={apiUrl:n.apiUrl||t.apiUrl||B,apiKey:n.apiKey!==void 0?n.apiKey:t.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:t.deployToken},i={apiUrl:e.apiUrl};return e.apiKey!==void 0&&(i.apiKey=e.apiKey),e.deployToken!==void 0&&(i.deployToken=e.deployToken),i}function ge(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}S();z();async function ze(){let n=JSON.stringify(he,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await K(t);return{path:W,content:t,size:n.length,md5:e}}async function De(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===W))return n;try{if(await t.checkSPA(n,e)){let o=await ze();return[...n,o]}}catch{}return n}function Se(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:o,hasAuth:s}=n;return{upload:async(l,p={})=>{await e();let r=o?ge(p,o):p;if(s&&!s()&&!r.deployToken&&!r.apiKey)try{let y=t(),{secret:D}=await y.fetchAgentToken();r.deployToken=D}catch{throw a.authentication("Too many requests; try again later or configure a free API key with 'ship config'")}if(!i)throw a.config("processInput function is not provided.");let c=t(),u=await i(l,r);return u=await De(u,c,r),c.deploy(u,r)},list:async()=>(await e(),t().listDeployments()),get:async l=>(await e(),t().getDeployment(l)),set:async(l,p)=>(await e(),t().updateDeploymentLabels(l,p.labels)),remove:async l=>{await e(),await t().removeDeployment(l)}}}function Ee(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,o={})=>(await e(),t().setDomain(i,o.deployment,o.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 Ae(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 H=class{constructor(t={}){this.initPromise=null;this._config=null;this.auth=null;this.customHeaders={};this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let e=this.resolveInitialConfig(t);this.http=new P({...t,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=Se({...i,processInput:(o,s)=>this.processInput(o,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=Ee(i),this._account=Ae(i),this._tokens=Ce(i)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}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()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=k(),this._config)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.customHeaders=t,this.http.setGlobalHeaders(t)}clearHeaders(){this.customHeaders={},this.http.setGlobalHeaders({})}replaceHttpClient(t){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(t)}catch(e){console.warn("Event transfer failed during client replacement:",e)}this.http=t,Object.keys(this.customHeaders).length>0&&this.http.setGlobalHeaders(this.customHeaders)}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}};S();F();S();F();import{z as $}from"zod";var ee="ship",He=$.object({apiUrl:$.string().url().optional(),apiKey:$.string().min(1).optional(),deployToken:$.string().min(1).optional()}).strict();function ve(n){try{return He.parse(n)}catch(t){if(t instanceof $.ZodError){let e=t.issues[0],i=e.path.length>0?` at ${e.path.join(".")}`:"";throw a.config(`Configuration validation failed${i}: ${e.message}`)}throw a.config("Configuration validation failed")}}async function je(n){try{if(R()!=="node")return{};let{cosmiconfigSync:t}=await import("cosmiconfig"),e=await import("os"),i=t(ee,{searchPlaces:[`.${ee}rc`,"package.json",`${e.homedir()}/.${ee}rc`],stopDir:e.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return ve(o.config)}catch(t){if(w(t))throw t}return{}}async function te(n){if(R()!=="node")return{};let t={apiUrl:process.env.SHIP_API_URL||void 0,apiKey:process.env.SHIP_API_KEY||void 0,deployToken:process.env.SHIP_DEPLOY_TOKEN||void 0},e=await je(n),i={apiUrl:t.apiUrl??e.apiUrl,apiKey:t.apiKey??e.apiKey,deployToken:t.deployToken??e.deployToken};return ve(i)}N();S();async function Te(n,t,e,i){let{FormData:o,File:s}=await import("formdata-node"),{FormDataEncoder:l}=await import("form-data-encoder"),p=new o,r=[];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}`,D.path);if(!D.md5)throw a.file(`File missing md5 checksum: ${D.path}`,D.path);let L=new s([D.content],D.path,{type:"application/octet-stream"});p.append("files[]",L),r.push(D.md5)}p.append("checksums",JSON.stringify(r)),t&&t.length>0&&p.append("labels",JSON.stringify(t)),e&&p.append("via",e),i?.build&&p.append("build","true"),i?.prerender&&p.append("prerender","true"),i?.spa&&p.append("spa","true");let c=new l(p),u=[];for await(let D of c.encode())u.push(Buffer.from(D));let y=Buffer.concat(u);return{body:y.buffer.slice(y.byteOffset,y.byteOffset+y.byteLength),headers:{"Content-Type":c.contentType,"Content-Length":Buffer.byteLength(y).toString()}}}z();function Gt(n,t,e,i=!0){let o=n===1?t:e;return i?`${n} ${o}`:o}ne();se();F();le();pe();S();N();ce();var ue=class extends H{constructor(t={}){if(R()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");super(t)}resolveInitialConfig(t){return Q(t,{})}async loadFullConfig(){try{let t=await te(this.clientOptions.configFile),e=Q(this.clientOptions,t);e.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(e.deployToken):e.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(e.apiKey);let i=new P({...this.clientOptions,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();X(o)}catch(t){throw this.initPromise=null,t}}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:o}=await Promise.resolve().then(()=>(ce(),Oe));return o(i,e)}getDeployBodyCreator(){return Te}},We=ue;export{G as API_KEY_HEX_LENGTH,et as API_KEY_HINT_LENGTH,b as API_KEY_PREFIX,de as API_KEY_TOTAL_LENGTH,Ze as AccountPlan,P as ApiHttp,tt as AuthMethod,Le as BLOCKED_EXTENSIONS,B as DEFAULT_API,W as DEPLOYMENT_CONFIG_FILENAME,q as DEPLOY_TOKEN_HEX_LENGTH,I as DEPLOY_TOKEN_PREFIX,fe as DEPLOY_TOKEN_TOTAL_LENGTH,Xe as DeploymentStatus,Qe as DomainStatus,f as ErrorType,g as FILE_VALIDATION_STATUS,g as FileValidationStatus,Ge as JUNK_DIRECTORIES,ct as LABEL_CONSTRAINTS,ut as LABEL_PATTERN,he as SPA_DEFAULT_CONFIG,ue as Ship,a as ShipError,Y as UNBUILT_PROJECT_MARKERS,Ue as UNSAFE_FILENAME_CHARS,vt as __setTestEnvironment,nn as allValidFilesReady,K as calculateMD5,Ae as createAccountResource,Se as createDeploymentResource,Ee as createDomainResource,Ce as createTokenResource,We as default,ft as deserializeLabels,at as extractSubdomain,Re as filterJunk,re as formatFileSize,lt as generateDeploymentUrl,pt as generateDomainUrl,k as getCurrentConfig,R as getENV,Ye as getValidFiles,_ as hasUnbuiltMarker,me as hasUnsafeChars,U as isBlockedExtension,rt as isCustomDomain,st as isDeployment,ye as isPlatformDomain,w as isShipError,te as loadConfig,ge as mergeDeployOptions,xe as optimizeDeployPaths,Gt as pluralize,Fe as processFilesForNode,Q as resolveConfig,dt as serializeLabels,X as setPlatformConfig,nt as validateApiKey,ot as validateApiUrl,Ie as validateDeployFile,be as validateDeployPath,it as validateDeployToken,ae as validateFileName,tn as validateFiles};
|
|
1
|
+
var Me=Object.defineProperty;var v=(n,t)=>()=>(n&&(t=n(n=0)),t);var Be=(n,t)=>{for(var e in t)Me(n,e,{get:t[e],enumerable:!0})};function C(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function B(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return He.has(e)}function ge(n){return Ke.test(n)}function H(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>J.has(e))}function at(n){if(!n.startsWith(P))throw a.validation(`API key must start with "${P}"`);if(n.length!==he)throw a.validation(`API key must be ${he} characters total (${P} + ${W} hex chars)`);let t=n.slice(P.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`API key must contain ${W} hexadecimal characters after "${P}" prefix`)}function lt(n){if(!n.startsWith(O))throw a.validation(`Deploy token must start with "${O}"`);if(n.length!==ye)throw a.validation(`Deploy token must be ${ye} characters total (${O} + ${X} hex chars)`);let t=n.slice(O.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`Deploy token must contain ${X} hexadecimal characters after "${O}" prefix`)}function pt(n){try{let t=new URL(n);if(!["http:","https:"].includes(t.protocol))throw a.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw a.validation("API URL must not contain a path");if(t.search||t.hash)throw a.validation("API URL must not contain query parameters or fragments")}catch(t){throw C(t)?t:a.validation("API URL must be a valid URL")}}function ct(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function Se(n,t){return n.endsWith(`.${t}`)}function ut(n,t){return!Se(n,t)}function dt(n,t){return Se(n,t)?n.slice(0,-(t.length+1)):null}function ft(n){return`https://${n}`}function mt(n){return`https://${n}`}function ht(n){return!n||n.length===0?null:JSON.stringify(n)}function yt(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}var nt,it,ot,f,Y,a,He,Ke,J,P,W,he,rt,O,X,ye,st,Q,De,K,D,I,Ee,L,S=v(()=>{"use strict";nt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},it={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},ot={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"};(function(n){n.Validation="validation_failed",n.NotFound="not_found",n.RateLimit="rate_limit_exceeded",n.Authentication="authentication_failed",n.Business="business_logic_error",n.Api="internal_server_error",n.Network="network_error",n.Cancelled="operation_cancelled",n.File="file_error",n.Config="config_error"})(f||(f={}));Y={client:new Set([f.Business,f.Config,f.File,f.Validation]),network:new Set([f.Network]),auth:new Set([f.Authentication])},a=class n extends Error{type;status;details;constructor(t,e,i,o){super(e),this.type=t,this.status=i,this.details=o,this.name="ShipError"}toResponse(){let t=this.type===f.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:t}}static fromResponse(t){return new n(t.error,t.message,t.status,t.details)}static validation(t,e){return new n(f.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(f.NotFound,i,404)}static rateLimit(t="Too many requests"){return new n(f.RateLimit,t,429)}static authentication(t="Authentication required",e){return new n(f.Authentication,t,401,e)}static business(t,e=400){return new n(f.Business,t,e)}static network(t,e){return new n(f.Network,t,void 0,{cause:e})}static cancelled(t){return new n(f.Cancelled,t)}static file(t,e){return new n(f.File,t,void 0,{filePath:e})}static config(t,e){return new n(f.Config,t,void 0,e)}static api(t,e=500){return new n(f.Api,t,e)}static database(t,e=500){return new n(f.Api,t,e)}static storage(t,e=500){return new n(f.Api,t,e)}get filePath(){return this.details?.filePath}isClientError(){return Y.client.has(this.type)}isNetworkError(){return Y.network.has(this.type)}isAuthError(){return Y.auth.has(this.type)}isValidationError(){return this.type===f.Validation}isFileError(){return this.type===f.File}isConfigError(){return this.type===f.Config}isType(t){return this.type===t}};He=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"]);Ke=/[\x00-\x1f\x7f#?%\\<>"]/;J=new Set(["node_modules","package.json"]);P="ship-",W=64,he=P.length+W,rt=4,O="token-",X=64,ye=O.length+X,st={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},Q="ship.json",De={rewrites:[{source:"/(.*)",destination:"/index.html"}]};K="https://api.shipstatic.com",D={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};I={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},Ee=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;L={MIN_LENGTH:6,MAX_LENGTH:128}});function ee(n){Z=n}function _(){if(Z===null)throw a.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return Z}var Z,U=v(()=>{"use strict";S();Z=null});function It(n){ne=n}function Ge(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function R(){return ne||Ge()}var ne,F=v(()=>{"use strict";ne=null});async function je(n){let t=(await import("spark-md5")).default;return new Promise((e,i)=>{let r=Math.ceil(n.size/2097152),l=0,c=new t.ArrayBuffer,s=new FileReader,p=()=>{let u=l*2097152,y=Math.min(u+2097152,n.size);s.readAsArrayBuffer(n.slice(u,y))};s.onload=u=>{let y=u.target?.result;if(!y){i(a.business("Failed to read file chunk"));return}c.append(y),l++,l<r?p():e({md5:c.end()})},s.onerror=()=>{i(a.business("Failed to calculate MD5: FileReader error"))},p()})}async function Ve(n){let t=await import("crypto");if(Buffer.isBuffer(n)){let i=t.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let e=await import("fs");return new Promise((i,o)=>{let r=t.createHash("md5"),l=e.createReadStream(n);l.on("error",c=>o(a.business(`Failed to read file for MD5: ${c.message}`))),l.on("data",c=>r.update(c)),l.on("end",()=>i({md5:r.digest("hex")}))})}async function G(n){let t=R();if(t==="browser"){if(!(n instanceof Blob))throw a.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return je(n)}if(t==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw a.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Ve(n)}throw a.business("Unknown or unsupported execution environment for MD5 calculation.")}var j=v(()=>{"use strict";F();S()});import{isJunk as Xe}from"junk";function Pe(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&H(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 o=i[i.length-1];if(Xe(o))return!1;for(let l of i)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let r=i.slice(0,-1);for(let l of r)if(Je.some(c=>l.toLowerCase()===c.toLowerCase()))return!1;return!0})}var Je,re=v(()=>{"use strict";S();Je=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Oe(n){if(!n||n.length===0)return"";let t=n.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let e=t.map(r=>r.split("/").filter(Boolean)),i=[],o=Math.min(...e.map(r=>r.length));for(let r=0;r<o;r++){let l=e[0][r];if(e.every(c=>c[r]===l))i.push(l);else break}return i.join("/")}function q(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var se=v(()=>{"use strict"});function Ne(n,t={}){if(t.flatten===!1)return n.map(i=>({path:q(i),name:ae(i)}));let e=Qe(n);return n.map(i=>{let o=q(i);if(e){let r=e.endsWith("/")?e:`${e}/`;o.startsWith(r)&&(o=o.substring(r.length))}return o||(o=ae(i)),{path:o,name:ae(i)}})}function Qe(n){if(!n.length)return"";let e=n.map(r=>q(r)).map(r=>r.split("/")),i=[],o=Math.min(...e.map(r=>r.length));for(let r=0;r<o-1;r++){let l=e[0][r];if(e.every(c=>c[r]===l))i.push(l);else break}return i.join("/")}function ae(n){return n.split(/[/\\]/).pop()||n}var le=v(()=>{"use strict";se()});function pe(n,t=1){if(n===0)return"0 Bytes";let e=1024,i=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,o)).toFixed(t))+" "+i[o]}function ce(n){if(ge(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 ln(n,t){let e=[],i=[],o=[];if(n.length===0){let s={file:"(no files)",message:"At least one file must be provided"};return e.push(s),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let s of n)if(H(s.name))return e.push({file:s.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(p=>({...p,status:D.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let s={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(s),{files:n.map(p=>({...p,status:D.VALIDATION_FAILED,statusMessage:s.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let r=0;for(let s of n){let p=D.READY,u="Ready for upload",y=s.name?ce(s.name):{valid:!1,reason:"File name cannot be empty"};if(s.status===D.PROCESSING_ERROR)p=D.VALIDATION_FAILED,u=s.statusMessage||"File failed during processing",e.push({file:s.name,message:u});else if(s.size===0){p=D.EXCLUDED,u="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:s.name,message:u}),o.push({...s,status:p,statusMessage:u});continue}else s.size<0?(p=D.VALIDATION_FAILED,u="File size must be positive",e.push({file:s.name,message:u})):!s.name||s.name.trim().length===0?(p=D.VALIDATION_FAILED,u="File name cannot be empty",e.push({file:s.name||"(empty)",message:u})):s.name.includes("\0")?(p=D.VALIDATION_FAILED,u="File name contains invalid characters (null byte)",e.push({file:s.name,message:u})):y.valid?B(s.name)?(p=D.VALIDATION_FAILED,u=`File extension not allowed: "${s.name}"`,e.push({file:s.name,message:u})):s.size>t.maxFileSize?(p=D.VALIDATION_FAILED,u=`File size (${pe(s.size)}) exceeds limit of ${pe(t.maxFileSize)}`,e.push({file:s.name,message:u})):(r+=s.size,r>t.maxTotalSize&&(p=D.VALIDATION_FAILED,u=`Total size would exceed limit of ${pe(t.maxTotalSize)}`,e.push({file:s.name,message:u}))):(p=D.VALIDATION_FAILED,u=y.reason||"Invalid file name",e.push({file:s.name,message:u}));o.push({...s,status:p,statusMessage:u})}e.length>0&&(o=o.map(s=>s.status===D.EXCLUDED?s:{...s,status:D.VALIDATION_FAILED,statusMessage:s.status===D.VALIDATION_FAILED?s.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=e.length===0?o.filter(s=>s.status===D.READY):[],c=e.length===0;return{files:o,validFiles:l,errors:e,warnings:i,canDeploy:c}}function Ze(n){return n.filter(t=>t.status===D.READY)}function pn(n){return Ze(n).length>0}var ue=v(()=>{"use strict";S()});function Fe(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 ke(n,t){let e=ce(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if(B(n))throw a.business(`File extension not allowed: "${t}"`)}var de=v(()=>{"use strict";S();ue()});var _e={};Be(_e,{processFilesForNode:()=>$e});import*as E from"fs";import*as A from"path";function Le(n,t=new Set){let e=[],i=E.realpathSync(n);if(t.has(i))return e;t.add(i);let o=E.readdirSync(n);for(let r of o){let l=A.join(n,r),c=E.statSync(l);if(c.isDirectory()){let s=Le(l,t);e.push(...s)}else c.isFile()&&e.push(l)}return e}async function $e(n,t={}){if(R()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let d of n){let h=A.resolve(d);try{if(E.statSync(h).isDirectory()){let w=E.readdirSync(h).find(T=>J.has(T));if(w)throw a.business(`"${w}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(w){if(C(w))throw w}}let e=n.flatMap(d=>{let h=A.resolve(d);try{return E.statSync(h).isDirectory()?Le(h):[h]}catch{throw a.file(`Path does not exist: ${d}`,d)}}),i=[...new Set(e)],o=n.map(d=>A.resolve(d)),r=Oe(o.map(d=>{try{return E.statSync(d).isDirectory()?d:A.dirname(d)}catch{return A.dirname(d)}})),l=i.map(d=>{if(r&&r.length>0){let h=A.relative(r,d);if(h&&typeof h=="string"&&!h.startsWith(".."))return h.replace(/\\/g,"/")}return A.basename(d)}),s=Ne(l,{flatten:t.pathDetect!==!1}).map(d=>d.path),p=new Set(Pe(s));if(p.size===0)return[];let u=[],y=[];for(let d=0;d<i.length;d++)p.has(s[d])&&(u.push(i[d]),y.push(s[d]));let x=[],b=0,g=_();for(let d=0;d<u.length;d++){let h=u[d],w=y[d];try{Fe(w,h);let T=E.statSync(h);if(T.size===0)continue;if(ke(w,h),T.size>g.maxFileSize)throw a.business(`File ${h} is too large. Maximum allowed size is ${g.maxFileSize/(1024*1024)}MB.`);if(b+=T.size,b>g.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${g.maxTotalSize/(1024*1024)}MB.`);let k=E.readFileSync(h),{md5:Ue}=await G(k);x.push({path:w,content:k,size:k.length,md5:Ue})}catch(T){if(C(T))throw T;let k=T instanceof Error?T.message:String(T);throw a.file(`Failed to read file "${h}": ${k}`,h)}}if(x.length>g.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${g.maxFilesCount} files.`);return x}var fe=v(()=>{"use strict";F();j();re();de();S();U();le();se()});S();var z=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 o=Array.from(i);for(let r of o)try{r(...e)}catch(l){i.delete(r),t!=="error"&&setTimeout(()=>{l instanceof Error?this.emit("error",l,String(t)):this.emit("error",new Error(String(l)),String(t))},0)}}transfer(t){this.handlers.forEach((e,i)=>{e.forEach(o=>{t.on(i,o)})})}clear(){this.handlers.clear()}};S();function Ae(n){if(n!=null){if(typeof n!="string")throw a.validation("Password must be a string");if(n.length<L.MIN_LENGTH||n.length>L.MAX_LENGTH)throw a.validation(`Password must be between ${L.MIN_LENGTH} and ${L.MAX_LENGTH} characters`)}}function $(n){if(n==null)return;if(n.length===0)return n;if(n.length>I.MAX_COUNT)throw a.validation(`Maximum ${I.MAX_COUNT} labels allowed`);let t=n.map((i,o)=>{if(typeof i!="string")throw a.validation(`Label at index ${o} must be a string`);let r=i.trim().toLowerCase();if(r.length<I.MIN_LENGTH)throw a.validation(`Labels must be at least ${I.MIN_LENGTH} characters long`);if(r.length>I.MAX_LENGTH)throw a.validation(`Labels must be no more than ${I.MAX_LENGTH} characters long`);if(!Ee.test(r))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${I.SEPARATORS}) between segments`);return r}),e=[...new Set(t)];if(e.length!==t.length)throw a.validation("Duplicate labels are not allowed");return e}var m={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},ze=3e4,N=class extends z{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||K,this.getAuthHeadersCallback=e.getAuthHeaders,this.useCredentials=e.useCredentials??!1,this.timeout=e.timeout??ze,this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||m.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}transferEventsTo(e){this.transfer(e)}async executeRequest(e,i,o){let r=this.mergeHeaders(i.headers),{signal:l,cleanup:c}=this.createTimeoutSignal(i.signal),s={...i,headers:r,credentials:this.useCredentials&&!r.Authorization?"include":void 0,signal:l};this.emit("request",e,s);try{let p=await fetch(e,s);return c(),p.ok||await this.handleResponseError(p,o),this.emit("response",this.safeClone(p),e),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(p){c();let u=p instanceof Error?p:new Error(String(p));this.emit("error",u,e),this.handleFetchError(p,o)}}async request(e,i,o){let{data:r}=await this.executeRequest(e,i,o);return r}async requestWithStatus(e,i,o){return this.executeRequest(e,i,o)}mergeHeaders(e={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...e}}createTimeoutSignal(e){let i=new AbortController,o=setTimeout(()=>i.abort(),this.timeout);if(e){let r=()=>i.abort();e.addEventListener("abort",r),e.aborted&&i.abort()}return{signal:i.signal,cleanup:()=>clearTimeout(o)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,i){let o={};try{if(e.headers.get("content-type")?.includes("application/json")){let c=await e.json();if(c&&typeof c=="object"){let s=c;typeof s.message=="string"&&(o.message=s.message),typeof s.error=="string"&&(o.error=s.error)}}else o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}let r=o.message||o.error||`${i} failed`;throw e.status===401?a.authentication(r):e.status===429?a.rateLimit(r):a.api(r,e.status)}handleFetchError(e,i){throw C(e)?e:e instanceof Error&&e.name==="AbortError"?a.cancelled(`${i} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?a.network(`${i} failed: ${e.message}`,e):e instanceof Error?a.business(`${i} failed: ${e.message}`):a.business(`${i} failed: Unknown error`)}async deploy(e,i={}){if(!e.length)throw a.business("No files to deploy");for(let p of e)if(!p.md5)throw a.file(`MD5 checksum missing for file: ${p.path}`,p.path);Ae(i.password);let o=$(i.labels),r=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:l,headers:c}=await this.createDeployBody(e,{labels:o,via:i.via,password:i.password,flags:r}),s={};return i.deployToken?s.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(s.Authorization=`Bearer ${i.apiKey}`),i.caller&&(s["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:l,headers:{...c,...s},signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){let o=$(i);return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:o})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,o){let r=$(o),l={};i&&(l.deployment=i),r!==void 0&&(l.labels=r);let{data:c,status:s}=await this.requestWithStatus(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)},"Set domain");return{...c,isCreate:s===201}}async listDomains(){return this.request(`${this.apiUrl}${m.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,i){let o=$(i),r={};return e!==void 0&&(r.ttl=e),o!==void 0&&(r.labels=o),this.request(`${this.apiUrl}${m.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${m.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${m.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async fetchAgentToken(){return this.request(`${this.apiUrl}${m.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent token")}async getAccount(){return this.request(`${this.apiUrl}${m.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${m.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${m.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e,i={}){let o=e.find(p=>p.path==="index.html"||p.path==="/index.html");if(!o||o.size>100*1024)return!1;let r;if(typeof Buffer<"u"&&Buffer.isBuffer(o.content))r=o.content.toString("utf-8");else if(typeof Blob<"u"&&o.content instanceof Blob)r=await o.content.text();else if(typeof File<"u"&&o.content instanceof File)r=await o.content.text();else return!1;let l={"Content-Type":"application/json"};i.deployToken?l.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(l.Authorization=`Bearer ${i.apiKey}`);let c={files:e.map(p=>p.path),index:r};return(await this.request(`${this.apiUrl}${m.SPA_CHECK}`,{method:"POST",headers:l,body:JSON.stringify(c)},"SPA check")).isSPA}};S();U();S();S();function te(n={},t={}){let e={apiUrl:n.apiUrl||t.apiUrl||K,apiKey:n.apiKey!==void 0?n.apiKey:t.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:t.deployToken},i={apiUrl:e.apiUrl};return e.apiKey!==void 0&&(i.apiKey=e.apiKey),e.deployToken!==void 0&&(i.deployToken=e.deployToken),i}function we(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}S();j();async function qe(){let n=JSON.stringify(De,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await G(t);return{path:Q,content:t,size:n.length,md5:e}}async function Te(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===Q))return n;try{if(await t.checkSPA(n,e)){let o=await qe();return[...n,o]}}catch{}return n}function ve(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:o,hasAuth:r}=n;return{upload:async(l,c={})=>{await e();let s=o?we(c,o):c;if(r&&!r()&&!s.deployToken&&!s.apiKey)try{let y=t(),{secret:x}=await y.fetchAgentToken();s.deployToken=x}catch(y){throw C(y)&&y.type===f.RateLimit?a.rateLimit("public deploy rate limit exceeded, try again later or run 'ship config' for a free account with higher limits"):y}if(!i)throw a.config("processInput function is not provided.");let p=t(),u=await i(l,s);return u=await Te(u,p,s),p.deploy(u,s)},list:async()=>(await e(),t().listDeployments()),get:async l=>(await e(),t().getDeployment(l)),set:async(l,c)=>(await e(),t().updateDeploymentLabels(l,c.labels)),remove:async l=>{await e(),await t().removeDeployment(l)}}}function Ce(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,o={})=>(await e(),t().setDomain(i,o.deployment,o.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 Re(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function xe(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 V=class{constructor(t={}){this.initPromise=null;this._config=null;this.auth=null;this.customHeaders={};this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let e=this.resolveInitialConfig(t);this.http=new N({...t,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=ve({...i,processInput:(o,r)=>this.processInput(o,r),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=Ce(i),this._account=Re(i),this._tokens=xe(i)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}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()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=_(),this._config)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.customHeaders=t,this.http.setGlobalHeaders(t)}clearHeaders(){this.customHeaders={},this.http.setGlobalHeaders({})}replaceHttpClient(t){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(t)}catch(e){console.warn("Event transfer failed during client replacement:",e)}this.http=t,Object.keys(this.customHeaders).length>0&&this.http.setGlobalHeaders(this.customHeaders)}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}};S();F();S();F();import{z as M}from"zod";var ie="ship",Ye=M.object({apiUrl:M.string().url().optional(),apiKey:M.string().min(1).optional(),deployToken:M.string().min(1).optional()}).strict();function be(n){try{return Ye.parse(n)}catch(t){if(t instanceof M.ZodError){let e=t.issues[0],i=e.path.length>0?` at ${e.path.join(".")}`:"";throw a.config(`Configuration validation failed${i}: ${e.message}`)}throw a.config("Configuration validation failed")}}async function We(n){try{if(R()!=="node")return{};let{cosmiconfigSync:t}=await import("cosmiconfig"),e=await import("os"),i=t(ie,{searchPlaces:[`.${ie}rc`,"package.json",`${e.homedir()}/.${ie}rc`],stopDir:e.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return be(o.config)}catch(t){if(C(t))throw t}return{}}async function oe(n){if(R()!=="node")return{};let t={apiUrl:process.env.SHIP_API_URL||void 0,apiKey:process.env.SHIP_API_KEY||void 0,deployToken:process.env.SHIP_DEPLOY_TOKEN||void 0},e=await We(n),i={apiUrl:t.apiUrl??e.apiUrl,apiKey:t.apiKey??e.apiKey,deployToken:t.deployToken??e.deployToken};return be(i)}U();S();async function Ie(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:o}=await import("form-data-encoder"),{labels:r,via:l,password:c,flags:s}=t,p=new e,u=[];for(let g of n){if(!Buffer.isBuffer(g.content)&&!(typeof Blob<"u"&&g.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${g.path}`,g.path);if(!g.md5)throw a.file(`File missing md5 checksum: ${g.path}`,g.path);let d=new i([g.content],g.path,{type:"application/octet-stream"});p.append("files[]",d),u.push(g.md5)}p.append("checksums",JSON.stringify(u)),r&&r.length>0&&p.append("labels",JSON.stringify(r)),l&&p.append("via",l),c&&p.append("password",c),s?.build&&p.append("build","true"),s?.prerender&&p.append("prerender","true"),s?.spa&&p.append("spa","true");let y=new o(p),x=[];for await(let g of y.encode())x.push(Buffer.from(g));let b=Buffer.concat(x);return{body:b.buffer.slice(b.byteOffset,b.byteOffset+b.byteLength),headers:{"Content-Type":y.contentType,"Content-Length":Buffer.byteLength(b).toString()}}}j();function Qt(n,t,e,i=!0){let o=n===1?t:e;return i?`${n} ${o}`:o}re();le();F();ue();de();S();U();fe();var me=class extends V{constructor(t={}){if(R()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");super(t)}resolveInitialConfig(t){return te(t,{})}async loadFullConfig(){try{let t=await oe(this.clientOptions.configFile),e=te(this.clientOptions,t);e.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(e.deployToken):e.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(e.apiKey);let i=new N({...this.clientOptions,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();ee(o)}catch(t){throw this.initPromise=null,t}}async processInput(t,e){let i=typeof t=="string"?[t]:t;if(!Array.isArray(i)||!i.every(r=>typeof r=="string"))throw a.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw a.business("No files to deploy.");let{processFilesForNode:o}=await Promise.resolve().then(()=>(fe(),_e));return o(i,e)}getDeployBodyCreator(){return Ie}},et=me;export{W as API_KEY_HEX_LENGTH,rt as API_KEY_HINT_LENGTH,P as API_KEY_PREFIX,he as API_KEY_TOTAL_LENGTH,ot as AccountPlan,N as ApiHttp,st as AuthMethod,He as BLOCKED_EXTENSIONS,K as DEFAULT_API,Q as DEPLOYMENT_CONFIG_FILENAME,X as DEPLOY_TOKEN_HEX_LENGTH,O as DEPLOY_TOKEN_PREFIX,ye as DEPLOY_TOKEN_TOTAL_LENGTH,nt as DeploymentStatus,it as DomainStatus,f as ErrorType,D as FILE_VALIDATION_STATUS,D as FileValidationStatus,Je as JUNK_DIRECTORIES,I as LABEL_CONSTRAINTS,Ee as LABEL_PATTERN,L as PASSWORD_CONSTRAINTS,De as SPA_DEFAULT_CONFIG,me as Ship,a as ShipError,J as UNBUILT_PROJECT_MARKERS,Ke as UNSAFE_FILENAME_CHARS,It as __setTestEnvironment,pn as allValidFilesReady,G as calculateMD5,Re as createAccountResource,ve as createDeploymentResource,Ce as createDomainResource,xe as createTokenResource,et as default,yt as deserializeLabels,dt as extractSubdomain,Pe as filterJunk,pe as formatFileSize,ft as generateDeploymentUrl,mt as generateDomainUrl,_ as getCurrentConfig,R as getENV,Ze as getValidFiles,H as hasUnbuiltMarker,ge as hasUnsafeChars,B as isBlockedExtension,ut as isCustomDomain,ct as isDeployment,Se as isPlatformDomain,C as isShipError,oe as loadConfig,we as mergeDeployOptions,Ne as optimizeDeployPaths,Qt as pluralize,$e as processFilesForNode,te as resolveConfig,ht as serializeLabels,ee as setPlatformConfig,at as validateApiKey,pt as validateApiUrl,ke as validateDeployFile,Fe as validateDeployPath,lt as validateDeployToken,ce as validateFileName,ln as validateFiles};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|