@shipstatic/ship 0.7.13 → 0.7.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/SKILL.md +83 -0
- package/dist/browser.d.ts +3 -1
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +4 -3
package/dist/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Ot=Object.create;var fe=Object.defineProperty;var Rt=Object.getOwnPropertyDescriptor;var kt=Object.getOwnPropertyNames;var It=Object.getPrototypeOf,Ft=Object.prototype.hasOwnProperty;var F=(e,o)=>()=>(e&&(o=e(e=0)),o);var Pt=(e,o)=>{for(var t in o)fe(e,t,{get:o[t],enumerable:!0})},$t=(e,o,t,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of kt(o))!Ft.call(e,i)&&i!==t&&fe(e,i,{get:()=>o[i],enumerable:!(n=Rt(o,i))||n.enumerable});return e};var E=(e,o,t)=>(t=e!=null?Ot(It(e)):{},$t(o||!e||!e.__esModule?fe(t,"default",{value:e,enumerable:!0}):t,e));function O(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function Se(e){let o=e.lastIndexOf(".");if(o===-1||o===e.length-1)return!1;let t=e.slice(o+1).toLowerCase();return Lt.has(t)}function Pe(e){return Nt.test(e)}function be(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(t=>De.has(t))}function te(e){if(!e.startsWith(j))throw l.validation(`API key must start with "${j}"`);if(e.length!==Ie)throw l.validation(`API key must be ${Ie} characters total (${j} + ${ge} hex chars)`);let o=e.slice(j.length);if(!/^[a-f0-9]{64}$/i.test(o))throw l.validation(`API key must contain ${ge} hexadecimal characters after "${j}" prefix`)}function $e(e){if(!e.startsWith(M))throw l.validation(`Deploy token must start with "${M}"`);if(e.length!==Fe)throw l.validation(`Deploy token must be ${Fe} characters total (${M} + ${ye} hex chars)`);let o=e.slice(M.length);if(!/^[a-f0-9]{64}$/i.test(o))throw l.validation(`Deploy token must contain ${ye} hexadecimal characters after "${M}" prefix`)}function Le(e){try{let o=new URL(e);if(!["http:","https:"].includes(o.protocol))throw l.validation("API URL must use http:// or https:// protocol");if(o.pathname!=="/"&&o.pathname!=="")throw l.validation("API URL must not contain a path");if(o.search||o.hash)throw l.validation("API URL must not contain query parameters or fragments")}catch(o){throw O(o)?o:l.validation("API URL must be a valid URL")}}var g,he,l,Lt,Nt,De,j,ge,Ie,M,ye,Fe,Ce,K,b=F(()=>{"use strict";(function(e){e.Validation="validation_failed",e.NotFound="not_found",e.RateLimit="rate_limit_exceeded",e.Authentication="authentication_failed",e.Business="business_logic_error",e.Api="internal_server_error",e.Network="network_error",e.Cancelled="operation_cancelled",e.File="file_error",e.Config="config_error"})(g||(g={}));he={client:new Set([g.Business,g.Config,g.File,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},l=class e extends Error{type;status;details;constructor(o,t,n,i){super(t),this.type=o,this.status=n,this.details=i,this.name="ShipError"}toResponse(){let o=this.type===g.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:o}}static fromResponse(o){return new e(o.error,o.message,o.status,o.details)}static validation(o,t){return new e(g.Validation,o,400,t)}static notFound(o,t){let n=t?`${o} ${t} not found`:`${o} not found`;return new e(g.NotFound,n,404)}static rateLimit(o="Too many requests"){return new e(g.RateLimit,o,429)}static authentication(o="Authentication required",t){return new e(g.Authentication,o,401,t)}static business(o,t=400){return new e(g.Business,o,t)}static network(o,t){return new e(g.Network,o,void 0,{cause:t})}static cancelled(o){return new e(g.Cancelled,o)}static file(o,t){return new e(g.File,o,void 0,{filePath:t})}static config(o,t){return new e(g.Config,o,void 0,t)}static api(o,t=500){return new e(g.Api,o,t)}static database(o,t=500){return new e(g.Api,o,t)}static storage(o,t=500){return new e(g.Api,o,t)}get filePath(){return this.details?.filePath}isClientError(){return he.client.has(this.type)}isNetworkError(){return he.network.has(this.type)}isAuthError(){return he.auth.has(this.type)}isValidationError(){return this.type===g.Validation}isFileError(){return this.type===g.File}isConfigError(){return this.type===g.Config}isType(o){return this.type===o}};Lt=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);Nt=/[\x00-\x1f\x7f#?%\\<>"]/;De=new Set(["node_modules","package.json"]);j="ship-",ge=64,Ie=j.length+ge,M="token-",ye=64,Fe=M.length+ye,Ce="ship.json";K="https://api.shipstatic.com"});function Ne(e){ve=e}function ne(){if(ve===null)throw l.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ve}var ve,ie=F(()=>{"use strict";b();ve=null});function Ut(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function P(){return Ue||Ut()}var Ue,J=F(()=>{"use strict";Ue=null});async function jt(e){let o=(await import("spark-md5")).default;return new Promise((t,n)=>{let s=Math.ceil(e.size/2097152),r=0,a=new o.ArrayBuffer,p=new FileReader,c=()=>{let u=r*2097152,d=Math.min(u+2097152,e.size);p.readAsArrayBuffer(e.slice(u,d))};p.onload=u=>{let d=u.target?.result;if(!d){n(l.business("Failed to read file chunk"));return}a.append(d),r++,r<s?c():t({md5:a.end()})},p.onerror=()=>{n(l.business("Failed to calculate MD5: FileReader error"))},c()})}async function Mt(e){let o=await import("crypto");if(Buffer.isBuffer(e)){let n=o.createHash("md5");return n.update(e),{md5:n.digest("hex")}}let t=await import("fs");return new Promise((n,i)=>{let s=o.createHash("md5"),r=t.createReadStream(e);r.on("error",a=>i(l.business(`Failed to read file for MD5: ${a.message}`))),r.on("data",a=>s.update(a)),r.on("end",()=>n({md5:s.digest("hex")}))})}async function se(e){let o=P();if(o==="browser"){if(!(e instanceof Blob))throw l.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return jt(e)}if(o==="node"){if(!(Buffer.isBuffer(e)||typeof e=="string"))throw l.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Mt(e)}throw l.business("Unknown or unsupported execution environment for MD5 calculation.")}var Ee=F(()=>{"use strict";J();b()});function Je(e){if(!e||e.length===0)return[];if(e.find(t=>t&&be(t)))throw l.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(t=>{if(!t)return!1;let n=t.replace(/\\/g,"/").split("/").filter(Boolean);if(n.length===0)return!0;let i=n[n.length-1];if((0,qe.isJunk)(i))return!1;for(let r of n)if(r!==".well-known"&&(r.startsWith(".")||r.length>255))return!1;let s=n.slice(0,-1);for(let r of s)if(Ht.some(a=>r.toLowerCase()===a.toLowerCase()))return!1;return!0})}var qe,Ht,We=F(()=>{"use strict";qe=require("junk");b();Ht=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ye(e){if(!e||e.length===0)return"";let o=e.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(o.length===0)return"";if(o.length===1)return o[0];let t=o.map(s=>s.split("/").filter(Boolean)),n=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i;s++){let r=t[0][s];if(t.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function ae(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Ae=F(()=>{"use strict"});function Xe(e,o={}){if(o.flatten===!1)return e.map(n=>({path:ae(n),name:xe(n)}));let t=Gt(e);return e.map(n=>{let i=ae(n);if(t){let s=t.endsWith("/")?t:`${t}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=xe(n)),{path:i,name:xe(n)}})}function Gt(e){if(!e.length)return"";let t=e.map(s=>ae(s)).map(s=>s.split("/")),n=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i-1;s++){let r=t[0][s];if(t.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function xe(e){return e.split(/[/\\]/).pop()||e}var Ze=F(()=>{"use strict";Ae()});function Qe(e){if(Pe(e))return{valid:!1,reason:"File name contains unsafe characters"};if(e.startsWith(" ")||e.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(e.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let o=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,t=e.split("/").pop()||e;return o.test(t)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}var et=F(()=>{"use strict";b()});function tt(e,o){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw l.business(`Security error: Unsafe file path "${e}" for file: ${o}`)}function ot(e,o){let t=Qe(e);if(!t.valid)throw l.business(t.reason||"Invalid file name");if(Se(e))throw l.business(`File extension not allowed: "${o}"`)}var nt=F(()=>{"use strict";b();et()});var st={};Pt(st,{processFilesForNode:()=>Vt});function it(e,o=new Set){let t=[],n=A.realpathSync(e);if(o.has(n))return t;o.add(n);let i=A.readdirSync(e);for(let s of i){let r=x.join(e,s),a=A.statSync(r);if(a.isDirectory()){let p=it(r,o);t.push(...p)}else a.isFile()&&t.push(r)}return t}async function Vt(e,o={}){if(P()!=="node")throw l.business("processFilesForNode can only be called in Node.js environment.");for(let f of e){let D=x.resolve(f);try{if(A.statSync(D).isDirectory()){let R=A.readdirSync(D).find(k=>De.has(k));if(R)throw l.business(`"${R}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(R){if(O(R))throw R}}let t=e.flatMap(f=>{let D=x.resolve(f);try{return A.statSync(D).isDirectory()?it(D):[D]}catch{throw l.file(`Path does not exist: ${f}`,f)}}),n=[...new Set(t)],i=e.map(f=>x.resolve(f)),s=Ye(i.map(f=>{try{return A.statSync(f).isDirectory()?f:x.dirname(f)}catch{return x.dirname(f)}})),r=n.map(f=>{if(s&&s.length>0){let D=x.relative(s,f);if(D&&typeof D=="string"&&!D.startsWith(".."))return D.replace(/\\/g,"/")}return x.basename(f)}),a=new Set(Je(r));if(a.size===0)return[];let p=[],c=[];for(let f=0;f<n.length;f++)a.has(r[f])&&(p.push(n[f]),c.push(r[f]));let u=Xe(c,{flatten:o.pathDetect!==!1}),d=[],I=0,U=ne();for(let f=0;f<p.length;f++){let D=p[f],R=u[f].path;try{tt(R,D);let k=A.statSync(D);if(k.size===0)continue;if(ot(R,D),k.size>U.maxFileSize)throw l.business(`File ${D} is too large. Maximum allowed size is ${U.maxFileSize/(1024*1024)}MB.`);if(I+=k.size,I>U.maxTotalSize)throw l.business(`Total deploy size is too large. Maximum allowed is ${U.maxTotalSize/(1024*1024)}MB.`);let q=A.readFileSync(D),{md5:xt}=await se(q);d.push({path:R,content:q,size:q.length,md5:xt})}catch(k){if(O(k))throw k;let q=k instanceof Error?k.message:String(k);throw l.file(`Failed to read file "${D}": ${q}`,D)}}if(d.length>U.maxFilesCount)throw l.business(`Too many files to deploy. Maximum allowed is ${U.maxFilesCount} files.`);return d}var A,x,rt=F(()=>{"use strict";J();Ee();We();nt();b();ie();Ze();Ae();A=E(require("fs"),1),x=E(require("path"),1)});var wt=require("commander");b();var oe=class{constructor(){this.handlers=new Map}on(o,t){this.handlers.has(o)||this.handlers.set(o,new Set),this.handlers.get(o).add(t)}off(o,t){let n=this.handlers.get(o);n&&(n.delete(t),n.size===0&&this.handlers.delete(o))}emit(o,...t){let n=this.handlers.get(o);if(!n)return;let i=Array.from(n);for(let s of i)try{s(...t)}catch(r){n.delete(s),o!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(o)):this.emit("error",new Error(String(r)),String(o))},0)}}transfer(o){this.handlers.forEach((t,n)=>{t.forEach(i=>{o.on(n,i)})})}clear(){this.handlers.clear()}};var S={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},_t=3e4,B=class extends oe{constructor(t){super();this.globalHeaders={};this.apiUrl=t.apiUrl||K,this.getAuthHeadersCallback=t.getAuthHeaders,this.timeout=t.timeout??_t,this.createDeployBody=t.createDeployBody}setGlobalHeaders(t){this.globalHeaders=t}transferEventsTo(t){this.transfer(t)}async executeRequest(t,n,i){let s=this.mergeHeaders(n.headers),{signal:r,cleanup:a}=this.createTimeoutSignal(n.signal),p={...n,headers:s,credentials:s.Authorization?void 0:"include",signal:r};this.emit("request",t,p);try{let c=await fetch(t,p);return a(),c.ok||await this.handleResponseError(c,i),this.emit("response",this.safeClone(c),t),{data:await this.parseResponse(this.safeClone(c)),status:c.status}}catch(c){a();let u=c instanceof Error?c:new Error(String(c));this.emit("error",u,t),this.handleFetchError(c,i)}}async request(t,n,i){let{data:s}=await this.executeRequest(t,n,i);return s}async requestWithStatus(t,n,i){return this.executeRequest(t,n,i)}mergeHeaders(t={}){return{...this.globalHeaders,...t,...this.getAuthHeadersCallback()}}createTimeoutSignal(t){let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeout);if(t){let s=()=>n.abort();t.addEventListener("abort",s),t.aborted&&n.abort()}return{signal:n.signal,cleanup:()=>clearTimeout(i)}}safeClone(t){try{return t.clone()}catch{return t}}async parseResponse(t){if(!(t.headers.get("Content-Length")==="0"||t.status===204))return t.json()}async handleResponseError(t,n){let i={};try{if(t.headers.get("content-type")?.includes("application/json")){let a=await t.json();if(a&&typeof a=="object"){let p=a;typeof p.message=="string"&&(i.message=p.message),typeof p.error=="string"&&(i.error=p.error)}}else i={message:await t.text()}}catch{i={message:"Failed to parse error response"}}let s=i.message||i.error||`${n} failed`;throw t.status===401?l.authentication(s):l.api(s,t.status)}handleFetchError(t,n){throw O(t)?t:t instanceof Error&&t.name==="AbortError"?l.cancelled(`${n} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?l.network(`${n} failed: ${t.message}`,t):t instanceof Error?l.business(`${n} failed: ${t.message}`):l.business(`${n} failed: Unknown error`)}async deploy(t,n={}){if(!t.length)throw l.business("No files to deploy");for(let a of t)if(!a.md5)throw l.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:i,headers:s}=await this.createDeployBody(t,n.labels,n.via),r={};return n.deployToken?r.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(r.Authorization=`Bearer ${n.apiKey}`),n.caller&&(r["X-Caller"]=n.caller),this.request(`${n.apiUrl||this.apiUrl}${S.DEPLOYMENTS}`,{method:"POST",body:i,headers:{...s,...r},signal:n.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(t){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(t,n){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:n})},"Update deployment labels")}async removeDeployment(t){await this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove deployment")}async setDomain(t,n,i){let s={};n&&(s.deployment=n),i!==void 0&&(s.labels=i);let{data:r,status:a}=await this.requestWithStatus(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Set domain");return{...r,isCreate:a===201}}async listDomains(){return this.request(`${this.apiUrl}${S.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}`,{method:"GET"},"Get domain")}async removeDomain(t){await this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/share`,{method:"GET"},"Get domain share")}async validateDomain(t){return this.request(`${this.apiUrl}${S.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:t})},"Validate domain")}async createToken(t,n){let i={};return t!==void 0&&(i.ttl=t),n!==void 0&&(i.labels=n),this.request(`${this.apiUrl}${S.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${S.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(t){await this.request(`${this.apiUrl}${S.TOKENS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${S.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${S.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${S.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(t){let n=t.find(a=>a.path==="index.html"||a.path==="/index.html");if(!n||n.size>100*1024)return!1;let i;if(typeof Buffer<"u"&&Buffer.isBuffer(n.content))i=n.content.toString("utf-8");else if(typeof Blob<"u"&&n.content instanceof Blob)i=await n.content.text();else if(typeof File<"u"&&n.content instanceof File)i=await n.content.text();else return!1;let s={files:t.map(a=>a.path),index:i};return(await this.request(`${this.apiUrl}${S.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA check")).isSPA}};b();ie();b();b();function we(e={},o={}){let t={apiUrl:e.apiUrl||o.apiUrl||K,apiKey:e.apiKey!==void 0?e.apiKey:o.apiKey,deployToken:e.deployToken!==void 0?e.deployToken:o.deployToken},n={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(n.apiKey=t.apiKey),t.deployToken!==void 0&&(n.deployToken=t.deployToken),n}function _e(e,o){let t={...e};return t.apiUrl===void 0&&o.apiUrl!==void 0&&(t.apiUrl=o.apiUrl),t.apiKey===void 0&&o.apiKey!==void 0&&(t.apiKey=o.apiKey),t.deployToken===void 0&&o.deployToken!==void 0&&(t.deployToken=o.deployToken),t.timeout===void 0&&o.timeout!==void 0&&(t.timeout=o.timeout),t.maxConcurrency===void 0&&o.maxConcurrency!==void 0&&(t.maxConcurrency=o.maxConcurrency),t.onProgress===void 0&&o.onProgress!==void 0&&(t.onProgress=o.onProgress),t.caller===void 0&&o.caller!==void 0&&(t.caller=o.caller),t}b();Ee();async function Kt(){let o=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(o,"utf-8"):t=new Blob([o],{type:"application/json"});let{md5:n}=await se(t);return{path:Ce,content:t,size:o.length,md5:n}}async function je(e,o,t){if(t.spaDetect===!1||e.some(n=>n.path===Ce))return e;try{if(await o.checkSPA(e)){let i=await Kt();return[...e,i]}}catch{}return e}function Me(e){let{getApi:o,ensureInit:t,processInput:n,clientDefaults:i,hasAuth:s}=e;return{upload:async(r,a={})=>{await t();let p=i?_e(a,i):a;if(s&&!s()&&!p.deployToken&&!p.apiKey)throw l.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw l.config("processInput function is not provided.");let c=o(),u=await n(r,p);return u=await je(u,c,p),c.deploy(u,p)},list:async()=>(await t(),o().listDeployments()),get:async r=>(await t(),o().getDeployment(r)),set:async(r,a)=>(await t(),o().updateDeploymentLabels(r,a.labels)),remove:async r=>{await t(),await o().removeDeployment(r)}}}function Ke(e){let{getApi:o,ensureInit:t}=e;return{set:async(n,i={})=>(await t(),o().setDomain(n,i.deployment,i.labels)),list:async()=>(await t(),o().listDomains()),get:async n=>(await t(),o().getDomain(n)),remove:async n=>{await t(),await o().removeDomain(n)},verify:async n=>(await t(),o().verifyDomain(n)),validate:async n=>(await t(),o().validateDomain(n)),dns:async n=>(await t(),o().getDomainDns(n)),records:async n=>(await t(),o().getDomainRecords(n)),share:async n=>(await t(),o().getDomainShare(n))}}function Be(e){let{getApi:o,ensureInit:t}=e;return{get:async()=>(await t(),o().getAccount())}}function ze(e){let{getApi:o,ensureInit:t}=e;return{create:async(n={})=>(await t(),o().createToken(n.ttl,n.labels)),list:async()=>(await t(),o().listTokens()),remove:async n=>{await t(),await o().removeToken(n)}}}var re=class{constructor(o={}){this.initPromise=null;this._config=null;this.auth=null;this.customHeaders={};this.clientOptions=o,o.deployToken?this.auth={type:"token",value:o.deployToken}:o.apiKey&&(this.auth={type:"apiKey",value:o.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(o);this.http=new B({...o,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=Me({...n,processInput:(i,s)=>this.processInput(i,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=Ke(n),this._account=Be(n),this._tokens=ze(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(o,t){return this.deployments.upload(o,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=ne(),this._config)}on(o,t){this.http.on(o,t)}off(o,t){this.http.off(o,t)}setHeaders(o){this.customHeaders=o,this.http.setGlobalHeaders(o)}clearHeaders(){this.customHeaders={},this.http.setGlobalHeaders({})}replaceHttpClient(o){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(o)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=o,Object.keys(this.customHeaders).length>0&&this.http.setGlobalHeaders(this.customHeaders)}setDeployToken(o){if(!o||typeof o!="string")throw l.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:o}}setApiKey(o){if(!o||typeof o!="string")throw l.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:o}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};b();J();var z=require("zod");b();J();var Te="ship",Bt=z.z.object({apiUrl:z.z.string().url().optional(),apiKey:z.z.string().optional(),deployToken:z.z.string().optional()}).strict();function He(e){try{return Bt.parse(e)}catch(o){if(o instanceof z.z.ZodError){let t=o.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw l.config(`Configuration validation failed${n}: ${t.message}`)}throw l.config("Configuration validation failed")}}async function zt(e){try{if(P()!=="node")return{};let{cosmiconfigSync:o}=await import("cosmiconfig"),t=await import("os"),n=o(Te,{searchPlaces:[`.${Te}rc`,"package.json",`${t.homedir()}/.${Te}rc`],stopDir:t.homedir()}),i;if(e?i=n.load(e):i=n.search(),i&&i.config)return He(i.config)}catch(o){if(O(o))throw o}return{}}async function Ge(e){if(P()!=="node")return{};let o={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await zt(e),n={apiUrl:o.apiUrl??t.apiUrl,apiKey:o.apiKey??t.apiKey,deployToken:o.deployToken??t.deployToken};return He(n)}ie();b();async function Ve(e,o,t){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new n,a=[];for(let d of e){if(!Buffer.isBuffer(d.content)&&!(typeof Blob<"u"&&d.content instanceof Blob))throw l.file(`Unsupported file.content type for Node.js: ${d.path}`,d.path);if(!d.md5)throw l.file(`File missing md5 checksum: ${d.path}`,d.path);let I=new i([d.content],d.path,{type:"application/octet-stream"});r.append("files[]",I),a.push(d.md5)}r.append("checksums",JSON.stringify(a)),o&&o.length>0&&r.append("labels",JSON.stringify(o)),t&&r.append("via",t);let p=new s(r),c=[];for await(let d of p.encode())c.push(Buffer.from(d));let u=Buffer.concat(c);return{body:u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),headers:{"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(u).toString()}}}var le=class extends re{constructor(o={}){if(P()!=="node")throw l.business("Node.js Ship class can only be used in Node.js environment.");super(o)}resolveInitialConfig(o){return we(o,{})}async loadFullConfig(){try{let o=await Ge(this.clientOptions.configFile),t=we(this.clientOptions,o);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let n=new B({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();Ne(i)}catch(o){throw this.initPromise=null,o}}async processInput(o,t){let n=typeof o=="string"?[o]:o;if(!Array.isArray(n)||!n.every(s=>typeof s=="string"))throw l.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw l.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(rt(),st));return i(n,t)}getDeployBodyCreator(){return Ve}};b();var _=require("fs"),de=E(require("path"),1);var Oe=E(require("columnify"),1),m=require("yoctocolors"),at=["isCreate"],v=(e,o,t)=>t?o:e(o),w=(e,o,t)=>{console.log(o?JSON.stringify({success:e},null,2)+`
|
|
2
|
+
"use strict";var Ot=Object.create;var fe=Object.defineProperty;var Rt=Object.getOwnPropertyDescriptor;var kt=Object.getOwnPropertyNames;var It=Object.getPrototypeOf,Ft=Object.prototype.hasOwnProperty;var F=(e,o)=>()=>(e&&(o=e(e=0)),o);var Pt=(e,o)=>{for(var t in o)fe(e,t,{get:o[t],enumerable:!0})},$t=(e,o,t,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of kt(o))!Ft.call(e,i)&&i!==t&&fe(e,i,{get:()=>o[i],enumerable:!(n=Rt(o,i))||n.enumerable});return e};var E=(e,o,t)=>(t=e!=null?Ot(It(e)):{},$t(o||!e||!e.__esModule?fe(t,"default",{value:e,enumerable:!0}):t,e));function O(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function Se(e){let o=e.lastIndexOf(".");if(o===-1||o===e.length-1)return!1;let t=e.slice(o+1).toLowerCase();return Lt.has(t)}function Pe(e){return Nt.test(e)}function be(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(t=>De.has(t))}function te(e){if(!e.startsWith(j))throw l.validation(`API key must start with "${j}"`);if(e.length!==Ie)throw l.validation(`API key must be ${Ie} characters total (${j} + ${ge} hex chars)`);let o=e.slice(j.length);if(!/^[a-f0-9]{64}$/i.test(o))throw l.validation(`API key must contain ${ge} hexadecimal characters after "${j}" prefix`)}function $e(e){if(!e.startsWith(M))throw l.validation(`Deploy token must start with "${M}"`);if(e.length!==Fe)throw l.validation(`Deploy token must be ${Fe} characters total (${M} + ${ye} hex chars)`);let o=e.slice(M.length);if(!/^[a-f0-9]{64}$/i.test(o))throw l.validation(`Deploy token must contain ${ye} hexadecimal characters after "${M}" prefix`)}function Le(e){try{let o=new URL(e);if(!["http:","https:"].includes(o.protocol))throw l.validation("API URL must use http:// or https:// protocol");if(o.pathname!=="/"&&o.pathname!=="")throw l.validation("API URL must not contain a path");if(o.search||o.hash)throw l.validation("API URL must not contain query parameters or fragments")}catch(o){throw O(o)?o:l.validation("API URL must be a valid URL")}}var g,he,l,Lt,Nt,De,j,ge,Ie,M,ye,Fe,Ce,K,b=F(()=>{"use strict";(function(e){e.Validation="validation_failed",e.NotFound="not_found",e.RateLimit="rate_limit_exceeded",e.Authentication="authentication_failed",e.Business="business_logic_error",e.Api="internal_server_error",e.Network="network_error",e.Cancelled="operation_cancelled",e.File="file_error",e.Config="config_error"})(g||(g={}));he={client:new Set([g.Business,g.Config,g.File,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},l=class e extends Error{type;status;details;constructor(o,t,n,i){super(t),this.type=o,this.status=n,this.details=i,this.name="ShipError"}toResponse(){let o=this.type===g.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:o}}static fromResponse(o){return new e(o.error,o.message,o.status,o.details)}static validation(o,t){return new e(g.Validation,o,400,t)}static notFound(o,t){let n=t?`${o} ${t} not found`:`${o} not found`;return new e(g.NotFound,n,404)}static rateLimit(o="Too many requests"){return new e(g.RateLimit,o,429)}static authentication(o="Authentication required",t){return new e(g.Authentication,o,401,t)}static business(o,t=400){return new e(g.Business,o,t)}static network(o,t){return new e(g.Network,o,void 0,{cause:t})}static cancelled(o){return new e(g.Cancelled,o)}static file(o,t){return new e(g.File,o,void 0,{filePath:t})}static config(o,t){return new e(g.Config,o,void 0,t)}static api(o,t=500){return new e(g.Api,o,t)}static database(o,t=500){return new e(g.Api,o,t)}static storage(o,t=500){return new e(g.Api,o,t)}get filePath(){return this.details?.filePath}isClientError(){return he.client.has(this.type)}isNetworkError(){return he.network.has(this.type)}isAuthError(){return he.auth.has(this.type)}isValidationError(){return this.type===g.Validation}isFileError(){return this.type===g.File}isConfigError(){return this.type===g.Config}isType(o){return this.type===o}};Lt=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);Nt=/[\x00-\x1f\x7f#?%\\<>"]/;De=new Set(["node_modules","package.json"]);j="ship-",ge=64,Ie=j.length+ge,M="token-",ye=64,Fe=M.length+ye,Ce="ship.json";K="https://api.shipstatic.com"});function Ne(e){ve=e}function ne(){if(ve===null)throw l.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ve}var ve,ie=F(()=>{"use strict";b();ve=null});function Ut(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function P(){return Ue||Ut()}var Ue,J=F(()=>{"use strict";Ue=null});async function jt(e){let o=(await import("spark-md5")).default;return new Promise((t,n)=>{let s=Math.ceil(e.size/2097152),r=0,a=new o.ArrayBuffer,p=new FileReader,c=()=>{let u=r*2097152,d=Math.min(u+2097152,e.size);p.readAsArrayBuffer(e.slice(u,d))};p.onload=u=>{let d=u.target?.result;if(!d){n(l.business("Failed to read file chunk"));return}a.append(d),r++,r<s?c():t({md5:a.end()})},p.onerror=()=>{n(l.business("Failed to calculate MD5: FileReader error"))},c()})}async function Mt(e){let o=await import("crypto");if(Buffer.isBuffer(e)){let n=o.createHash("md5");return n.update(e),{md5:n.digest("hex")}}let t=await import("fs");return new Promise((n,i)=>{let s=o.createHash("md5"),r=t.createReadStream(e);r.on("error",a=>i(l.business(`Failed to read file for MD5: ${a.message}`))),r.on("data",a=>s.update(a)),r.on("end",()=>n({md5:s.digest("hex")}))})}async function se(e){let o=P();if(o==="browser"){if(!(e instanceof Blob))throw l.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return jt(e)}if(o==="node"){if(!(Buffer.isBuffer(e)||typeof e=="string"))throw l.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Mt(e)}throw l.business("Unknown or unsupported execution environment for MD5 calculation.")}var Ee=F(()=>{"use strict";J();b()});function Je(e){if(!e||e.length===0)return[];if(e.find(t=>t&&be(t)))throw l.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(t=>{if(!t)return!1;let n=t.replace(/\\/g,"/").split("/").filter(Boolean);if(n.length===0)return!0;let i=n[n.length-1];if((0,qe.isJunk)(i))return!1;for(let r of n)if(r!==".well-known"&&(r.startsWith(".")||r.length>255))return!1;let s=n.slice(0,-1);for(let r of s)if(Ht.some(a=>r.toLowerCase()===a.toLowerCase()))return!1;return!0})}var qe,Ht,We=F(()=>{"use strict";qe=require("junk");b();Ht=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ye(e){if(!e||e.length===0)return"";let o=e.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(o.length===0)return"";if(o.length===1)return o[0];let t=o.map(s=>s.split("/").filter(Boolean)),n=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i;s++){let r=t[0][s];if(t.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function ae(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Ae=F(()=>{"use strict"});function Xe(e,o={}){if(o.flatten===!1)return e.map(n=>({path:ae(n),name:xe(n)}));let t=Gt(e);return e.map(n=>{let i=ae(n);if(t){let s=t.endsWith("/")?t:`${t}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=xe(n)),{path:i,name:xe(n)}})}function Gt(e){if(!e.length)return"";let t=e.map(s=>ae(s)).map(s=>s.split("/")),n=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i-1;s++){let r=t[0][s];if(t.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function xe(e){return e.split(/[/\\]/).pop()||e}var Ze=F(()=>{"use strict";Ae()});function Qe(e){if(Pe(e))return{valid:!1,reason:"File name contains unsafe characters"};if(e.startsWith(" ")||e.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(e.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let o=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,t=e.split("/").pop()||e;return o.test(t)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}var et=F(()=>{"use strict";b()});function tt(e,o){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw l.business(`Security error: Unsafe file path "${e}" for file: ${o}`)}function ot(e,o){let t=Qe(e);if(!t.valid)throw l.business(t.reason||"Invalid file name");if(Se(e))throw l.business(`File extension not allowed: "${o}"`)}var nt=F(()=>{"use strict";b();et()});var st={};Pt(st,{processFilesForNode:()=>Vt});function it(e,o=new Set){let t=[],n=A.realpathSync(e);if(o.has(n))return t;o.add(n);let i=A.readdirSync(e);for(let s of i){let r=x.join(e,s),a=A.statSync(r);if(a.isDirectory()){let p=it(r,o);t.push(...p)}else a.isFile()&&t.push(r)}return t}async function Vt(e,o={}){if(P()!=="node")throw l.business("processFilesForNode can only be called in Node.js environment.");for(let f of e){let D=x.resolve(f);try{if(A.statSync(D).isDirectory()){let R=A.readdirSync(D).find(k=>De.has(k));if(R)throw l.business(`"${R}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(R){if(O(R))throw R}}let t=e.flatMap(f=>{let D=x.resolve(f);try{return A.statSync(D).isDirectory()?it(D):[D]}catch{throw l.file(`Path does not exist: ${f}`,f)}}),n=[...new Set(t)],i=e.map(f=>x.resolve(f)),s=Ye(i.map(f=>{try{return A.statSync(f).isDirectory()?f:x.dirname(f)}catch{return x.dirname(f)}})),r=n.map(f=>{if(s&&s.length>0){let D=x.relative(s,f);if(D&&typeof D=="string"&&!D.startsWith(".."))return D.replace(/\\/g,"/")}return x.basename(f)}),a=new Set(Je(r));if(a.size===0)return[];let p=[],c=[];for(let f=0;f<n.length;f++)a.has(r[f])&&(p.push(n[f]),c.push(r[f]));let u=Xe(c,{flatten:o.pathDetect!==!1}),d=[],I=0,U=ne();for(let f=0;f<p.length;f++){let D=p[f],R=u[f].path;try{tt(R,D);let k=A.statSync(D);if(k.size===0)continue;if(ot(R,D),k.size>U.maxFileSize)throw l.business(`File ${D} is too large. Maximum allowed size is ${U.maxFileSize/(1024*1024)}MB.`);if(I+=k.size,I>U.maxTotalSize)throw l.business(`Total deploy size is too large. Maximum allowed is ${U.maxTotalSize/(1024*1024)}MB.`);let q=A.readFileSync(D),{md5:xt}=await se(q);d.push({path:R,content:q,size:q.length,md5:xt})}catch(k){if(O(k))throw k;let q=k instanceof Error?k.message:String(k);throw l.file(`Failed to read file "${D}": ${q}`,D)}}if(d.length>U.maxFilesCount)throw l.business(`Too many files to deploy. Maximum allowed is ${U.maxFilesCount} files.`);return d}var A,x,rt=F(()=>{"use strict";J();Ee();We();nt();b();ie();Ze();Ae();A=E(require("fs"),1),x=E(require("path"),1)});var wt=require("commander");b();var oe=class{constructor(){this.handlers=new Map}on(o,t){this.handlers.has(o)||this.handlers.set(o,new Set),this.handlers.get(o).add(t)}off(o,t){let n=this.handlers.get(o);n&&(n.delete(t),n.size===0&&this.handlers.delete(o))}emit(o,...t){let n=this.handlers.get(o);if(!n)return;let i=Array.from(n);for(let s of i)try{s(...t)}catch(r){n.delete(s),o!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(o)):this.emit("error",new Error(String(r)),String(o))},0)}}transfer(o){this.handlers.forEach((t,n)=>{t.forEach(i=>{o.on(n,i)})})}clear(){this.handlers.clear()}};var S={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},_t=3e4,B=class extends oe{constructor(t){super();this.globalHeaders={};this.apiUrl=t.apiUrl||K,this.getAuthHeadersCallback=t.getAuthHeaders,this.timeout=t.timeout??_t,this.createDeployBody=t.createDeployBody}setGlobalHeaders(t){this.globalHeaders=t}transferEventsTo(t){this.transfer(t)}async executeRequest(t,n,i){let s=this.mergeHeaders(n.headers),{signal:r,cleanup:a}=this.createTimeoutSignal(n.signal),p={...n,headers:s,credentials:s.Authorization?void 0:"include",signal:r};this.emit("request",t,p);try{let c=await fetch(t,p);return a(),c.ok||await this.handleResponseError(c,i),this.emit("response",this.safeClone(c),t),{data:await this.parseResponse(this.safeClone(c)),status:c.status}}catch(c){a();let u=c instanceof Error?c:new Error(String(c));this.emit("error",u,t),this.handleFetchError(c,i)}}async request(t,n,i){let{data:s}=await this.executeRequest(t,n,i);return s}async requestWithStatus(t,n,i){return this.executeRequest(t,n,i)}mergeHeaders(t={}){return{...this.globalHeaders,...t,...this.getAuthHeadersCallback()}}createTimeoutSignal(t){let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeout);if(t){let s=()=>n.abort();t.addEventListener("abort",s),t.aborted&&n.abort()}return{signal:n.signal,cleanup:()=>clearTimeout(i)}}safeClone(t){try{return t.clone()}catch{return t}}async parseResponse(t){if(!(t.headers.get("Content-Length")==="0"||t.status===204))return t.json()}async handleResponseError(t,n){let i={};try{if(t.headers.get("content-type")?.includes("application/json")){let a=await t.json();if(a&&typeof a=="object"){let p=a;typeof p.message=="string"&&(i.message=p.message),typeof p.error=="string"&&(i.error=p.error)}}else i={message:await t.text()}}catch{i={message:"Failed to parse error response"}}let s=i.message||i.error||`${n} failed`;throw t.status===401?l.authentication(s):l.api(s,t.status)}handleFetchError(t,n){throw O(t)?t:t instanceof Error&&t.name==="AbortError"?l.cancelled(`${n} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?l.network(`${n} failed: ${t.message}`,t):t instanceof Error?l.business(`${n} failed: ${t.message}`):l.business(`${n} failed: Unknown error`)}async deploy(t,n={}){if(!t.length)throw l.business("No files to deploy");for(let a of t)if(!a.md5)throw l.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:i,headers:s}=await this.createDeployBody(t,n.labels,n.via),r={};return n.deployToken?r.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(r.Authorization=`Bearer ${n.apiKey}`),n.caller&&(r["X-Caller"]=n.caller),this.request(`${n.apiUrl||this.apiUrl}${n.endpoint||S.DEPLOYMENTS}`,{method:"POST",body:i,headers:{...s,...r},signal:n.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(t){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(t,n){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:n})},"Update deployment labels")}async removeDeployment(t){await this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove deployment")}async setDomain(t,n,i){let s={};n&&(s.deployment=n),i!==void 0&&(s.labels=i);let{data:r,status:a}=await this.requestWithStatus(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Set domain");return{...r,isCreate:a===201}}async listDomains(){return this.request(`${this.apiUrl}${S.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}`,{method:"GET"},"Get domain")}async removeDomain(t){await this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/share`,{method:"GET"},"Get domain share")}async validateDomain(t){return this.request(`${this.apiUrl}${S.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:t})},"Validate domain")}async createToken(t,n){let i={};return t!==void 0&&(i.ttl=t),n!==void 0&&(i.labels=n),this.request(`${this.apiUrl}${S.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${S.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(t){await this.request(`${this.apiUrl}${S.TOKENS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${S.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${S.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${S.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(t){let n=t.find(a=>a.path==="index.html"||a.path==="/index.html");if(!n||n.size>100*1024)return!1;let i;if(typeof Buffer<"u"&&Buffer.isBuffer(n.content))i=n.content.toString("utf-8");else if(typeof Blob<"u"&&n.content instanceof Blob)i=await n.content.text();else if(typeof File<"u"&&n.content instanceof File)i=await n.content.text();else return!1;let s={files:t.map(a=>a.path),index:i};return(await this.request(`${this.apiUrl}${S.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA check")).isSPA}};b();ie();b();b();function we(e={},o={}){let t={apiUrl:e.apiUrl||o.apiUrl||K,apiKey:e.apiKey!==void 0?e.apiKey:o.apiKey,deployToken:e.deployToken!==void 0?e.deployToken:o.deployToken},n={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(n.apiKey=t.apiKey),t.deployToken!==void 0&&(n.deployToken=t.deployToken),n}function _e(e,o){let t={...e};return t.apiUrl===void 0&&o.apiUrl!==void 0&&(t.apiUrl=o.apiUrl),t.apiKey===void 0&&o.apiKey!==void 0&&(t.apiKey=o.apiKey),t.deployToken===void 0&&o.deployToken!==void 0&&(t.deployToken=o.deployToken),t.timeout===void 0&&o.timeout!==void 0&&(t.timeout=o.timeout),t.maxConcurrency===void 0&&o.maxConcurrency!==void 0&&(t.maxConcurrency=o.maxConcurrency),t.onProgress===void 0&&o.onProgress!==void 0&&(t.onProgress=o.onProgress),t.caller===void 0&&o.caller!==void 0&&(t.caller=o.caller),t}b();Ee();async function Kt(){let o=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(o,"utf-8"):t=new Blob([o],{type:"application/json"});let{md5:n}=await se(t);return{path:Ce,content:t,size:o.length,md5:n}}async function je(e,o,t){if(t.spaDetect===!1||e.some(n=>n.path===Ce))return e;try{if(await o.checkSPA(e)){let i=await Kt();return[...e,i]}}catch{}return e}function Me(e){let{getApi:o,ensureInit:t,processInput:n,clientDefaults:i,hasAuth:s}=e;return{upload:async(r,a={})=>{await t();let p=i?_e(a,i):a;if(s&&!s()&&!p.deployToken&&!p.apiKey)throw l.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw l.config("processInput function is not provided.");let c=o(),u=await n(r,p);return u=await je(u,c,p),c.deploy(u,p)},list:async()=>(await t(),o().listDeployments()),get:async r=>(await t(),o().getDeployment(r)),set:async(r,a)=>(await t(),o().updateDeploymentLabels(r,a.labels)),remove:async r=>{await t(),await o().removeDeployment(r)}}}function Ke(e){let{getApi:o,ensureInit:t}=e;return{set:async(n,i={})=>(await t(),o().setDomain(n,i.deployment,i.labels)),list:async()=>(await t(),o().listDomains()),get:async n=>(await t(),o().getDomain(n)),remove:async n=>{await t(),await o().removeDomain(n)},verify:async n=>(await t(),o().verifyDomain(n)),validate:async n=>(await t(),o().validateDomain(n)),dns:async n=>(await t(),o().getDomainDns(n)),records:async n=>(await t(),o().getDomainRecords(n)),share:async n=>(await t(),o().getDomainShare(n))}}function Be(e){let{getApi:o,ensureInit:t}=e;return{get:async()=>(await t(),o().getAccount())}}function ze(e){let{getApi:o,ensureInit:t}=e;return{create:async(n={})=>(await t(),o().createToken(n.ttl,n.labels)),list:async()=>(await t(),o().listTokens()),remove:async n=>{await t(),await o().removeToken(n)}}}var re=class{constructor(o={}){this.initPromise=null;this._config=null;this.auth=null;this.customHeaders={};this.clientOptions=o,o.deployToken?this.auth={type:"token",value:o.deployToken}:o.apiKey&&(this.auth={type:"apiKey",value:o.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(o);this.http=new B({...o,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=Me({...n,processInput:(i,s)=>this.processInput(i,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=Ke(n),this._account=Be(n),this._tokens=ze(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(o,t){return this.deployments.upload(o,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=ne(),this._config)}on(o,t){this.http.on(o,t)}off(o,t){this.http.off(o,t)}setHeaders(o){this.customHeaders=o,this.http.setGlobalHeaders(o)}clearHeaders(){this.customHeaders={},this.http.setGlobalHeaders({})}replaceHttpClient(o){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(o)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=o,Object.keys(this.customHeaders).length>0&&this.http.setGlobalHeaders(this.customHeaders)}setDeployToken(o){if(!o||typeof o!="string")throw l.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:o}}setApiKey(o){if(!o||typeof o!="string")throw l.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:o}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};b();J();var z=require("zod");b();J();var Te="ship",Bt=z.z.object({apiUrl:z.z.string().url().optional(),apiKey:z.z.string().optional(),deployToken:z.z.string().optional()}).strict();function He(e){try{return Bt.parse(e)}catch(o){if(o instanceof z.z.ZodError){let t=o.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw l.config(`Configuration validation failed${n}: ${t.message}`)}throw l.config("Configuration validation failed")}}async function zt(e){try{if(P()!=="node")return{};let{cosmiconfigSync:o}=await import("cosmiconfig"),t=await import("os"),n=o(Te,{searchPlaces:[`.${Te}rc`,"package.json",`${t.homedir()}/.${Te}rc`],stopDir:t.homedir()}),i;if(e?i=n.load(e):i=n.search(),i&&i.config)return He(i.config)}catch(o){if(O(o))throw o}return{}}async function Ge(e){if(P()!=="node")return{};let o={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await zt(e),n={apiUrl:o.apiUrl??t.apiUrl,apiKey:o.apiKey??t.apiKey,deployToken:o.deployToken??t.deployToken};return He(n)}ie();b();async function Ve(e,o,t){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new n,a=[];for(let d of e){if(!Buffer.isBuffer(d.content)&&!(typeof Blob<"u"&&d.content instanceof Blob))throw l.file(`Unsupported file.content type for Node.js: ${d.path}`,d.path);if(!d.md5)throw l.file(`File missing md5 checksum: ${d.path}`,d.path);let I=new i([d.content],d.path,{type:"application/octet-stream"});r.append("files[]",I),a.push(d.md5)}r.append("checksums",JSON.stringify(a)),o&&o.length>0&&r.append("labels",JSON.stringify(o)),t&&r.append("via",t);let p=new s(r),c=[];for await(let d of p.encode())c.push(Buffer.from(d));let u=Buffer.concat(c);return{body:u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),headers:{"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(u).toString()}}}var le=class extends re{constructor(o={}){if(P()!=="node")throw l.business("Node.js Ship class can only be used in Node.js environment.");super(o)}resolveInitialConfig(o){return we(o,{})}async loadFullConfig(){try{let o=await Ge(this.clientOptions.configFile),t=we(this.clientOptions,o);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let n=new B({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();Ne(i)}catch(o){throw this.initPromise=null,o}}async processInput(o,t){let n=typeof o=="string"?[o]:o;if(!Array.isArray(n)||!n.every(s=>typeof s=="string"))throw l.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw l.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(rt(),st));return i(n,t)}getDeployBodyCreator(){return Ve}};b();var _=require("fs"),de=E(require("path"),1);var Oe=E(require("columnify"),1),m=require("yoctocolors"),at=["isCreate"],v=(e,o,t)=>t?o:e(o),w=(e,o,t)=>{console.log(o?JSON.stringify({success:e},null,2)+`
|
|
3
3
|
`:`${v(m.green,e.toLowerCase().replace(/\.$/,""),t)}
|
|
4
4
|
`)},T=(e,o,t)=>{if(o)console.error(JSON.stringify({error:e},null,2)+`
|
|
5
5
|
`);else{let n=v(s=>(0,m.inverse)((0,m.red)(s)),`${v(m.hidden,"[",t)}error${v(m.hidden,"]",t)}`,t),i=v(m.red,e.toLowerCase().replace(/\.$/,""),t);console.error(`${n} ${i}
|