@shipstatic/ship 0.4.20 → 0.4.21

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.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Le=Object.create;var _=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var ze=Object.getPrototypeOf,Ke=Object.prototype.hasOwnProperty;var C=(n,e)=>()=>(n&&(e=n(n=0)),e);var xe=(n,e)=>{for(var t in e)_(n,t,{get:e[t],enumerable:!0})},Te=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Be(e))!Ke.call(n,r)&&r!==t&&_(n,r,{get:()=>e[r],enumerable:!(i=Ue(e,r))||i.enumerable});return n};var S=(n,e,t)=>(t=n!=null?Le(ze(n)):{},Te(e||!n||!n.__esModule?_(t,"default",{value:n,enumerable:!0}):t,n)),je=n=>Te(_({},"__esModule",{value:!0}),n);function R(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function ee(n){return B.some(e=>n===e||n.startsWith(e))}function Ye(n){if(!n.startsWith(w))throw p.validation(`API key must start with "${w}"`);if(n.length!==Q)throw p.validation(`API key must be ${Q} characters total (${w} + ${L} hex chars)`);let e=n.slice(w.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`API key must contain ${L} hexadecimal characters after "${w}" prefix`)}function We(n){if(!n.startsWith(P))throw p.validation(`Deploy token must start with "${P}"`);if(n.length!==Z)throw p.validation(`Deploy token must be ${Z} characters total (${P} + ${U} hex chars)`);let e=n.slice(P.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`Deploy token must contain ${U} hexadecimal characters after "${P}" prefix`)}function Je(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 R(e)?e:p.validation("API URL must be a valid URL")}}function Xe(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(n)}function te(n,e){return n.endsWith(`.${e}`)}function Qe(n,e){return!te(n,e)}function Ze(n,e){return te(n,e)?n.slice(0,-(e.length+1)):null}function et(n,e){return`https://${n}.${e||"shipstatic.com"}`}function tt(n){return`https://${n}`}function ot(n){return!n||n.length===0?null:JSON.stringify(n)}function rt(n){if(n)try{let e=JSON.parse(n);return Array.isArray(e)&&e.length>0?e:void 0}catch{return}}var He,Ge,Ve,u,X,p,B,w,L,Q,P,U,Z,qe,z,N,d,nt,it,E=C(()=>{"use strict";He={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Ge={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Ve={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"})(u||(u={}));X={client:new Set([u.Business,u.Config,u.File,u.Validation]),network:new Set([u.Network]),auth:new Set([u.Authentication])},p=class n extends Error{type;status;details;constructor(e,t,i,r){super(t),this.type=e,this.status=i,this.details=r,this.name="ShipError"}toResponse(){let e=this.type===u.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(u.Validation,e,400,t)}static notFound(e,t){let i=t?`${e} ${t} not found`:`${e} not found`;return new n(u.NotFound,i,404)}static rateLimit(e="Too many requests"){return new n(u.RateLimit,e,429)}static authentication(e="Authentication required",t){return new n(u.Authentication,e,401,t)}static business(e,t=400){return new n(u.Business,e,t)}static network(e,t){return new n(u.Network,e,void 0,{cause:t})}static cancelled(e){return new n(u.Cancelled,e)}static file(e,t){return new n(u.File,e,void 0,{filePath:t})}static config(e,t){return new n(u.Config,e,void 0,t)}static api(e,t=500){return new n(u.Api,e,t)}static database(e,t=500){return new n(u.Api,e,t)}static storage(e,t=500){return new n(u.Api,e,t)}get filePath(){return this.details?.filePath}isClientError(){return X.client.has(this.type)}isNetworkError(){return X.network.has(this.type)}isAuthError(){return X.auth.has(this.type)}isValidationError(){return this.type===u.Validation}isFileError(){return this.type===u.File}isConfigError(){return this.type===u.Config}isType(e){return this.type===e}};B=["text/html","text/css","text/plain","text/markdown","text/xml","text/csv","text/yaml","text/vtt","text/calendar","text/javascript","text/typescript","text/tsx","text/jsx","text/x-scss","text/x-sass","text/x-less","text/stylus","text/x-vue","text/x-svelte","image/","audio/","video/","font/","application/javascript","application/ecmascript","application/x-javascript","application/wasm","application/json","application/ld+json","application/manifest+json","application/source-map","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/yaml","application/pdf","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"];w="ship-",L=64,Q=w.length+L,P="token-",U=64,Z=P.length+U,qe={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},z="ship.json";N="https://api.shipstatic.com",d={PENDING:"pending",PROCESSING_ERROR:"processing_error",EMPTY_FILE:"empty_file",VALIDATION_FAILED:"validation_failed",READY:"ready"};nt={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},it=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function j(n){ne=n}function O(){if(ne===null)throw p.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ne}var ne,k=C(()=>{"use strict";E();ne=null});function Ae(n){ie=n}function at(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function x(){return ie||at()}var ie,F=C(()=>{"use strict";ie=null});async function pt(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let o=Math.ceil(n.size/2097152),s=0,a=new e.ArrayBuffer,l=new FileReader,y=()=>{let g=s*2097152,c=Math.min(g+2097152,n.size);l.readAsArrayBuffer(n.slice(g,c))};l.onload=g=>{let c=g.target?.result;if(!c){i(p.business("Failed to read file chunk"));return}a.append(c),s++,s<o?y():t({md5:a.end()})},l.onerror=()=>{i(p.business("Failed to calculate MD5: FileReader error"))},y()})}async function lt(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,r)=>{let o=e.createHash("md5"),s=t.createReadStream(n);s.on("error",a=>r(p.business(`Failed to read file for MD5: ${a.message}`))),s.on("data",a=>o.update(a)),s.on("end",()=>i({md5:o.digest("hex")}))})}async function M(n){let e=x();if(e==="browser"){if(!(n instanceof Blob))throw p.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return pt(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 lt(n)}throw p.business("Unknown or unsupported execution environment for MD5 calculation.")}var G=C(()=>{"use strict";F();E()});function Ce(n){try{return ut.parse(n)}catch(e){if(e instanceof $.z.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 ft(n){try{if(x()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(le,{searchPlaces:[`.${le}rc`,"package.json",`${t.homedir()}/.${le}rc`],stopDir:t.homedir()}),r;if(n?r=i.load(n):r=i.search(),r&&r.config)return Ce(r.config)}catch(e){if(R(e))throw e}return{}}async function q(n){if(x()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await ft(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Ce(i)}var $,le,ut,ce=C(()=>{"use strict";$=require("zod");E();F();le="ship",ut=$.z.object({apiUrl:$.z.string().url().optional(),apiKey:$.z.string().optional(),deployToken:$.z.string().optional()}).strict()});function de(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((0,Pe.isJunk)(i))return!1;let r=t.slice(0,-1);for(let o of r)if(Ie.some(s=>o.toLowerCase()===s.toLowerCase()))return!1;return!0})}var Pe,Ie,me=C(()=>{"use strict";Pe=require("junk"),Ie=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Fe(n){if(!n||n.length===0)return"";let e=n.filter(o=>o&&typeof o=="string").map(o=>o.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(o=>o.split("/").filter(Boolean)),i=[],r=Math.min(...t.map(o=>o.length));for(let o=0;o<r;o++){let s=t[0][o];if(t.every(a=>a[o]===s))i.push(s);else break}return i.join("/")}function Y(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var he=C(()=>{"use strict"});function ge(n,e={}){if(e.flatten===!1)return n.map(i=>({path:Y(i),name:ye(i)}));let t=mt(n);return n.map(i=>{let r=Y(i);if(t){let o=t.endsWith("/")?t:`${t}/`;r.startsWith(o)&&(r=r.substring(o.length))}return r||(r=ye(i)),{path:r,name:ye(i)}})}function mt(n){if(!n.length)return"";let t=n.map(o=>Y(o)).map(o=>o.split("/")),i=[],r=Math.min(...t.map(o=>o.length));for(let o=0;o<r-1;o++){let s=t[0][o];if(t.every(a=>a[o]===s))i.push(s);else break}return i.join("/")}function ye(n){return n.split(/[/\\]/).pop()||n}var Ee=C(()=>{"use strict";he()});var ke={};xe(ke,{processFilesForNode:()=>De});function Ne(n,e=new Set){let t=[],i=T.realpathSync(n);if(e.has(i))return t;e.add(i);let r=T.readdirSync(n);for(let o of r){let s=D.join(n,o),a=T.statSync(s);if(a.isDirectory()){let l=Ne(s,e);t.push(...l)}else a.isFile()&&t.push(s)}return t}async function De(n,e={}){if(x()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(m=>{let h=D.resolve(m);try{return T.statSync(h).isDirectory()?Ne(h):[h]}catch{throw p.file(`Path does not exist: ${m}`,m)}}),i=[...new Set(t)],r=de(i);if(r.length===0)return[];let o=n.map(m=>D.resolve(m)),s=Fe(o.map(m=>{try{return T.statSync(m).isDirectory()?m:D.dirname(m)}catch{return D.dirname(m)}})),a=r.map(m=>{if(s&&s.length>0){let h=D.relative(s,m);if(h&&typeof h=="string"&&!h.startsWith(".."))return h.replace(/\\/g,"/")}return D.basename(m)}),l=ge(a,{flatten:e.pathDetect!==!1}),y=[],g=0,c=O();for(let m=0;m<r.length;m++){let h=r[m],A=l[m].path;try{let v=T.statSync(h);if(v.size===0)continue;if(v.size>c.maxFileSize)throw p.business(`File ${h} is too large. Maximum allowed size is ${c.maxFileSize/(1024*1024)}MB.`);if(g+=v.size,g>c.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${c.maxTotalSize/(1024*1024)}MB.`);let b=T.readFileSync(h),{md5:_e}=await M(b);if(A.includes("\0")||A.includes("/../")||A.startsWith("../")||A.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${A}" for file: ${h}`);y.push({path:A,content:b,size:b.length,md5:_e})}catch(v){if(R(v))throw v;let b=v instanceof Error?v.message:String(v);throw p.file(`Failed to read file "${h}": ${b}`,h)}}if(y.length>c.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return y}var T,D,Se=C(()=>{"use strict";F();G();me();E();k();Ee();he();T=S(require("fs"),1),D=S(require("path"),1)});var At={};xe(At,{ALLOWED_MIME_TYPES:()=>B,API_KEY_HEX_LENGTH:()=>L,API_KEY_PREFIX:()=>w,API_KEY_TOTAL_LENGTH:()=>Q,AccountPlan:()=>Ve,ApiHttp:()=>I,AuthMethod:()=>qe,DEFAULT_API:()=>N,DEPLOYMENT_CONFIG_FILENAME:()=>z,DEPLOY_TOKEN_HEX_LENGTH:()=>U,DEPLOY_TOKEN_PREFIX:()=>P,DEPLOY_TOKEN_TOTAL_LENGTH:()=>Z,DeploymentStatus:()=>He,DomainStatus:()=>Ge,ErrorType:()=>u,FILE_VALIDATION_STATUS:()=>d,FileValidationStatus:()=>d,JUNK_DIRECTORIES:()=>Ie,Ship:()=>J,ShipError:()=>p,TAG_CONSTRAINTS:()=>nt,TAG_PATTERN:()=>it,__setTestEnvironment:()=>Ae,allValidFilesReady:()=>Tt,calculateMD5:()=>M,createAccountResource:()=>ae,createDeploymentResource:()=>re,createDomainResource:()=>se,createTokenResource:()=>pe,default:()=>Me,deserializeTags:()=>rt,extractSubdomain:()=>Ze,filterJunk:()=>de,formatFileSize:()=>W,generateDeploymentUrl:()=>et,generateDomainUrl:()=>tt,getCurrentConfig:()=>O,getENV:()=>x,getValidFiles:()=>be,isAllowedMimeType:()=>ee,isCustomDomain:()=>Qe,isDeployment:()=>Xe,isPlatformDomain:()=>te,isShipError:()=>R,loadConfig:()=>q,mergeDeployOptions:()=>oe,optimizeDeployPaths:()=>ge,pluralize:()=>dt,processFilesForNode:()=>De,resolveConfig:()=>H,serializeTags:()=>ot,setPlatformConfig:()=>j,validateApiKey:()=>Ye,validateApiUrl:()=>Je,validateDeployToken:()=>We,validateFiles:()=>xt});module.exports=je(At);E();var K=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 r=Array.from(i);for(let o of r)try{o(...t)}catch(s){i.delete(o),e!=="error"&&setTimeout(()=>{s instanceof Error?this.emit("error",s,String(e)):this.emit("error",new Error(String(s)),String(e))},0)}}transfer(e){this.handlers.forEach((t,i)=>{t.forEach(r=>{e.on(i,r)})})}clear(){this.handlers.clear()}};var f={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},st=3e4,I=class extends K{constructor(e){super(),this.apiUrl=e.apiUrl||N,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??st,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,t,i){let r=this.mergeHeaders(t.headers),{signal:o,cleanup:s}=this.createTimeoutSignal(t.signal),a={...t,headers:r,credentials:r.Authorization?void 0:"include",signal:o};this.emit("request",e,a);try{let l=await fetch(e,a);return s(),l.ok||await this.handleResponseError(l,i),this.emit("response",this.safeClone(l),e),{data:await this.parseResponse(this.safeClone(l)),status:l.status}}catch(l){s();let y=l instanceof Error?l:new Error(String(l));this.emit("error",y,e),this.handleFetchError(l,i)}}async request(e,t,i){let{data:r}=await this.executeRequest(e,t,i);return r}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 r=()=>t.abort();e.addEventListener("abort",r),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 s=await e.json();if(s&&typeof s=="object"){let a=s;typeof a.message=="string"&&(i.message=a.message),typeof a.error=="string"&&(i.error=a.error)}}else i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let r=i.message||i.error||`${t} failed`;throw e.status===401?p.authentication(r):p.api(r,e.status)}handleFetchError(e,t){throw R(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 s of e)if(!s.md5)throw p.file(`MD5 checksum missing for file: ${s.path}`,s.path);let{body:i,headers:r}=await this.createDeployBody(e,t.tags,t.via),o={};return t.deployToken?o.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(o.Authorization=`Bearer ${t.apiKey}`),t.caller&&(o["X-Caller"]=t.caller),this.request(`${t.apiUrl||this.apiUrl}${f.DEPLOYMENTS}`,{method:"POST",body:i,headers:{...r,...o},signal:t.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentTags(e,t){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:t})},"Update deployment tags")}async removeDeployment(e){await this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,t,i){let r={};t&&(r.deployment=t),i!==void 0&&(r.tags=i);let{data:o,status:s}=await this.requestWithStatus(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"Set domain");return{...o,isCreate:s===201}}async listDomains(){return this.request(`${this.apiUrl}${f.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async updateDomainTags(e,t){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:t})},"Update domain tags")}async removeDomain(e){await this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,t){let i={};return e!==void 0&&(i.ttl=e),t!==void 0&&(i.tags=t),this.request(`${this.apiUrl}${f.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${f.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${f.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${f.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${f.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${f.PING}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return this.request(`${this.apiUrl}${f.PING}`,{method:"GET"},"Ping")}async checkSPA(e){let t=e.find(s=>s.path==="index.html"||s.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 r={files:e.map(s=>s.path),index:i};return(await this.request(`${this.apiUrl}${f.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"SPA check")).isSPA}};E();k();E();E();function H(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 oe(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}E();G();async function ct(){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 M(t);return{path:z,content:t,size:e.length,md5:i}}async function ve(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===z))return n;try{if(await e.checkSPA(n)){let r=await ct();return[...n,r]}}catch{}return n}function re(n){let{getApi:e,ensureInit:t,processInput:i,clientDefaults:r,hasAuth:o}=n;return{create:async(s,a={})=>{await t();let l=r?oe(a,r):a;if(o&&!o()&&!l.deployToken&&!l.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 y=e(),g=await i(s,l);return g=await ve(g,y,l),y.deploy(g,l)},list:async()=>(await t(),e().listDeployments()),get:async s=>(await t(),e().getDeployment(s)),set:async(s,a)=>(await t(),e().updateDeploymentTags(s,a.tags)),remove:async s=>{await t(),await e().removeDeployment(s)}}}function se(n){let{getApi:e,ensureInit:t}=n;return{set:async(i,r={})=>{await t();let{deployment:o,tags:s}=r;return o===void 0&&s&&s.length>0?e().updateDomainTags(i,s):e().setDomain(i,o,s)},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 ae(n){let{getApi:e,ensureInit:t}=n;return{get:async()=>(await t(),e().getAccount())}}function pe(n){let{getApi:e,ensureInit:t}=n;return{create:async(i={})=>(await t(),e().createToken(i.ttl,i.tags)),list:async()=>(await t(),e().listTokens()),remove:async i=>{await t(),await e().removeToken(i)}}}var V=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 I({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=re({...i,processInput:(r,o)=>this.processInput(r,o),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=se(i),this._account=ae(i),this._tokens=pe(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}};E();F();ce();k();E();var ue=S(require("mime-db"),1),fe={};for(let n in ue.default){let e=ue.default[n];e&&e.extensions&&e.extensions.forEach(t=>{fe[t]||(fe[t]=n)})}function Re(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return fe[e]||"application/octet-stream"}async function we(n,e,t){let{FormData:i,File:r}=await import("formdata-node"),{FormDataEncoder:o}=await import("form-data-encoder"),s=new i,a=[];for(let c of n){let m=Re(c.path),h;if(Buffer.isBuffer(c.content))h=new r([c.content],c.path,{type:m});else if(typeof Blob<"u"&&c.content instanceof Blob)h=new r([c.content],c.path,{type:m});else throw p.file(`Unsupported file.content type for Node.js: ${c.path}`,c.path);if(!c.md5)throw p.file(`File missing md5 checksum: ${c.path}`,c.path);let A=c.path.startsWith("/")?c.path:"/"+c.path;s.append("files[]",h,A),a.push(c.md5)}s.append("checksums",JSON.stringify(a)),e&&e.length>0&&s.append("tags",JSON.stringify(e)),t&&s.append("via",t);let l=new o(s),y=[];for await(let c of l.encode())y.push(Buffer.from(c));let g=Buffer.concat(y);return{body:g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength),headers:{"Content-Type":l.contentType,"Content-Length":Buffer.byteLength(g).toString()}}}G();function dt(n,e,t,i=!0){let r=n===1?e:t;return i?`${n} ${r}`:r}me();Ee();F();E();var Oe=S(require("mime-db"),1),$e=Oe.default,ht=new Set(Object.keys($e)),yt=new Map(Object.entries($e).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)]));var gt=[[/File name cannot|Invalid file name|File name contains|File name uses|traversal/i,"Invalid File Name"],[/File size must be positive/i,"Invalid File Size"],[/MIME type is required/i,"Missing MIME Type"],[/Invalid MIME type/i,"Invalid MIME Type"],[/not allowed/i,"Invalid File Type"],[/extension does not match/i,"Extension Mismatch"],[/Total size/i,"Total Size Exceeded"],[/exceeds limit/i,"File Too Large"]];function Et(n,e){if(n===d.PROCESSING_ERROR)return"Processing Error";if(n===d.EMPTY_FILE)return"Empty File";if(!e)return"Validation Failed";for(let[t,i]of gt)if(t.test(e))return i;return"Validation Failed"}function W(n,e=1){if(n===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,r)).toFixed(e))+" "+i[r]}function Dt(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 St(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],r=yt.get(e);if(r&&!r.has(i))return!1}return!0}function xt(n,e){let t=[],i=[];if(n.length===0){let o="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:o,errors:[o],isClientError:!0}}}if(n.length>e.maxFilesCount){let o=`Number of files (${n.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:n.map(s=>({...s,status:d.VALIDATION_FAILED,statusMessage:o})),validFiles:[],error:{error:"File Count Exceeded",details:o,errors:[o],isClientError:!0}}}let r=0;for(let o of n){let s=d.READY,a="Ready for upload",l=o.name?Dt(o.name):{valid:!1,reason:"File name cannot be empty"};o.status===d.PROCESSING_ERROR?(s=d.PROCESSING_ERROR,a=o.statusMessage||"A file failed during processing.",t.push(`${o.name}: ${a}`)):!o.name||o.name.trim().length===0?(s=d.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${o.name||"(empty)"}: ${a}`)):o.name.includes("\0")?(s=d.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push(`${o.name}: ${a}`)):l.valid?o.size<=0?(s=d.EMPTY_FILE,a=o.size===0?"File is empty (0 bytes)":"File size must be positive",t.push(`${o.name}: ${a}`)):!o.type||o.type.trim().length===0?(s=d.VALIDATION_FAILED,a="File MIME type is required",t.push(`${o.name}: ${a}`)):ee(o.type)?!B.some(y=>o.type===y)&&!ht.has(o.type)?(s=d.VALIDATION_FAILED,a=`Invalid MIME type "${o.type}"`,t.push(`${o.name}: ${a}`)):St(o.name,o.type)?o.size>e.maxFileSize?(s=d.VALIDATION_FAILED,a=`File size (${W(o.size)}) exceeds limit of ${W(e.maxFileSize)}`,t.push(`${o.name}: ${a}`)):(r+=o.size,r>e.maxTotalSize&&(s=d.VALIDATION_FAILED,a=`Total size would exceed limit of ${W(e.maxTotalSize)}`,t.push(`${o.name}: ${a}`))):(s=d.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${o.name}: ${a}`)):(s=d.VALIDATION_FAILED,a=`File type "${o.type}" is not allowed`,t.push(`${o.name}: ${a}`)):(s=d.VALIDATION_FAILED,a=l.reason||"Invalid file name",t.push(`${o.name}: ${a}`)),i.push({...o,status:s,statusMessage:a})}if(t.length>0){let o=i.find(a=>a.status!==d.READY&&a.status!==d.PENDING),s=Et(o?.status,o?.statusMessage);return{files:i.map(a=>({...a,status:d.VALIDATION_FAILED})),validFiles:[],error:{error:s,details:t.length===1?t[0]:`${t.length} file(s) failed validation`,errors:t,isClientError:!0}}}return{files:i,validFiles:i,error:null}}function be(n){return n.filter(e=>e.status===d.READY)}function Tt(n){return be(n).length>0}E();ce();k();Se();F();var J=class extends V{constructor(e={}){if(x()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return H(e,{})}async loadFullConfig(){try{let e=await q(this.clientOptions.configFile),t=H(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let i=new I({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let r=await this.http.getConfig();j(r)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){let i=typeof e=="string"?[e]:e;if(!Array.isArray(i)||!i.every(o=>typeof o=="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:r}=await Promise.resolve().then(()=>(Se(),ke));return r(i,t)}getDeployBodyCreator(){return we}},Me=J;0&&(module.exports={ALLOWED_MIME_TYPES,API_KEY_HEX_LENGTH,API_KEY_PREFIX,API_KEY_TOTAL_LENGTH,AccountPlan,ApiHttp,AuthMethod,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_TOKEN_HEX_LENGTH,DEPLOY_TOKEN_PREFIX,DEPLOY_TOKEN_TOTAL_LENGTH,DeploymentStatus,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,JUNK_DIRECTORIES,Ship,ShipError,TAG_CONSTRAINTS,TAG_PATTERN,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeTags,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getCurrentConfig,getENV,getValidFiles,isAllowedMimeType,isCustomDomain,isDeployment,isPlatformDomain,isShipError,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,serializeTags,setPlatformConfig,validateApiKey,validateApiUrl,validateDeployToken,validateFiles});
1
+ "use strict";var Le=Object.create;var _=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var ze=Object.getPrototypeOf,Ke=Object.prototype.hasOwnProperty;var C=(n,e)=>()=>(n&&(e=n(n=0)),e);var xe=(n,e)=>{for(var t in e)_(n,t,{get:e[t],enumerable:!0})},Te=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Be(e))!Ke.call(n,r)&&r!==t&&_(n,r,{get:()=>e[r],enumerable:!(i=Ue(e,r))||i.enumerable});return n};var S=(n,e,t)=>(t=n!=null?Le(ze(n)):{},Te(e||!n||!n.__esModule?_(t,"default",{value:n,enumerable:!0}):t,n)),je=n=>Te(_({},"__esModule",{value:!0}),n);function R(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function ee(n){return B.some(e=>n===e||n.startsWith(e))}function Ye(n){if(!n.startsWith(w))throw p.validation(`API key must start with "${w}"`);if(n.length!==Q)throw p.validation(`API key must be ${Q} characters total (${w} + ${L} hex chars)`);let e=n.slice(w.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`API key must contain ${L} hexadecimal characters after "${w}" prefix`)}function We(n){if(!n.startsWith(P))throw p.validation(`Deploy token must start with "${P}"`);if(n.length!==Z)throw p.validation(`Deploy token must be ${Z} characters total (${P} + ${U} hex chars)`);let e=n.slice(P.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`Deploy token must contain ${U} hexadecimal characters after "${P}" prefix`)}function Je(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 R(e)?e:p.validation("API URL must be a valid URL")}}function Xe(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(n)}function te(n,e){return n.endsWith(`.${e}`)}function Qe(n,e){return!te(n,e)}function Ze(n,e){return te(n,e)?n.slice(0,-(e.length+1)):null}function et(n,e){return`https://${n}.${e||"shipstatic.com"}`}function tt(n){return`https://${n}`}function ot(n){return!n||n.length===0?null:JSON.stringify(n)}function rt(n){if(n)try{let e=JSON.parse(n);return Array.isArray(e)&&e.length>0?e:void 0}catch{return}}var He,Ge,Ve,u,X,p,B,w,L,Q,P,U,Z,qe,z,N,d,nt,it,E=C(()=>{"use strict";He={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Ge={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Ve={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"})(u||(u={}));X={client:new Set([u.Business,u.Config,u.File,u.Validation]),network:new Set([u.Network]),auth:new Set([u.Authentication])},p=class n extends Error{type;status;details;constructor(e,t,i,r){super(t),this.type=e,this.status=i,this.details=r,this.name="ShipError"}toResponse(){let e=this.type===u.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(u.Validation,e,400,t)}static notFound(e,t){let i=t?`${e} ${t} not found`:`${e} not found`;return new n(u.NotFound,i,404)}static rateLimit(e="Too many requests"){return new n(u.RateLimit,e,429)}static authentication(e="Authentication required",t){return new n(u.Authentication,e,401,t)}static business(e,t=400){return new n(u.Business,e,t)}static network(e,t){return new n(u.Network,e,void 0,{cause:t})}static cancelled(e){return new n(u.Cancelled,e)}static file(e,t){return new n(u.File,e,void 0,{filePath:t})}static config(e,t){return new n(u.Config,e,void 0,t)}static api(e,t=500){return new n(u.Api,e,t)}static database(e,t=500){return new n(u.Api,e,t)}static storage(e,t=500){return new n(u.Api,e,t)}get filePath(){return this.details?.filePath}isClientError(){return X.client.has(this.type)}isNetworkError(){return X.network.has(this.type)}isAuthError(){return X.auth.has(this.type)}isValidationError(){return this.type===u.Validation}isFileError(){return this.type===u.File}isConfigError(){return this.type===u.Config}isType(e){return this.type===e}};B=["text/html","text/css","text/plain","text/markdown","text/xml","text/csv","text/yaml","text/vtt","text/calendar","text/javascript","text/typescript","text/tsx","text/jsx","text/x-scss","text/x-sass","text/x-less","text/stylus","text/x-vue","text/x-svelte","image/","audio/","video/","font/","application/javascript","application/ecmascript","application/x-javascript","application/wasm","application/json","application/ld+json","application/manifest+json","application/source-map","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/yaml","application/toml","application/pdf","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"];w="ship-",L=64,Q=w.length+L,P="token-",U=64,Z=P.length+U,qe={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},z="ship.json";N="https://api.shipstatic.com",d={PENDING:"pending",PROCESSING_ERROR:"processing_error",EMPTY_FILE:"empty_file",VALIDATION_FAILED:"validation_failed",READY:"ready"};nt={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},it=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function j(n){ne=n}function O(){if(ne===null)throw p.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ne}var ne,k=C(()=>{"use strict";E();ne=null});function Ae(n){ie=n}function at(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function x(){return ie||at()}var ie,F=C(()=>{"use strict";ie=null});async function pt(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let o=Math.ceil(n.size/2097152),s=0,a=new e.ArrayBuffer,l=new FileReader,y=()=>{let g=s*2097152,c=Math.min(g+2097152,n.size);l.readAsArrayBuffer(n.slice(g,c))};l.onload=g=>{let c=g.target?.result;if(!c){i(p.business("Failed to read file chunk"));return}a.append(c),s++,s<o?y():t({md5:a.end()})},l.onerror=()=>{i(p.business("Failed to calculate MD5: FileReader error"))},y()})}async function lt(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,r)=>{let o=e.createHash("md5"),s=t.createReadStream(n);s.on("error",a=>r(p.business(`Failed to read file for MD5: ${a.message}`))),s.on("data",a=>o.update(a)),s.on("end",()=>i({md5:o.digest("hex")}))})}async function M(n){let e=x();if(e==="browser"){if(!(n instanceof Blob))throw p.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return pt(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 lt(n)}throw p.business("Unknown or unsupported execution environment for MD5 calculation.")}var G=C(()=>{"use strict";F();E()});function Ce(n){try{return ut.parse(n)}catch(e){if(e instanceof $.z.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 ft(n){try{if(x()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(le,{searchPlaces:[`.${le}rc`,"package.json",`${t.homedir()}/.${le}rc`],stopDir:t.homedir()}),r;if(n?r=i.load(n):r=i.search(),r&&r.config)return Ce(r.config)}catch(e){if(R(e))throw e}return{}}async function q(n){if(x()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await ft(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Ce(i)}var $,le,ut,ce=C(()=>{"use strict";$=require("zod");E();F();le="ship",ut=$.z.object({apiUrl:$.z.string().url().optional(),apiKey:$.z.string().optional(),deployToken:$.z.string().optional()}).strict()});function de(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((0,Pe.isJunk)(i))return!1;let r=t.slice(0,-1);for(let o of r)if(Ie.some(s=>o.toLowerCase()===s.toLowerCase()))return!1;return!0})}var Pe,Ie,me=C(()=>{"use strict";Pe=require("junk"),Ie=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Fe(n){if(!n||n.length===0)return"";let e=n.filter(o=>o&&typeof o=="string").map(o=>o.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(o=>o.split("/").filter(Boolean)),i=[],r=Math.min(...t.map(o=>o.length));for(let o=0;o<r;o++){let s=t[0][o];if(t.every(a=>a[o]===s))i.push(s);else break}return i.join("/")}function Y(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var he=C(()=>{"use strict"});function ge(n,e={}){if(e.flatten===!1)return n.map(i=>({path:Y(i),name:ye(i)}));let t=mt(n);return n.map(i=>{let r=Y(i);if(t){let o=t.endsWith("/")?t:`${t}/`;r.startsWith(o)&&(r=r.substring(o.length))}return r||(r=ye(i)),{path:r,name:ye(i)}})}function mt(n){if(!n.length)return"";let t=n.map(o=>Y(o)).map(o=>o.split("/")),i=[],r=Math.min(...t.map(o=>o.length));for(let o=0;o<r-1;o++){let s=t[0][o];if(t.every(a=>a[o]===s))i.push(s);else break}return i.join("/")}function ye(n){return n.split(/[/\\]/).pop()||n}var Ee=C(()=>{"use strict";he()});var ke={};xe(ke,{processFilesForNode:()=>De});function Ne(n,e=new Set){let t=[],i=T.realpathSync(n);if(e.has(i))return t;e.add(i);let r=T.readdirSync(n);for(let o of r){let s=D.join(n,o),a=T.statSync(s);if(a.isDirectory()){let l=Ne(s,e);t.push(...l)}else a.isFile()&&t.push(s)}return t}async function De(n,e={}){if(x()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(m=>{let h=D.resolve(m);try{return T.statSync(h).isDirectory()?Ne(h):[h]}catch{throw p.file(`Path does not exist: ${m}`,m)}}),i=[...new Set(t)],r=de(i);if(r.length===0)return[];let o=n.map(m=>D.resolve(m)),s=Fe(o.map(m=>{try{return T.statSync(m).isDirectory()?m:D.dirname(m)}catch{return D.dirname(m)}})),a=r.map(m=>{if(s&&s.length>0){let h=D.relative(s,m);if(h&&typeof h=="string"&&!h.startsWith(".."))return h.replace(/\\/g,"/")}return D.basename(m)}),l=ge(a,{flatten:e.pathDetect!==!1}),y=[],g=0,c=O();for(let m=0;m<r.length;m++){let h=r[m],A=l[m].path;try{let v=T.statSync(h);if(v.size===0)continue;if(v.size>c.maxFileSize)throw p.business(`File ${h} is too large. Maximum allowed size is ${c.maxFileSize/(1024*1024)}MB.`);if(g+=v.size,g>c.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${c.maxTotalSize/(1024*1024)}MB.`);let b=T.readFileSync(h),{md5:_e}=await M(b);if(A.includes("\0")||A.includes("/../")||A.startsWith("../")||A.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${A}" for file: ${h}`);y.push({path:A,content:b,size:b.length,md5:_e})}catch(v){if(R(v))throw v;let b=v instanceof Error?v.message:String(v);throw p.file(`Failed to read file "${h}": ${b}`,h)}}if(y.length>c.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return y}var T,D,Se=C(()=>{"use strict";F();G();me();E();k();Ee();he();T=S(require("fs"),1),D=S(require("path"),1)});var At={};xe(At,{ALLOWED_MIME_TYPES:()=>B,API_KEY_HEX_LENGTH:()=>L,API_KEY_PREFIX:()=>w,API_KEY_TOTAL_LENGTH:()=>Q,AccountPlan:()=>Ve,ApiHttp:()=>I,AuthMethod:()=>qe,DEFAULT_API:()=>N,DEPLOYMENT_CONFIG_FILENAME:()=>z,DEPLOY_TOKEN_HEX_LENGTH:()=>U,DEPLOY_TOKEN_PREFIX:()=>P,DEPLOY_TOKEN_TOTAL_LENGTH:()=>Z,DeploymentStatus:()=>He,DomainStatus:()=>Ge,ErrorType:()=>u,FILE_VALIDATION_STATUS:()=>d,FileValidationStatus:()=>d,JUNK_DIRECTORIES:()=>Ie,Ship:()=>J,ShipError:()=>p,TAG_CONSTRAINTS:()=>nt,TAG_PATTERN:()=>it,__setTestEnvironment:()=>Ae,allValidFilesReady:()=>Tt,calculateMD5:()=>M,createAccountResource:()=>ae,createDeploymentResource:()=>re,createDomainResource:()=>se,createTokenResource:()=>pe,default:()=>Me,deserializeTags:()=>rt,extractSubdomain:()=>Ze,filterJunk:()=>de,formatFileSize:()=>W,generateDeploymentUrl:()=>et,generateDomainUrl:()=>tt,getCurrentConfig:()=>O,getENV:()=>x,getValidFiles:()=>be,isAllowedMimeType:()=>ee,isCustomDomain:()=>Qe,isDeployment:()=>Xe,isPlatformDomain:()=>te,isShipError:()=>R,loadConfig:()=>q,mergeDeployOptions:()=>oe,optimizeDeployPaths:()=>ge,pluralize:()=>dt,processFilesForNode:()=>De,resolveConfig:()=>H,serializeTags:()=>ot,setPlatformConfig:()=>j,validateApiKey:()=>Ye,validateApiUrl:()=>Je,validateDeployToken:()=>We,validateFiles:()=>xt});module.exports=je(At);E();var K=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 r=Array.from(i);for(let o of r)try{o(...t)}catch(s){i.delete(o),e!=="error"&&setTimeout(()=>{s instanceof Error?this.emit("error",s,String(e)):this.emit("error",new Error(String(s)),String(e))},0)}}transfer(e){this.handlers.forEach((t,i)=>{t.forEach(r=>{e.on(i,r)})})}clear(){this.handlers.clear()}};var f={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},st=3e4,I=class extends K{constructor(e){super(),this.apiUrl=e.apiUrl||N,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??st,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,t,i){let r=this.mergeHeaders(t.headers),{signal:o,cleanup:s}=this.createTimeoutSignal(t.signal),a={...t,headers:r,credentials:r.Authorization?void 0:"include",signal:o};this.emit("request",e,a);try{let l=await fetch(e,a);return s(),l.ok||await this.handleResponseError(l,i),this.emit("response",this.safeClone(l),e),{data:await this.parseResponse(this.safeClone(l)),status:l.status}}catch(l){s();let y=l instanceof Error?l:new Error(String(l));this.emit("error",y,e),this.handleFetchError(l,i)}}async request(e,t,i){let{data:r}=await this.executeRequest(e,t,i);return r}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 r=()=>t.abort();e.addEventListener("abort",r),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 s=await e.json();if(s&&typeof s=="object"){let a=s;typeof a.message=="string"&&(i.message=a.message),typeof a.error=="string"&&(i.error=a.error)}}else i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let r=i.message||i.error||`${t} failed`;throw e.status===401?p.authentication(r):p.api(r,e.status)}handleFetchError(e,t){throw R(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 s of e)if(!s.md5)throw p.file(`MD5 checksum missing for file: ${s.path}`,s.path);let{body:i,headers:r}=await this.createDeployBody(e,t.tags,t.via),o={};return t.deployToken?o.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(o.Authorization=`Bearer ${t.apiKey}`),t.caller&&(o["X-Caller"]=t.caller),this.request(`${t.apiUrl||this.apiUrl}${f.DEPLOYMENTS}`,{method:"POST",body:i,headers:{...r,...o},signal:t.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentTags(e,t){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:t})},"Update deployment tags")}async removeDeployment(e){await this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,t,i){let r={};t&&(r.deployment=t),i!==void 0&&(r.tags=i);let{data:o,status:s}=await this.requestWithStatus(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"Set domain");return{...o,isCreate:s===201}}async listDomains(){return this.request(`${this.apiUrl}${f.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async updateDomainTags(e,t){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:t})},"Update domain tags")}async removeDomain(e){await this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,t){let i={};return e!==void 0&&(i.ttl=e),t!==void 0&&(i.tags=t),this.request(`${this.apiUrl}${f.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${f.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${f.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${f.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${f.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${f.PING}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return this.request(`${this.apiUrl}${f.PING}`,{method:"GET"},"Ping")}async checkSPA(e){let t=e.find(s=>s.path==="index.html"||s.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 r={files:e.map(s=>s.path),index:i};return(await this.request(`${this.apiUrl}${f.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"SPA check")).isSPA}};E();k();E();E();function H(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 oe(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}E();G();async function ct(){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 M(t);return{path:z,content:t,size:e.length,md5:i}}async function ve(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===z))return n;try{if(await e.checkSPA(n)){let r=await ct();return[...n,r]}}catch{}return n}function re(n){let{getApi:e,ensureInit:t,processInput:i,clientDefaults:r,hasAuth:o}=n;return{create:async(s,a={})=>{await t();let l=r?oe(a,r):a;if(o&&!o()&&!l.deployToken&&!l.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 y=e(),g=await i(s,l);return g=await ve(g,y,l),y.deploy(g,l)},list:async()=>(await t(),e().listDeployments()),get:async s=>(await t(),e().getDeployment(s)),set:async(s,a)=>(await t(),e().updateDeploymentTags(s,a.tags)),remove:async s=>{await t(),await e().removeDeployment(s)}}}function se(n){let{getApi:e,ensureInit:t}=n;return{set:async(i,r={})=>{await t();let{deployment:o,tags:s}=r;return o===void 0&&s&&s.length>0?e().updateDomainTags(i,s):e().setDomain(i,o,s)},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 ae(n){let{getApi:e,ensureInit:t}=n;return{get:async()=>(await t(),e().getAccount())}}function pe(n){let{getApi:e,ensureInit:t}=n;return{create:async(i={})=>(await t(),e().createToken(i.ttl,i.tags)),list:async()=>(await t(),e().listTokens()),remove:async i=>{await t(),await e().removeToken(i)}}}var V=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 I({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=re({...i,processInput:(r,o)=>this.processInput(r,o),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=se(i),this._account=ae(i),this._tokens=pe(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}};E();F();ce();k();E();var ue=S(require("mime-db"),1),fe={};for(let n in ue.default){let e=ue.default[n];e&&e.extensions&&e.extensions.forEach(t=>{fe[t]||(fe[t]=n)})}function Re(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return fe[e]||"application/octet-stream"}async function we(n,e,t){let{FormData:i,File:r}=await import("formdata-node"),{FormDataEncoder:o}=await import("form-data-encoder"),s=new i,a=[];for(let c of n){let m=Re(c.path),h;if(Buffer.isBuffer(c.content))h=new r([c.content],c.path,{type:m});else if(typeof Blob<"u"&&c.content instanceof Blob)h=new r([c.content],c.path,{type:m});else throw p.file(`Unsupported file.content type for Node.js: ${c.path}`,c.path);if(!c.md5)throw p.file(`File missing md5 checksum: ${c.path}`,c.path);let A=c.path.startsWith("/")?c.path:"/"+c.path;s.append("files[]",h,A),a.push(c.md5)}s.append("checksums",JSON.stringify(a)),e&&e.length>0&&s.append("tags",JSON.stringify(e)),t&&s.append("via",t);let l=new o(s),y=[];for await(let c of l.encode())y.push(Buffer.from(c));let g=Buffer.concat(y);return{body:g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength),headers:{"Content-Type":l.contentType,"Content-Length":Buffer.byteLength(g).toString()}}}G();function dt(n,e,t,i=!0){let r=n===1?e:t;return i?`${n} ${r}`:r}me();Ee();F();E();var Oe=S(require("mime-db"),1),$e=Oe.default,ht=new Set(Object.keys($e)),yt=new Map(Object.entries($e).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)]));var gt=[[/File name cannot|Invalid file name|File name contains|File name uses|traversal/i,"Invalid File Name"],[/File size must be positive/i,"Invalid File Size"],[/MIME type is required/i,"Missing MIME Type"],[/Invalid MIME type/i,"Invalid MIME Type"],[/not allowed/i,"Invalid File Type"],[/extension does not match/i,"Extension Mismatch"],[/Total size/i,"Total Size Exceeded"],[/exceeds limit/i,"File Too Large"]];function Et(n,e){if(n===d.PROCESSING_ERROR)return"Processing Error";if(n===d.EMPTY_FILE)return"Empty File";if(!e)return"Validation Failed";for(let[t,i]of gt)if(t.test(e))return i;return"Validation Failed"}function W(n,e=1){if(n===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,r)).toFixed(e))+" "+i[r]}function Dt(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 St(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],r=yt.get(e);if(r&&!r.has(i))return!1}return!0}function xt(n,e){let t=[],i=[];if(n.length===0){let o="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:o,errors:[o],isClientError:!0}}}if(n.length>e.maxFilesCount){let o=`Number of files (${n.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:n.map(s=>({...s,status:d.VALIDATION_FAILED,statusMessage:o})),validFiles:[],error:{error:"File Count Exceeded",details:o,errors:[o],isClientError:!0}}}let r=0;for(let o of n){let s=d.READY,a="Ready for upload",l=o.name?Dt(o.name):{valid:!1,reason:"File name cannot be empty"};o.status===d.PROCESSING_ERROR?(s=d.PROCESSING_ERROR,a=o.statusMessage||"A file failed during processing.",t.push(`${o.name}: ${a}`)):!o.name||o.name.trim().length===0?(s=d.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${o.name||"(empty)"}: ${a}`)):o.name.includes("\0")?(s=d.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push(`${o.name}: ${a}`)):l.valid?o.size<=0?(s=d.EMPTY_FILE,a=o.size===0?"File is empty (0 bytes)":"File size must be positive",t.push(`${o.name}: ${a}`)):!o.type||o.type.trim().length===0?(s=d.VALIDATION_FAILED,a="File MIME type is required",t.push(`${o.name}: ${a}`)):ee(o.type)?!B.some(y=>o.type===y)&&!ht.has(o.type)?(s=d.VALIDATION_FAILED,a=`Invalid MIME type "${o.type}"`,t.push(`${o.name}: ${a}`)):St(o.name,o.type)?o.size>e.maxFileSize?(s=d.VALIDATION_FAILED,a=`File size (${W(o.size)}) exceeds limit of ${W(e.maxFileSize)}`,t.push(`${o.name}: ${a}`)):(r+=o.size,r>e.maxTotalSize&&(s=d.VALIDATION_FAILED,a=`Total size would exceed limit of ${W(e.maxTotalSize)}`,t.push(`${o.name}: ${a}`))):(s=d.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${o.name}: ${a}`)):(s=d.VALIDATION_FAILED,a=`File type "${o.type}" is not allowed`,t.push(`${o.name}: ${a}`)):(s=d.VALIDATION_FAILED,a=l.reason||"Invalid file name",t.push(`${o.name}: ${a}`)),i.push({...o,status:s,statusMessage:a})}if(t.length>0){let o=i.find(a=>a.status!==d.READY&&a.status!==d.PENDING),s=Et(o?.status,o?.statusMessage);return{files:i.map(a=>({...a,status:d.VALIDATION_FAILED})),validFiles:[],error:{error:s,details:t.length===1?t[0]:`${t.length} file(s) failed validation`,errors:t,isClientError:!0}}}return{files:i,validFiles:i,error:null}}function be(n){return n.filter(e=>e.status===d.READY)}function Tt(n){return be(n).length>0}E();ce();k();Se();F();var J=class extends V{constructor(e={}){if(x()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return H(e,{})}async loadFullConfig(){try{let e=await q(this.clientOptions.configFile),t=H(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let i=new I({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let r=await this.http.getConfig();j(r)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){let i=typeof e=="string"?[e]:e;if(!Array.isArray(i)||!i.every(o=>typeof o=="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:r}=await Promise.resolve().then(()=>(Se(),ke));return r(i,t)}getDeployBodyCreator(){return we}},Me=J;0&&(module.exports={ALLOWED_MIME_TYPES,API_KEY_HEX_LENGTH,API_KEY_PREFIX,API_KEY_TOTAL_LENGTH,AccountPlan,ApiHttp,AuthMethod,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_TOKEN_HEX_LENGTH,DEPLOY_TOKEN_PREFIX,DEPLOY_TOKEN_TOTAL_LENGTH,DeploymentStatus,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,JUNK_DIRECTORIES,Ship,ShipError,TAG_CONSTRAINTS,TAG_PATTERN,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeTags,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getCurrentConfig,getENV,getValidFiles,isAllowedMimeType,isCustomDomain,isDeployment,isPlatformDomain,isShipError,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,serializeTags,setPlatformConfig,validateApiKey,validateApiUrl,validateDeployToken,validateFiles});
2
2
 
3
3
  // Ship SDK: Enable axios-style CommonJS imports
4
4
  const originalExports = module.exports;