@shipstatic/ship 0.5.4 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -576,6 +576,29 @@ declare function getValidFiles<T extends ValidatableFile>(files: T[]): T[];
576
576
  */
577
577
  declare function allValidFilesReady<T extends ValidatableFile>(files: T[]): boolean;
578
578
 
579
+ /**
580
+ * Validate a deploy path for security concerns.
581
+ * Rejects paths containing path traversal patterns or null bytes.
582
+ *
583
+ * Checks for:
584
+ * - Null bytes (\0) — path injection
585
+ * - /../ — directory traversal within path
586
+ * - ../ at start — upward traversal
587
+ * - /.. at end — trailing traversal
588
+ *
589
+ * Does NOT reject double dots in filenames (e.g., "foo..bar.txt" is safe).
590
+ *
591
+ * @param deployPath - The deployment path to validate
592
+ * @param sourceIdentifier - Human-readable identifier for error messages
593
+ * @throws {ShipError} If the path contains unsafe patterns
594
+ */
595
+ declare function validateDeployPath(deployPath: string, sourceIdentifier: string): void;
596
+
597
+ /**
598
+ * Get MIME type from file path (browser-compatible, no Node.js dependencies)
599
+ */
600
+ declare function getMimeType(path: string): string;
601
+
579
602
  /**
580
603
  * @file Manages loading and validation of client configuration.
581
604
  * This module uses `cosmiconfig` to find and load configuration from various
@@ -650,4 +673,4 @@ declare class Ship extends Ship$1 {
650
673
  protected getDeployBodyCreator(): DeployBodyCreator;
651
674
  }
652
675
 
653
- 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, validateFiles };
676
+ 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, getMimeType, getValidFiles, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig as setPlatformConfig, validateDeployPath, validateFiles };
package/dist/index.d.ts CHANGED
@@ -576,6 +576,29 @@ declare function getValidFiles<T extends ValidatableFile>(files: T[]): T[];
576
576
  */
577
577
  declare function allValidFilesReady<T extends ValidatableFile>(files: T[]): boolean;
578
578
 
579
+ /**
580
+ * Validate a deploy path for security concerns.
581
+ * Rejects paths containing path traversal patterns or null bytes.
582
+ *
583
+ * Checks for:
584
+ * - Null bytes (\0) — path injection
585
+ * - /../ — directory traversal within path
586
+ * - ../ at start — upward traversal
587
+ * - /.. at end — trailing traversal
588
+ *
589
+ * Does NOT reject double dots in filenames (e.g., "foo..bar.txt" is safe).
590
+ *
591
+ * @param deployPath - The deployment path to validate
592
+ * @param sourceIdentifier - Human-readable identifier for error messages
593
+ * @throws {ShipError} If the path contains unsafe patterns
594
+ */
595
+ declare function validateDeployPath(deployPath: string, sourceIdentifier: string): void;
596
+
597
+ /**
598
+ * Get MIME type from file path (browser-compatible, no Node.js dependencies)
599
+ */
600
+ declare function getMimeType(path: string): string;
601
+
579
602
  /**
580
603
  * @file Manages loading and validation of client configuration.
581
604
  * This module uses `cosmiconfig` to find and load configuration from various
@@ -650,4 +673,4 @@ declare class Ship extends Ship$1 {
650
673
  protected getDeployBodyCreator(): DeployBodyCreator;
651
674
  }
652
675
 
653
- 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, validateFiles };
676
+ 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, getMimeType, getValidFiles, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig as setPlatformConfig, validateDeployPath, validateFiles };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Ie=Object.defineProperty;var C=(n,e)=>()=>(n&&(e=n(n=0)),e);var Pe=(n,e)=>{for(var t in e)Ie(n,t,{get:e[t],enumerable:!0})};function T(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function pe(n){return z.some(e=>n===e||n.startsWith(e))}function et(n){if(!n.startsWith(R))throw p.validation(`API key must start with "${R}"`);if(n.length!==re)throw p.validation(`API key must be ${re} characters total (${R} + ${K} hex chars)`);let e=n.slice(R.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`API key must contain ${K} hexadecimal characters after "${R}" prefix`)}function tt(n){if(!n.startsWith(I))throw p.validation(`Deploy token must start with "${I}"`);if(n.length!==ae)throw p.validation(`Deploy token must be ${ae} characters total (${I} + ${j} hex chars)`);let e=n.slice(I.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`Deploy token must contain ${j} hexadecimal characters after "${I}" prefix`)}function nt(n){try{let e=new URL(n);if(!["http:","https:"].includes(e.protocol))throw p.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw p.validation("API URL must not contain a path");if(e.search||e.hash)throw p.validation("API URL must not contain query parameters or fragments")}catch(e){throw T(e)?e:p.validation("API URL must be a valid URL")}}function it(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(n)}function le(n,e){return n.endsWith(`.${e}`)}function ot(n,e){return!le(n,e)}function st(n,e){return le(n,e)?n.slice(0,-(e.length+1)):null}function rt(n,e){return`https://${n}.${e||"shipstatic.com"}`}function at(n){return`https://${n}`}function ct(n){return!n||n.length===0?null:JSON.stringify(n)}function ut(n){if(!n)return[];try{let e=JSON.parse(n);return Array.isArray(e)?e:[]}catch{return[]}}var We,Je,Xe,m,B,p,z,R,K,re,Qe,I,j,ae,Ze,V,N,h,pt,lt,x=C(()=>{"use strict";We={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Je={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Xe={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"})(m||(m={}));B={client:new Set([m.Business,m.Config,m.File,m.Validation]),network:new Set([m.Network]),auth:new Set([m.Authentication])},p=class n extends Error{type;status;details;constructor(e,t,i,o){super(t),this.type=e,this.status=i,this.details=o,this.name="ShipError"}toResponse(){let e=this.type===m.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static fromResponse(e){return new n(e.error,e.message,e.status,e.details)}static validation(e,t){return new n(m.Validation,e,400,t)}static notFound(e,t){let i=t?`${e} ${t} not found`:`${e} not found`;return new n(m.NotFound,i,404)}static rateLimit(e="Too many requests"){return new n(m.RateLimit,e,429)}static authentication(e="Authentication required",t){return new n(m.Authentication,e,401,t)}static business(e,t=400){return new n(m.Business,e,t)}static network(e,t){return new n(m.Network,e,void 0,{cause:t})}static cancelled(e){return new n(m.Cancelled,e)}static file(e,t){return new n(m.File,e,void 0,{filePath:t})}static config(e,t){return new n(m.Config,e,void 0,t)}static api(e,t=500){return new n(m.Api,e,t)}static database(e,t=500){return new n(m.Api,e,t)}static storage(e,t=500){return new n(m.Api,e,t)}get filePath(){return this.details?.filePath}isClientError(){return B.client.has(this.type)}isNetworkError(){return B.network.has(this.type)}isAuthError(){return B.auth.has(this.type)}isValidationError(){return this.type===m.Validation}isFileError(){return this.type===m.File}isConfigError(){return this.type===m.Config}isType(e){return this.type===e}};z=["text/html","text/css","text/plain","text/markdown","text/xml","text/csv","text/tab-separated-values","text/yaml","text/vcard","text/mdx","text/x-mdx","text/vtt","text/srt","text/calendar","text/javascript","text/typescript","application/x-typescript","text/tsx","text/jsx","text/x-scss","text/x-sass","text/less","text/x-less","text/stylus","text/x-vue","text/x-svelte","text/x-sql","text/x-diff","text/x-patch","text/x-protobuf","text/x-ini","text/x-tex","text/x-latex","text/x-bibtex","text/x-r-markdown","image/","audio/","video/","font/","application/javascript","application/ecmascript","application/x-javascript","application/wasm","application/json","application/ld+json","application/geo+json","application/manifest+json","application/x-ipynb+json","application/x-ndjson","application/ndjson","text/x-ndjson","application/jsonl","text/jsonl","application/json5","text/json5","application/schema+json","application/source-map","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/feed+json","application/vnd.google-earth.kml+xml","application/yaml","application/toml","application/pdf","application/x-subrip","application/sql","application/graphql","application/graphql+json","application/x-protobuf","application/x-ini","application/x-tex","application/x-bibtex","model/gltf+json","model/gltf-binary","application/mp4","application/font-woff","application/font-woff2","application/x-font-woff","application/x-woff","application/vnd.ms-fontobject","application/x-font-ttf","application/x-font-truetype","application/x-font-otf","application/x-font-opentype"];R="ship-",K=64,re=R.length+K,Qe=4,I="token-",j=64,ae=I.length+j,Ze={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},V="ship.json";N="https://api.shipstatic.com",h={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};pt={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},lt=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function q(n){H=n}function O(){if(H===null)throw p.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return H}var H,F=C(()=>{"use strict";x();H=null});function Oe(n){G=n}function Fe(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function A(){return G||Fe()}var G,w=C(()=>{"use strict";G=null});async function ke(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let r=Math.ceil(n.size/2097152),a=0,c=new e.ArrayBuffer,s=new FileReader,f=()=>{let l=a*2097152,u=Math.min(l+2097152,n.size);s.readAsArrayBuffer(n.slice(l,u))};s.onload=l=>{let u=l.target?.result;if(!u){i(p.business("Failed to read file chunk"));return}c.append(u),a++,a<r?f():t({md5:c.end()})},s.onerror=()=>{i(p.business("Failed to calculate MD5: FileReader error"))},f()})}async function Ne(n){let e=await import("crypto");if(Buffer.isBuffer(n)){let i=e.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let t=await import("fs");return new Promise((i,o)=>{let r=e.createHash("md5"),a=t.createReadStream(n);a.on("error",c=>o(p.business(`Failed to read file for MD5: ${c.message}`))),a.on("data",c=>r.update(c)),a.on("end",()=>i({md5:r.digest("hex")}))})}async function L(n){let e=A();if(e==="browser"){if(!(n instanceof Blob))throw p.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return ke(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw p.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Ne(n)}throw p.business("Unknown or unsupported execution environment for MD5 calculation.")}var _=C(()=>{"use strict";w();x()});import{z as k}from"zod";function ye(n){try{return Le.parse(n)}catch(e){if(e instanceof k.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw p.config(`Configuration validation failed${i}: ${t.message}`)}throw p.config("Configuration validation failed")}}async function _e(n){try{if(A()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(W,{searchPlaces:[`.${W}rc`,"package.json",`${t.homedir()}/.${W}rc`],stopDir:t.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return ye(o.config)}catch(e){if(T(e))throw e}return{}}async function J(n){if(A()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await _e(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return ye(i)}var W,Le,X=C(()=>{"use strict";x();w();W="ship",Le=k.object({apiUrl:k.string().url().optional(),apiKey:k.string().optional(),deployToken:k.string().optional()}).strict()});import{isJunk as Me}from"junk";function Ee(n){return!n||n.length===0?[]:n.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let i=t[t.length-1];if(Me(i))return!1;for(let r of t)if(r.startsWith(".")||r.length>255)return!1;let o=t.slice(0,-1);for(let r of o)if(Ue.some(a=>r.toLowerCase()===a.toLowerCase()))return!1;return!0})}var Ue,Z=C(()=>{"use strict";Ue=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Se(n){if(!n||n.length===0)return"";let e=n.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(r=>r.split("/").filter(Boolean)),i=[],o=Math.min(...t.map(r=>r.length));for(let r=0;r<o;r++){let a=t[0][r];if(t.every(c=>c[r]===a))i.push(a);else break}return i.join("/")}function U(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ee=C(()=>{"use strict"});function Ae(n,e={}){if(e.flatten===!1)return n.map(i=>({path:U(i),name:te(i)}));let t=Be(n);return n.map(i=>{let o=U(i);if(t){let r=t.endsWith("/")?t:`${t}/`;o.startsWith(r)&&(o=o.substring(r.length))}return o||(o=te(i)),{path:o,name:te(i)}})}function Be(n){if(!n.length)return"";let t=n.map(r=>U(r)).map(r=>r.split("/")),i=[],o=Math.min(...t.map(r=>r.length));for(let r=0;r<o-1;r++){let a=t[0][r];if(t.every(c=>c[r]===a))i.push(a);else break}return i.join("/")}function te(n){return n.split(/[/\\]/).pop()||n}var ne=C(()=>{"use strict";ee()});var we={};Pe(we,{processFilesForNode:()=>Te});import*as E from"fs";import*as D from"path";function Ce(n,e=new Set){let t=[],i=E.realpathSync(n);if(e.has(i))return t;e.add(i);let o=E.readdirSync(n);for(let r of o){let a=D.join(n,r),c=E.statSync(a);if(c.isDirectory()){let s=Ce(a,e);t.push(...s)}else c.isFile()&&t.push(a)}return t}async function Te(n,e={}){if(A()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(d=>{let g=D.resolve(d);try{return E.statSync(g).isDirectory()?Ce(g):[g]}catch{throw p.file(`Path does not exist: ${d}`,d)}}),i=[...new Set(t)],o=Ee(i);if(o.length===0)return[];let r=n.map(d=>D.resolve(d)),a=Se(r.map(d=>{try{return E.statSync(d).isDirectory()?d:D.dirname(d)}catch{return D.dirname(d)}})),c=o.map(d=>{if(a&&a.length>0){let g=D.relative(a,d);if(g&&typeof g=="string"&&!g.startsWith(".."))return g.replace(/\\/g,"/")}return D.basename(d)}),s=Ae(c,{flatten:e.pathDetect!==!1}),f=[],l=0,u=O();for(let d=0;d<o.length;d++){let g=o[d],S=s[d].path;try{let v=E.statSync(g);if(v.size===0)continue;if(v.size>u.maxFileSize)throw p.business(`File ${g} is too large. Maximum allowed size is ${u.maxFileSize/(1024*1024)}MB.`);if(l+=v.size,l>u.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${u.maxTotalSize/(1024*1024)}MB.`);let b=E.readFileSync(g),{md5:Re}=await L(b);if(S.includes("\0")||S.includes("/../")||S.startsWith("../")||S.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${S}" for file: ${g}`);f.push({path:S,content:b,size:b.length,md5:Re})}catch(v){if(T(v))throw v;let b=v instanceof Error?v.message:String(v);throw p.file(`Failed to read file "${g}": ${b}`,g)}}if(f.length>u.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${u.maxFilesCount} files.`);return f}var oe=C(()=>{"use strict";w();_();Z();x();F();ne();ee()});x();var $=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let i=this.handlers.get(e);i&&(i.delete(t),i.size===0&&this.handlers.delete(e))}emit(e,...t){let i=this.handlers.get(e);if(!i)return;let o=Array.from(i);for(let r of o)try{r(...t)}catch(a){i.delete(r),e!=="error"&&setTimeout(()=>{a instanceof Error?this.emit("error",a,String(e)):this.emit("error",new Error(String(a)),String(e))},0)}}transfer(e){this.handlers.forEach((t,i)=>{t.forEach(o=>{e.on(i,o)})})}clear(){this.handlers.clear()}};var y={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},be=3e4,P=class extends ${constructor(e){super(),this.apiUrl=e.apiUrl||N,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??be,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,t,i){let o=this.mergeHeaders(t.headers),{signal:r,cleanup:a}=this.createTimeoutSignal(t.signal),c={...t,headers:o,credentials:o.Authorization?void 0:"include",signal:r};this.emit("request",e,c);try{let s=await fetch(e,c);return a(),s.ok||await this.handleResponseError(s,i),this.emit("response",this.safeClone(s),e),{data:await this.parseResponse(this.safeClone(s)),status:s.status}}catch(s){a();let f=s instanceof Error?s:new Error(String(s));this.emit("error",f,e),this.handleFetchError(s,i)}}async request(e,t,i){let{data:o}=await this.executeRequest(e,t,i);return o}async requestWithStatus(e,t,i){return this.executeRequest(e,t,i)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let t=new AbortController,i=setTimeout(()=>t.abort(),this.timeout);if(e){let o=()=>t.abort();e.addEventListener("abort",o),e.aborted&&t.abort()}return{signal:t.signal,cleanup:()=>clearTimeout(i)}}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,t){let i={};try{if(e.headers.get("content-type")?.includes("application/json")){let a=await e.json();if(a&&typeof a=="object"){let c=a;typeof c.message=="string"&&(i.message=c.message),typeof c.error=="string"&&(i.error=c.error)}}else i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let o=i.message||i.error||`${t} failed`;throw e.status===401?p.authentication(o):p.api(o,e.status)}handleFetchError(e,t){throw T(e)?e:e instanceof Error&&e.name==="AbortError"?p.cancelled(`${t} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?p.network(`${t} failed: ${e.message}`,e):e instanceof Error?p.business(`${t} failed: ${e.message}`):p.business(`${t} failed: Unknown error`)}async deploy(e,t={}){if(!e.length)throw p.business("No files to deploy");for(let a of e)if(!a.md5)throw p.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:i,headers:o}=await this.createDeployBody(e,t.labels,t.via),r={};return t.deployToken?r.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(r.Authorization=`Bearer ${t.apiKey}`),t.caller&&(r["X-Caller"]=t.caller),this.request(`${t.apiUrl||this.apiUrl}${y.DEPLOYMENTS}`,{method:"POST",body:i,headers:{...o,...r},signal:t.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,t){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:t})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,t,i){let o={};t&&(o.deployment=t),i!==void 0&&(o.labels=i);let{data:r,status:a}=await this.requestWithStatus(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Set domain");return{...r,isCreate:a===201}}async listDomains(){return this.request(`${this.apiUrl}${y.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,t){let i={};return e!==void 0&&(i.ttl=e),t!==void 0&&(i.labels=t),this.request(`${this.apiUrl}${y.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${y.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${y.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${y.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${y.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${y.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e){let t=e.find(a=>a.path==="index.html"||a.path==="/index.html");if(!t||t.size>100*1024)return!1;let i;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))i=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)i=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)i=await t.content.text();else return!1;let o={files:e.map(a=>a.path),index:i};return(await this.request(`${this.apiUrl}${y.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"SPA check")).isSPA}};x();F();x();x();function Y(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||N,apiKey:n.apiKey!==void 0?n.apiKey:e.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:e.deployToken},i={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(i.apiKey=t.apiKey),t.deployToken!==void 0&&(i.deployToken=t.deployToken),i}function ce(n,e){let t={...n};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.caller===void 0&&e.caller!==void 0&&(t.caller=e.caller),t}x();_();async function $e(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:i}=await L(t);return{path:V,content:t,size:e.length,md5:i}}async function ue(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===V))return n;try{if(await e.checkSPA(n)){let o=await $e();return[...n,o]}}catch{}return n}function fe(n){let{getApi:e,ensureInit:t,processInput:i,clientDefaults:o,hasAuth:r}=n;return{create:async(a,c={})=>{await t();let s=o?ce(c,o):c;if(r&&!r()&&!s.deployToken&&!s.apiKey)throw p.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!i)throw p.config("processInput function is not provided.");let f=e(),l=await i(a,s);return l=await ue(l,f,s),f.deploy(l,s)},list:async()=>(await t(),e().listDeployments()),get:async a=>(await t(),e().getDeployment(a)),set:async(a,c)=>(await t(),e().updateDeploymentLabels(a,c.labels)),remove:async a=>{await t(),await e().removeDeployment(a)}}}function me(n){let{getApi:e,ensureInit:t}=n;return{set:async(i,o={})=>(await t(),e().setDomain(i,o.deployment,o.labels)),list:async()=>(await t(),e().listDomains()),get:async i=>(await t(),e().getDomain(i)),remove:async i=>{await t(),await e().removeDomain(i)},verify:async i=>(await t(),e().verifyDomain(i)),validate:async i=>(await t(),e().validateDomain(i)),dns:async i=>(await t(),e().getDomainDns(i)),records:async i=>(await t(),e().getDomainRecords(i)),share:async i=>(await t(),e().getDomainShare(i))}}function de(n){let{getApi:e,ensureInit:t}=n;return{get:async()=>(await t(),e().getAccount())}}function he(n){let{getApi:e,ensureInit:t}=n;return{create:async(i={})=>(await t(),e().createToken(i.ttl,i.labels)),list:async()=>(await t(),e().listTokens()),remove:async i=>{await t(),await e().removeToken(i)}}}var M=class{constructor(e={}){this.initPromise=null;this._config=null;this.auth=null;this.clientOptions=e,e.deployToken?this.auth={type:"token",value:e.deployToken}:e.apiKey&&(this.auth={type:"apiKey",value:e.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(e);this.http=new P({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=fe({...i,processInput:(o,r)=>this.processInput(o,r),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=me(i),this._account=de(i),this._tokens=he(i)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}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=O(),this._config)}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}setDeployToken(e){if(!e||typeof e!="string")throw p.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw p.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};x();w();X();F();x();import ge from"mime-db";var Q={};for(let n in ge){let e=ge[n];e&&e.extensions&&e.extensions.forEach(t=>{Q[t]||(Q[t]=n)})}function xe(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return Q[e]||"application/octet-stream"}async function De(n,e,t){let{FormData:i,File:o}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),a=new i,c=[];for(let u of n){let d=xe(u.path),g;if(Buffer.isBuffer(u.content))g=new o([u.content],u.path,{type:d});else if(typeof Blob<"u"&&u.content instanceof Blob)g=new o([u.content],u.path,{type:d});else throw p.file(`Unsupported file.content type for Node.js: ${u.path}`,u.path);if(!u.md5)throw p.file(`File missing md5 checksum: ${u.path}`,u.path);let S=u.path.startsWith("/")?u.path:"/"+u.path;a.append("files[]",g,S),c.push(u.md5)}a.append("checksums",JSON.stringify(c)),e&&e.length>0&&a.append("labels",JSON.stringify(e)),t&&a.append("via",t);let s=new r(a),f=[];for await(let u of s.encode())f.push(Buffer.from(u));let l=Buffer.concat(f);return{body:l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength),headers:{"Content-Type":s.contentType,"Content-Length":Buffer.byteLength(l).toString()}}}_();function qt(n,e,t,i=!0){let o=n===1?e:t;return i?`${n} ${o}`:o}Z();ne();w();x();import Ke from"mime-db";var ve=Ke,je=new Set(Object.keys(ve)),ze=new Map(Object.entries(ve).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)]));function ie(n,e=1){if(n===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,o)).toFixed(e))+" "+i[o]}function Ve(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(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,i=n.split("/").pop()||n;return t.test(i)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function He(n,e){if(n.startsWith("."))return!0;let t=n.toLowerCase().split(".");if(t.length>1&&t[t.length-1]){let i=t[t.length-1],o=ze.get(e);if(o&&!o.has(i))return!1}return!0}function tn(n,e){let t=[],i=[],o=[];if(n.length===0){let s={file:"(no files)",message:"At least one file must be provided"};return t.push(s),{files:[],validFiles:[],errors:t,warnings:[],canDeploy:!1}}if(n.length>e.maxFilesCount){let s={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${e.maxFilesCount}`};return t.push(s),{files:n.map(f=>({...f,status:h.VALIDATION_FAILED,statusMessage:s.message})),validFiles:[],errors:t,warnings:[],canDeploy:!1}}let r=0;for(let s of n){let f=h.READY,l="Ready for upload",u=s.name?Ve(s.name):{valid:!1,reason:"File name cannot be empty"};if(s.status===h.PROCESSING_ERROR)f=h.VALIDATION_FAILED,l=s.statusMessage||"File failed during processing",t.push({file:s.name,message:l});else if(s.size===0){f=h.EXCLUDED,l="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:s.name,message:l}),o.push({...s,status:f,statusMessage:l});continue}else s.size<0?(f=h.VALIDATION_FAILED,l="File size must be positive",t.push({file:s.name,message:l})):!s.name||s.name.trim().length===0?(f=h.VALIDATION_FAILED,l="File name cannot be empty",t.push({file:s.name||"(empty)",message:l})):s.name.includes("\0")?(f=h.VALIDATION_FAILED,l="File name contains invalid characters (null byte)",t.push({file:s.name,message:l})):u.valid?!s.type||s.type.trim().length===0?(f=h.VALIDATION_FAILED,l="File MIME type is required",t.push({file:s.name,message:l})):pe(s.type)?!z.some(d=>s.type===d)&&!je.has(s.type)?(f=h.VALIDATION_FAILED,l=`Invalid MIME type "${s.type}"`,t.push({file:s.name,message:l})):He(s.name,s.type)?s.size>e.maxFileSize?(f=h.VALIDATION_FAILED,l=`File size (${ie(s.size)}) exceeds limit of ${ie(e.maxFileSize)}`,t.push({file:s.name,message:l})):(r+=s.size,r>e.maxTotalSize&&(f=h.VALIDATION_FAILED,l=`Total size would exceed limit of ${ie(e.maxTotalSize)}`,t.push({file:s.name,message:l}))):(f=h.VALIDATION_FAILED,l="File extension does not match MIME type",t.push({file:s.name,message:l})):(f=h.VALIDATION_FAILED,l=`File type "${s.type}" is not allowed`,t.push({file:s.name,message:l})):(f=h.VALIDATION_FAILED,l=u.reason||"Invalid file name",t.push({file:s.name,message:l}));o.push({...s,status:f,statusMessage:l})}t.length>0&&(o=o.map(s=>s.status===h.EXCLUDED?s:{...s,status:h.VALIDATION_FAILED,statusMessage:s.status===h.VALIDATION_FAILED?s.statusMessage:"Deployment failed due to validation errors in bundle"}));let a=t.length===0?o.filter(s=>s.status===h.READY):[],c=t.length===0;return{files:o,validFiles:a,errors:t,warnings:i,canDeploy:c}}function qe(n){return n.filter(e=>e.status===h.READY)}function nn(n){return qe(n).length>0}x();X();F();oe();w();var se=class extends M{constructor(e={}){if(A()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return Y(e,{})}async loadFullConfig(){try{let e=await J(this.clientOptions.configFile),t=Y(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let i=new P({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();q(o)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){let i=typeof e=="string"?[e]:e;if(!Array.isArray(i)||!i.every(r=>typeof r=="string"))throw p.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw p.business("No files to deploy.");let{processFilesForNode:o}=await Promise.resolve().then(()=>(oe(),we));return o(i,t)}getDeployBodyCreator(){return De}},Ge=se;export{z as ALLOWED_MIME_TYPES,K as API_KEY_HEX_LENGTH,Qe as API_KEY_HINT_LENGTH,R as API_KEY_PREFIX,re as API_KEY_TOTAL_LENGTH,Xe as AccountPlan,P as ApiHttp,Ze as AuthMethod,N as DEFAULT_API,V as DEPLOYMENT_CONFIG_FILENAME,j as DEPLOY_TOKEN_HEX_LENGTH,I as DEPLOY_TOKEN_PREFIX,ae as DEPLOY_TOKEN_TOTAL_LENGTH,We as DeploymentStatus,Je as DomainStatus,m as ErrorType,h as FILE_VALIDATION_STATUS,h as FileValidationStatus,Ue as JUNK_DIRECTORIES,pt as LABEL_CONSTRAINTS,lt as LABEL_PATTERN,se as Ship,p as ShipError,Oe as __setTestEnvironment,nn as allValidFilesReady,L as calculateMD5,de as createAccountResource,fe as createDeploymentResource,me as createDomainResource,he as createTokenResource,Ge as default,ut as deserializeLabels,st as extractSubdomain,Ee as filterJunk,ie as formatFileSize,rt as generateDeploymentUrl,at as generateDomainUrl,O as getCurrentConfig,A as getENV,qe as getValidFiles,pe as isAllowedMimeType,ot as isCustomDomain,it as isDeployment,le as isPlatformDomain,T as isShipError,J as loadConfig,ce as mergeDeployOptions,Ae as optimizeDeployPaths,qt as pluralize,Te as processFilesForNode,Y as resolveConfig,ct as serializeLabels,q as setPlatformConfig,et as validateApiKey,nt as validateApiUrl,tt as validateDeployToken,tn as validateFiles};
1
+ var Pe=Object.defineProperty;var A=(n,e)=>()=>(n&&(e=n(n=0)),e);var be=(n,e)=>{for(var t in e)Pe(n,t,{get:e[t],enumerable:!0})};function T(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function pe(n){return z.some(e=>n===e||n.startsWith(e))}function et(n){if(!n.startsWith(C))throw p.validation(`API key must start with "${C}"`);if(n.length!==re)throw p.validation(`API key must be ${re} characters total (${C} + ${K} hex chars)`);let e=n.slice(C.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`API key must contain ${K} hexadecimal characters after "${C}" prefix`)}function tt(n){if(!n.startsWith(w))throw p.validation(`Deploy token must start with "${w}"`);if(n.length!==ae)throw p.validation(`Deploy token must be ${ae} characters total (${w} + ${j} hex chars)`);let e=n.slice(w.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`Deploy token must contain ${j} hexadecimal characters after "${w}" prefix`)}function nt(n){try{let e=new URL(n);if(!["http:","https:"].includes(e.protocol))throw p.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw p.validation("API URL must not contain a path");if(e.search||e.hash)throw p.validation("API URL must not contain query parameters or fragments")}catch(e){throw T(e)?e:p.validation("API URL must be a valid URL")}}function it(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(n)}function le(n,e){return n.endsWith(`.${e}`)}function ot(n,e){return!le(n,e)}function st(n,e){return le(n,e)?n.slice(0,-(e.length+1)):null}function rt(n,e){return`https://${n}.${e||"shipstatic.com"}`}function at(n){return`https://${n}`}function ct(n){return!n||n.length===0?null:JSON.stringify(n)}function ut(n){if(!n)return[];try{let e=JSON.parse(n);return Array.isArray(e)?e:[]}catch{return[]}}var We,Je,Xe,m,B,p,z,C,K,re,Qe,w,j,ae,Ze,H,N,h,pt,lt,x=A(()=>{"use strict";We={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Je={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Xe={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"})(m||(m={}));B={client:new Set([m.Business,m.Config,m.File,m.Validation]),network:new Set([m.Network]),auth:new Set([m.Authentication])},p=class n extends Error{type;status;details;constructor(e,t,i,o){super(t),this.type=e,this.status=i,this.details=o,this.name="ShipError"}toResponse(){let e=this.type===m.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static fromResponse(e){return new n(e.error,e.message,e.status,e.details)}static validation(e,t){return new n(m.Validation,e,400,t)}static notFound(e,t){let i=t?`${e} ${t} not found`:`${e} not found`;return new n(m.NotFound,i,404)}static rateLimit(e="Too many requests"){return new n(m.RateLimit,e,429)}static authentication(e="Authentication required",t){return new n(m.Authentication,e,401,t)}static business(e,t=400){return new n(m.Business,e,t)}static network(e,t){return new n(m.Network,e,void 0,{cause:t})}static cancelled(e){return new n(m.Cancelled,e)}static file(e,t){return new n(m.File,e,void 0,{filePath:t})}static config(e,t){return new n(m.Config,e,void 0,t)}static api(e,t=500){return new n(m.Api,e,t)}static database(e,t=500){return new n(m.Api,e,t)}static storage(e,t=500){return new n(m.Api,e,t)}get filePath(){return this.details?.filePath}isClientError(){return B.client.has(this.type)}isNetworkError(){return B.network.has(this.type)}isAuthError(){return B.auth.has(this.type)}isValidationError(){return this.type===m.Validation}isFileError(){return this.type===m.File}isConfigError(){return this.type===m.Config}isType(e){return this.type===e}};z=["text/html","text/css","text/plain","text/markdown","text/xml","text/csv","text/tab-separated-values","text/yaml","text/vcard","text/mdx","text/x-mdx","text/vtt","text/srt","text/calendar","text/javascript","text/typescript","application/x-typescript","text/tsx","text/jsx","text/x-scss","text/x-sass","text/less","text/x-less","text/stylus","text/x-vue","text/x-svelte","text/x-sql","text/x-diff","text/x-patch","text/x-protobuf","text/x-ini","text/x-tex","text/x-latex","text/x-bibtex","text/x-r-markdown","image/","audio/","video/","font/","application/javascript","application/ecmascript","application/x-javascript","application/wasm","application/json","application/ld+json","application/geo+json","application/manifest+json","application/x-ipynb+json","application/x-ndjson","application/ndjson","text/x-ndjson","application/jsonl","text/jsonl","application/json5","text/json5","application/schema+json","application/source-map","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/feed+json","application/vnd.google-earth.kml+xml","application/yaml","application/toml","application/pdf","application/x-subrip","application/sql","application/graphql","application/graphql+json","application/x-protobuf","application/x-ini","application/x-tex","application/x-bibtex","model/gltf+json","model/gltf-binary","application/mp4","application/font-woff","application/font-woff2","application/x-font-woff","application/x-woff","application/vnd.ms-fontobject","application/x-font-ttf","application/x-font-truetype","application/x-font-otf","application/x-font-opentype"];C="ship-",K=64,re=C.length+K,Qe=4,w="token-",j=64,ae=w.length+j,Ze={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},H="ship.json";N="https://api.shipstatic.com",h={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};pt={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},lt=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function q(n){V=n}function b(){if(V===null)throw p.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return V}var V,O=A(()=>{"use strict";x();V=null});function St(n){Y=n}function Fe(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function v(){return Y||Fe()}var Y,I=A(()=>{"use strict";Y=null});async function ke(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let r=Math.ceil(n.size/2097152),a=0,c=new e.ArrayBuffer,s=new FileReader,u=()=>{let l=a*2097152,f=Math.min(l+2097152,n.size);s.readAsArrayBuffer(n.slice(l,f))};s.onload=l=>{let f=l.target?.result;if(!f){i(p.business("Failed to read file chunk"));return}c.append(f),a++,a<r?u():t({md5:c.end()})},s.onerror=()=>{i(p.business("Failed to calculate MD5: FileReader error"))},u()})}async function Ne(n){let e=await import("crypto");if(Buffer.isBuffer(n)){let i=e.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let t=await import("fs");return new Promise((i,o)=>{let r=e.createHash("md5"),a=t.createReadStream(n);a.on("error",c=>o(p.business(`Failed to read file for MD5: ${c.message}`))),a.on("data",c=>r.update(c)),a.on("end",()=>i({md5:r.digest("hex")}))})}async function L(n){let e=v();if(e==="browser"){if(!(n instanceof Blob))throw p.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return ke(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw p.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Ne(n)}throw p.business("Unknown or unsupported execution environment for MD5 calculation.")}var _=A(()=>{"use strict";I();x()});import{isJunk as Me}from"junk";function Ee(n){return!n||n.length===0?[]:n.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let i=t[t.length-1];if(Me(i))return!1;for(let r of t)if(r.startsWith(".")||r.length>255)return!1;let o=t.slice(0,-1);for(let r of o)if(Ue.some(a=>r.toLowerCase()===a.toLowerCase()))return!1;return!0})}var Ue,Q=A(()=>{"use strict";Ue=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Se(n){if(!n||n.length===0)return"";let e=n.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(r=>r.split("/").filter(Boolean)),i=[],o=Math.min(...t.map(r=>r.length));for(let r=0;r<o;r++){let a=t[0][r];if(t.every(c=>c[r]===a))i.push(a);else break}return i.join("/")}function U(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Z=A(()=>{"use strict"});function Ae(n,e={}){if(e.flatten===!1)return n.map(i=>({path:U(i),name:ee(i)}));let t=Be(n);return n.map(i=>{let o=U(i);if(t){let r=t.endsWith("/")?t:`${t}/`;o.startsWith(r)&&(o=o.substring(r.length))}return o||(o=ee(i)),{path:o,name:ee(i)}})}function Be(n){if(!n.length)return"";let t=n.map(r=>U(r)).map(r=>r.split("/")),i=[],o=Math.min(...t.map(r=>r.length));for(let r=0;r<o-1;r++){let a=t[0][r];if(t.every(c=>c[r]===a))i.push(a);else break}return i.join("/")}function ee(n){return n.split(/[/\\]/).pop()||n}var te=A(()=>{"use strict";Z()});function Te(n,e){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${n}" for file: ${e}`)}var ie=A(()=>{"use strict";x()});var Re={};be(Re,{processFilesForNode:()=>we});import*as E from"fs";import*as D from"path";function Ce(n,e=new Set){let t=[],i=E.realpathSync(n);if(e.has(i))return t;e.add(i);let o=E.readdirSync(n);for(let r of o){let a=D.join(n,r),c=E.statSync(a);if(c.isDirectory()){let s=Ce(a,e);t.push(...s)}else c.isFile()&&t.push(a)}return t}async function we(n,e={}){if(v()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(d=>{let g=D.resolve(d);try{return E.statSync(g).isDirectory()?Ce(g):[g]}catch{throw p.file(`Path does not exist: ${d}`,d)}}),i=[...new Set(t)],o=Ee(i);if(o.length===0)return[];let r=n.map(d=>D.resolve(d)),a=Se(r.map(d=>{try{return E.statSync(d).isDirectory()?d:D.dirname(d)}catch{return D.dirname(d)}})),c=o.map(d=>{if(a&&a.length>0){let g=D.relative(a,d);if(g&&typeof g=="string"&&!g.startsWith(".."))return g.replace(/\\/g,"/")}return D.basename(d)}),s=Ae(c,{flatten:e.pathDetect!==!1}),u=[],l=0,f=b();for(let d=0;d<o.length;d++){let g=o[d],k=s[d].path;try{Te(k,g);let S=E.statSync(g);if(S.size===0)continue;if(S.size>f.maxFileSize)throw p.business(`File ${g} is too large. Maximum allowed size is ${f.maxFileSize/(1024*1024)}MB.`);if(l+=S.size,l>f.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${f.maxTotalSize/(1024*1024)}MB.`);let P=E.readFileSync(g),{md5:Ie}=await L(P);u.push({path:k,content:P,size:P.length,md5:Ie})}catch(S){if(T(S))throw S;let P=S instanceof Error?S.message:String(S);throw p.file(`Failed to read file "${g}": ${P}`,g)}}if(u.length>f.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${f.maxFilesCount} files.`);return u}var oe=A(()=>{"use strict";I();_();Q();ie();x();O();te();Z()});x();var $=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let i=this.handlers.get(e);i&&(i.delete(t),i.size===0&&this.handlers.delete(e))}emit(e,...t){let i=this.handlers.get(e);if(!i)return;let o=Array.from(i);for(let r of o)try{r(...t)}catch(a){i.delete(r),e!=="error"&&setTimeout(()=>{a instanceof Error?this.emit("error",a,String(e)):this.emit("error",new Error(String(a)),String(e))},0)}}transfer(e){this.handlers.forEach((t,i)=>{t.forEach(o=>{e.on(i,o)})})}clear(){this.handlers.clear()}};var y={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Oe=3e4,R=class extends ${constructor(e){super(),this.apiUrl=e.apiUrl||N,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Oe,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,t,i){let o=this.mergeHeaders(t.headers),{signal:r,cleanup:a}=this.createTimeoutSignal(t.signal),c={...t,headers:o,credentials:o.Authorization?void 0:"include",signal:r};this.emit("request",e,c);try{let s=await fetch(e,c);return a(),s.ok||await this.handleResponseError(s,i),this.emit("response",this.safeClone(s),e),{data:await this.parseResponse(this.safeClone(s)),status:s.status}}catch(s){a();let u=s instanceof Error?s:new Error(String(s));this.emit("error",u,e),this.handleFetchError(s,i)}}async request(e,t,i){let{data:o}=await this.executeRequest(e,t,i);return o}async requestWithStatus(e,t,i){return this.executeRequest(e,t,i)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let t=new AbortController,i=setTimeout(()=>t.abort(),this.timeout);if(e){let o=()=>t.abort();e.addEventListener("abort",o),e.aborted&&t.abort()}return{signal:t.signal,cleanup:()=>clearTimeout(i)}}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,t){let i={};try{if(e.headers.get("content-type")?.includes("application/json")){let a=await e.json();if(a&&typeof a=="object"){let c=a;typeof c.message=="string"&&(i.message=c.message),typeof c.error=="string"&&(i.error=c.error)}}else i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let o=i.message||i.error||`${t} failed`;throw e.status===401?p.authentication(o):p.api(o,e.status)}handleFetchError(e,t){throw T(e)?e:e instanceof Error&&e.name==="AbortError"?p.cancelled(`${t} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?p.network(`${t} failed: ${e.message}`,e):e instanceof Error?p.business(`${t} failed: ${e.message}`):p.business(`${t} failed: Unknown error`)}async deploy(e,t={}){if(!e.length)throw p.business("No files to deploy");for(let a of e)if(!a.md5)throw p.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:i,headers:o}=await this.createDeployBody(e,t.labels,t.via),r={};return t.deployToken?r.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(r.Authorization=`Bearer ${t.apiKey}`),t.caller&&(r["X-Caller"]=t.caller),this.request(`${t.apiUrl||this.apiUrl}${y.DEPLOYMENTS}`,{method:"POST",body:i,headers:{...o,...r},signal:t.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,t){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:t})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,t,i){let o={};t&&(o.deployment=t),i!==void 0&&(o.labels=i);let{data:r,status:a}=await this.requestWithStatus(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Set domain");return{...r,isCreate:a===201}}async listDomains(){return this.request(`${this.apiUrl}${y.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,t){let i={};return e!==void 0&&(i.ttl=e),t!==void 0&&(i.labels=t),this.request(`${this.apiUrl}${y.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${y.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${y.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${y.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${y.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${y.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e){let t=e.find(a=>a.path==="index.html"||a.path==="/index.html");if(!t||t.size>100*1024)return!1;let i;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))i=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)i=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)i=await t.content.text();else return!1;let o={files:e.map(a=>a.path),index:i};return(await this.request(`${this.apiUrl}${y.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"SPA check")).isSPA}};x();O();x();x();function G(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||N,apiKey:n.apiKey!==void 0?n.apiKey:e.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:e.deployToken},i={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(i.apiKey=t.apiKey),t.deployToken!==void 0&&(i.deployToken=t.deployToken),i}function ce(n,e){let t={...n};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.caller===void 0&&e.caller!==void 0&&(t.caller=e.caller),t}x();_();async function $e(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:i}=await L(t);return{path:H,content:t,size:e.length,md5:i}}async function ue(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===H))return n;try{if(await e.checkSPA(n)){let o=await $e();return[...n,o]}}catch{}return n}function fe(n){let{getApi:e,ensureInit:t,processInput:i,clientDefaults:o,hasAuth:r}=n;return{create:async(a,c={})=>{await t();let s=o?ce(c,o):c;if(r&&!r()&&!s.deployToken&&!s.apiKey)throw p.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!i)throw p.config("processInput function is not provided.");let u=e(),l=await i(a,s);return l=await ue(l,u,s),u.deploy(l,s)},list:async()=>(await t(),e().listDeployments()),get:async a=>(await t(),e().getDeployment(a)),set:async(a,c)=>(await t(),e().updateDeploymentLabels(a,c.labels)),remove:async a=>{await t(),await e().removeDeployment(a)}}}function me(n){let{getApi:e,ensureInit:t}=n;return{set:async(i,o={})=>(await t(),e().setDomain(i,o.deployment,o.labels)),list:async()=>(await t(),e().listDomains()),get:async i=>(await t(),e().getDomain(i)),remove:async i=>{await t(),await e().removeDomain(i)},verify:async i=>(await t(),e().verifyDomain(i)),validate:async i=>(await t(),e().validateDomain(i)),dns:async i=>(await t(),e().getDomainDns(i)),records:async i=>(await t(),e().getDomainRecords(i)),share:async i=>(await t(),e().getDomainShare(i))}}function de(n){let{getApi:e,ensureInit:t}=n;return{get:async()=>(await t(),e().getAccount())}}function he(n){let{getApi:e,ensureInit:t}=n;return{create:async(i={})=>(await t(),e().createToken(i.ttl,i.labels)),list:async()=>(await t(),e().listTokens()),remove:async i=>{await t(),await e().removeToken(i)}}}var M=class{constructor(e={}){this.initPromise=null;this._config=null;this.auth=null;this.clientOptions=e,e.deployToken?this.auth={type:"token",value:e.deployToken}:e.apiKey&&(this.auth={type:"apiKey",value:e.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(e);this.http=new R({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=fe({...i,processInput:(o,r)=>this.processInput(o,r),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=me(i),this._account=de(i),this._tokens=he(i)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}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=b(),this._config)}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}setDeployToken(e){if(!e||typeof e!="string")throw p.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw p.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};x();I();x();I();import{z as F}from"zod";var W="ship",Le=F.object({apiUrl:F.string().url().optional(),apiKey:F.string().optional(),deployToken:F.string().optional()}).strict();function ye(n){try{return Le.parse(n)}catch(e){if(e instanceof F.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw p.config(`Configuration validation failed${i}: ${t.message}`)}throw p.config("Configuration validation failed")}}async function _e(n){try{if(v()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(W,{searchPlaces:[`.${W}rc`,"package.json",`${t.homedir()}/.${W}rc`],stopDir:t.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return ye(o.config)}catch(e){if(T(e))throw e}return{}}async function J(n){if(v()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await _e(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return ye(i)}O();x();import ge from"mime-db";var X={};for(let n in ge){let e=ge[n];e&&e.extensions&&e.extensions.forEach(t=>{X[t]||(X[t]=n)})}function xe(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return X[e]||"application/octet-stream"}async function De(n,e,t){let{FormData:i,File:o}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),a=new i,c=[];for(let f of n){if(!Buffer.isBuffer(f.content)&&!(typeof Blob<"u"&&f.content instanceof Blob))throw p.file(`Unsupported file.content type for Node.js: ${f.path}`,f.path);if(!f.md5)throw p.file(`File missing md5 checksum: ${f.path}`,f.path);let d=xe(f.path),g=new o([f.content],f.path,{type:d});a.append("files[]",g),c.push(f.md5)}a.append("checksums",JSON.stringify(c)),e&&e.length>0&&a.append("labels",JSON.stringify(e)),t&&a.append("via",t);let s=new r(a),u=[];for await(let f of s.encode())u.push(Buffer.from(f));let l=Buffer.concat(u);return{body:l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength),headers:{"Content-Type":s.contentType,"Content-Length":Buffer.byteLength(l).toString()}}}_();function Gt(n,e,t,i=!0){let o=n===1?e:t;return i?`${n} ${o}`:o}Q();te();I();x();import Ke from"mime-db";var ve=Ke,je=new Set(Object.keys(ve)),ze=new Map(Object.entries(ve).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)]));function ne(n,e=1){if(n===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,o)).toFixed(e))+" "+i[o]}function He(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(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,i=n.split("/").pop()||n;return t.test(i)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function Ve(n,e){if(n.startsWith("."))return!0;let t=n.toLowerCase().split(".");if(t.length>1&&t[t.length-1]){let i=t[t.length-1],o=ze.get(e);if(o&&!o.has(i))return!1}return!0}function nn(n,e){let t=[],i=[],o=[];if(n.length===0){let s={file:"(no files)",message:"At least one file must be provided"};return t.push(s),{files:[],validFiles:[],errors:t,warnings:[],canDeploy:!1}}if(n.length>e.maxFilesCount){let s={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${e.maxFilesCount}`};return t.push(s),{files:n.map(u=>({...u,status:h.VALIDATION_FAILED,statusMessage:s.message})),validFiles:[],errors:t,warnings:[],canDeploy:!1}}let r=0;for(let s of n){let u=h.READY,l="Ready for upload",f=s.name?He(s.name):{valid:!1,reason:"File name cannot be empty"};if(s.status===h.PROCESSING_ERROR)u=h.VALIDATION_FAILED,l=s.statusMessage||"File failed during processing",t.push({file:s.name,message:l});else if(s.size===0){u=h.EXCLUDED,l="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:s.name,message:l}),o.push({...s,status:u,statusMessage:l});continue}else s.size<0?(u=h.VALIDATION_FAILED,l="File size must be positive",t.push({file:s.name,message:l})):!s.name||s.name.trim().length===0?(u=h.VALIDATION_FAILED,l="File name cannot be empty",t.push({file:s.name||"(empty)",message:l})):s.name.includes("\0")?(u=h.VALIDATION_FAILED,l="File name contains invalid characters (null byte)",t.push({file:s.name,message:l})):f.valid?!s.type||s.type.trim().length===0?(u=h.VALIDATION_FAILED,l="File MIME type is required",t.push({file:s.name,message:l})):pe(s.type)?!z.some(d=>s.type===d)&&!je.has(s.type)?(u=h.VALIDATION_FAILED,l=`Invalid MIME type "${s.type}"`,t.push({file:s.name,message:l})):Ve(s.name,s.type)?s.size>e.maxFileSize?(u=h.VALIDATION_FAILED,l=`File size (${ne(s.size)}) exceeds limit of ${ne(e.maxFileSize)}`,t.push({file:s.name,message:l})):(r+=s.size,r>e.maxTotalSize&&(u=h.VALIDATION_FAILED,l=`Total size would exceed limit of ${ne(e.maxTotalSize)}`,t.push({file:s.name,message:l}))):(u=h.VALIDATION_FAILED,l="File extension does not match MIME type",t.push({file:s.name,message:l})):(u=h.VALIDATION_FAILED,l=`File type "${s.type}" is not allowed`,t.push({file:s.name,message:l})):(u=h.VALIDATION_FAILED,l=f.reason||"Invalid file name",t.push({file:s.name,message:l}));o.push({...s,status:u,statusMessage:l})}t.length>0&&(o=o.map(s=>s.status===h.EXCLUDED?s:{...s,status:h.VALIDATION_FAILED,statusMessage:s.status===h.VALIDATION_FAILED?s.statusMessage:"Deployment failed due to validation errors in bundle"}));let a=t.length===0?o.filter(s=>s.status===h.READY):[],c=t.length===0;return{files:o,validFiles:a,errors:t,warnings:i,canDeploy:c}}function qe(n){return n.filter(e=>e.status===h.READY)}function on(n){return qe(n).length>0}ie();x();O();oe();var se=class extends M{constructor(e={}){if(v()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return G(e,{})}async loadFullConfig(){try{let e=await J(this.clientOptions.configFile),t=G(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let i=new R({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();q(o)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){let i=typeof e=="string"?[e]:e;if(!Array.isArray(i)||!i.every(r=>typeof r=="string"))throw p.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw p.business("No files to deploy.");let{processFilesForNode:o}=await Promise.resolve().then(()=>(oe(),Re));return o(i,t)}getDeployBodyCreator(){return De}},Ge=se;export{z as ALLOWED_MIME_TYPES,K as API_KEY_HEX_LENGTH,Qe as API_KEY_HINT_LENGTH,C as API_KEY_PREFIX,re as API_KEY_TOTAL_LENGTH,Xe as AccountPlan,R as ApiHttp,Ze as AuthMethod,N as DEFAULT_API,H as DEPLOYMENT_CONFIG_FILENAME,j as DEPLOY_TOKEN_HEX_LENGTH,w as DEPLOY_TOKEN_PREFIX,ae as DEPLOY_TOKEN_TOTAL_LENGTH,We as DeploymentStatus,Je as DomainStatus,m as ErrorType,h as FILE_VALIDATION_STATUS,h as FileValidationStatus,Ue as JUNK_DIRECTORIES,pt as LABEL_CONSTRAINTS,lt as LABEL_PATTERN,se as Ship,p as ShipError,St as __setTestEnvironment,on as allValidFilesReady,L as calculateMD5,de as createAccountResource,fe as createDeploymentResource,me as createDomainResource,he as createTokenResource,Ge as default,ut as deserializeLabels,st as extractSubdomain,Ee as filterJunk,ne as formatFileSize,rt as generateDeploymentUrl,at as generateDomainUrl,b as getCurrentConfig,v as getENV,xe as getMimeType,qe as getValidFiles,pe as isAllowedMimeType,ot as isCustomDomain,it as isDeployment,le as isPlatformDomain,T as isShipError,J as loadConfig,ce as mergeDeployOptions,Ae as optimizeDeployPaths,Gt as pluralize,we as processFilesForNode,G as resolveConfig,ct as serializeLabels,q as setPlatformConfig,et as validateApiKey,nt as validateApiUrl,Te as validateDeployPath,tt as validateDeployToken,nn as validateFiles};
2
2
  //# sourceMappingURL=index.js.map