@shipstatic/ship 2.0.0-beta.4 → 2.0.0-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.d.ts +367 -81
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +27 -27
- 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 +367 -81
- package/dist/index.d.ts +367 -81
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/cli.cjs
CHANGED
|
@@ -1,44 +1,44 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Ut=Object.create;var Z=Object.defineProperty;var Mt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var Gt=Object.getPrototypeOf,Ht=Object.prototype.hasOwnProperty;var P=(e,t)=>()=>(e&&(t=e(e=0)),t);var _e=(e,t)=>{for(var n in t)Z(e,n,{get:t[n],enumerable:!0})},Ue=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of jt(t))!Ht.call(e,s)&&s!==n&&Z(e,s,{get:()=>t[s],enumerable:!(o=Mt(t,s))||o.enumerable});return e};var A=(e,t,n)=>(n=e!=null?Ut(Gt(e)):{},Ue(t||!e||!e.__esModule?Z(n,"default",{value:e,enumerable:!0}):n,e)),zt=e=>Ue(Z({},"__esModule",{value:!0}),e);function I(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function De(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return!1;let n=e.slice(t+1).toLowerCase();return qt.has(n)}function je(e){return Kt.test(e)}function Ee(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>be.has(n))}function Jt(e){return e.startsWith(Ge.PREFIX)?B.API_KEY:e.startsWith(He.PREFIX)?B.DEPLOY_TOKEN:B.OPAQUE}function Be(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n;try{n=JSON.parse(t)}catch(o){throw l.config(`invalid JSON format in config: ${o.message}`,{filePath:$})}if(n===null||typeof n!="object"||Array.isArray(n))throw l.config(`${$} must contain a JSON object`,{filePath:$})}function Ve(e,t,n){if(!e.startsWith(t.PREFIX))throw l.validation(`${n} must start with "${t.PREFIX}"`);if(e.length!==t.TOTAL_LENGTH)throw l.validation(`${n} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let o=e.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(o))throw l.validation(`${n} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function Xt(e){Ve(e,Ge,"API key")}function Yt(e){Ve(e,He,"Deploy token")}function G(e){switch(Jt(e)){case B.API_KEY:Xt(e);return;case B.DEPLOY_TOKEN:Yt(e);return;case B.OPAQUE:if(!e)throw l.validation("Token must be a non-empty string")}}function qe(e){if(!e||e.length>Se.MAX_LENGTH||!Se.PATTERN.test(e))throw l.validation(`Caller must be 1-${Se.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function Ke(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw l.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw l.validation("API URL must not contain a path");if(t.search||t.hash)throw l.validation("API URL must not contain query parameters or fragments")}catch(t){throw I(t)?t:l.validation("API URL must be a valid URL")}}function we(e){if(e==null)return;if(typeof e!="string")throw l.validation("Password must be a string");let t=e.trim();if(t.length<Q.MIN_LENGTH||t.length>Q.MAX_LENGTH)throw l.validation(`Password must be between ${Q.MIN_LENGTH} and ${Q.MAX_LENGTH} characters`);return t}var g,Bt,ye,Vt,l,qt,Kt,be,Me,Ge,He,Se,B,$,ze,ee,M,Je,Q,w=P(()=>{"use strict";g={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},Bt=new Set([g.Network,g.Cancelled,g.File,g.Config]),ye={client:new Set([g.Business,g.Config,g.File,g.Forbidden,g.NotFound,g.RateLimit,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},Vt=new Set(Object.values(g).filter(e=>!Bt.has(e))),l=class e extends Error{type;status;details;constructor(t,n,o,s){super(n),this.type=t,this.status=o,this.details=s,this.name="ShipError"}toResponse(){let t=this.details,n=this.type===g.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:n}}static async fromHttpResponse(t,n){let o,s,i;try{if(t.headers.get("content-type")?.includes("application/json")){let d=await t.json();if(d&&typeof d=="object"){let r=d;typeof r.message=="string"?o=r.message:typeof r.error=="string"&&(o=r.error),s=r.details,typeof r.error=="string"&&Vt.has(r.error)&&(i=r.error)}}else{let d=await t.text();d&&(o=d)}}catch{}let a=t.headers.get("retry-after");if(a!==null){let u=a.trim(),d=/^\d+$/.test(u)?Number(u):Math.ceil((Date.parse(u)-Date.now())/1e3);if(Number.isFinite(d)&&d>=0){let r=s&&typeof s=="object"?s:{};r.retryAfter===void 0&&(s={...r,retryAfter:d})}}o=o||`${n||"Request"} failed with status ${t.status}`;let m=i??(t.status===401?g.Authentication:t.status===403?g.Forbidden:t.status===429?g.RateLimit:g.Api);return new e(m,o,t.status,s)}static fromFetchError(t,n){if(I(t))return t;let o=n||"Request";return t instanceof Error?t.name==="AbortError"?e.cancelled(`${o} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?e.network(`${o} failed: ${t.message}`,{cause:t}):new e(g.Api,`${o} failed: ${t.message}`):new e(g.Api,`${o} failed: Unknown error`)}static validation(t,n){return new e(g.Validation,t,400,n)}static notFound(t,n){let o=n?`${t} ${n} not found`:`${t} not found`;return new e(g.NotFound,o,404)}static forbidden(t,n){return new e(g.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(g.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(g.Authentication,t,401,n)}static business(t,n=400,o){return new e(g.Business,t,n,o)}static network(t,n){return new e(g.Network,t,void 0,n)}static cancelled(t,n){return new e(g.Cancelled,t,void 0,n)}static file(t,n){return new e(g.File,t,void 0,n)}static config(t,n){return new e(g.Config,t,void 0,n)}static api(t,n=500,o){return new e(g.Api,t,n,o)}isClientError(){return ye.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return ye.network.has(this.type)}isAuthError(){return ye.auth.has(this.type)}isType(t){return this.type===t}};qt=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"]);Kt=/[\x00-\x1f\x7f#?%\\<>"]/;be=new Set(["node_modules","package.json"]);Me={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},Ge={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},He={PREFIX:"deploy-",HEX_LENGTH:64,TOTAL_LENGTH:71},Se={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},B={API_KEY:Me.API_KEY,DEPLOY_TOKEN:Me.TOKEN,OPAQUE:"opaque"};$="ship.json",ze={rewrites:[{source:"/(.*)",destination:"/index.html"}]};ee="https://api.shipstatic.com",M={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},Je=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Q={MIN_LENGTH:6,MAX_LENGTH:128}});function Wt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function V(){return Xe||Wt()}var Xe,ne=P(()=>{"use strict";Xe=null});async function sn(e){let t=(await import("spark-md5")).default,n=new t.ArrayBuffer,o=2097152;for(let s=0;s<e.size;s+=o){let i=Math.min(s+o,e.size);n.append(await e.slice(s,i).arrayBuffer())}return{md5:n.end()}}async function rn(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function an(e){let{createHash:t}=await import("crypto"),{createReadStream:n}=await import("fs");return new Promise((o,s)=>{let i=t("md5"),a=n(e);a.on("error",m=>s(l.business(`Failed to read file for MD5: ${m.message}`))),a.on("data",m=>i.update(m)),a.on("end",()=>o({md5:i.digest("hex")}))})}async function le(e){if(e instanceof Blob)return sn(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return rn(e);if(typeof e=="string")return an(e);throw l.business("Invalid input for MD5 calculation")}var xe=P(()=>{"use strict";w()});function ft(e){if(!e||e.length===0)return"";let t=e.filter(i=>i&&typeof i=="string").map(i=>i.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(i=>i.split("/").filter(Boolean)),o=[],s=Math.min(...n.map(i=>i.length));for(let i=0;i<s;i++){let a=n[0][i];if(n.every(m=>m[i]===a))o.push(a);else break}return o.join("/")}function ce(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Le=P(()=>{"use strict"});function ht(e,t={}){if(t.flatten===!1)return e.map(o=>({path:ce(o),name:ke(o)}));let n=pn(e);return e.map(o=>{let s=ce(o);if(n){let i=n.endsWith("/")?n:`${n}/`;s.startsWith(i)&&(s=s.substring(i.length))}return s||(s=ke(o)),{path:s,name:ke(o)}})}function pn(e){if(!e.length)return"";let n=e.map(i=>ce(i)).map(i=>i.split("/")),o=[],s=Math.min(...n.map(i=>i.length));for(let i=0;i<s-1;i++){let a=n[0][i];if(n.every(m=>m[i]===a))o.push(a);else break}return o.join("/")}function ke(e){return e.split(/[/\\]/).pop()||e}var gt=P(()=>{"use strict";Le()});function yt(e){if(je(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 t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,n=e.split("/").pop()||e;return t.test(n)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}var St=P(()=>{"use strict";w()});function bt(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(o=>o&&Ee(o)))throw l.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(n=>{if(!n)return!1;let o=n.replace(/\\/g,"/").split("/").filter(Boolean);if(o.length===0)return!0;let s=o[o.length-1];if((0,Dt.isJunk)(s))return!1;for(let a of o)if(a!==".well-known"&&(a.startsWith(".")||a.length>255))return!1;let i=o.slice(0,-1);for(let a of i)if(cn.some(m=>a.toLowerCase()===m.toLowerCase()))return!1;return!0})}var Dt,cn,Et=P(()=>{"use strict";w();Dt=require("junk"),cn=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function wt(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw l.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function vt(e,t){let n=yt(e);if(!n.valid)throw l.business(n.reason||"Invalid file name");if(De(e))throw l.business(`File extension not allowed: "${t}"`)}var Tt=P(()=>{"use strict";w();St()});var Ot={};_e(Ot,{processFilesForNode:()=>dn});function Ct(e,t=new Set){let n=[],o=x.realpathSync(e);if(t.has(o))return n;t.add(o);let s=x.readdirSync(e);for(let i of s){let a=L.join(e,i),m=x.statSync(a);if(m.isDirectory()){let u=Ct(a,t);n.push(...u)}else m.isFile()&&n.push(a)}return n}async function dn(e,t={},n){if(V()!=="node")throw l.business("processFilesForNode can only be called in Node.js environment.");for(let f of e){let y=L.resolve(f);try{if(x.statSync(y).isDirectory()){let v=x.readdirSync(y).find(T=>be.has(T));if(v)throw l.business(`"${v}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(v){if(I(v))throw v}}let o=e.flatMap(f=>{let y=L.resolve(f);try{return x.statSync(y).isDirectory()?Ct(y):[y]}catch{throw l.file(`Path does not exist: ${f}`,{filePath:f})}}),s=[...new Set(o)],i=e.map(f=>L.resolve(f)),a=ft(i.map(f=>{try{return x.statSync(f).isDirectory()?f:L.dirname(f)}catch{return L.dirname(f)}})),m=s.map(f=>{if(a&&a.length>0){let y=L.relative(a,f);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return L.basename(f)}),d=ht(m,{flatten:t.pathDetect!==!1}).map(f=>f.path),r=new Set(bt(d));if(r.size===0)return[];let p=[],c=[];for(let f=0;f<s.length;f++)r.has(d[f])&&(p.push(s[f]),c.push(d[f]));let h=[],D=0;if(!n)throw l.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let f=0;f<p.length;f++){let y=p[f],v=c[f];try{wt(v,y);let T=x.statSync(y);if(T.size===0)continue;if(vt(v,y),T.size>n.maxFileSize)throw l.business(`File ${y} is too large. Maximum allowed size is ${n.maxFileSize/(1024*1024)}MB.`);if(D+=T.size,D>n.maxTotalSize)throw l.business(`Total deploy size is too large. Maximum allowed is ${n.maxTotalSize/(1024*1024)}MB.`);let k=x.readFileSync(y),{md5:ge}=await le(k);h.push({path:v,content:k,size:k.length,md5:ge})}catch(T){if(I(T))throw T;let k=T instanceof Error?T.message:String(T);throw l.file(`Failed to read file "${y}": ${k}`,{filePath:y})}}if(h.length>n.maxFilesCount)throw l.business(`Too many files to deploy. Maximum allowed is ${n.maxFilesCount} files.`);return h}var x,L,Rt=P(()=>{"use strict";x=A(require("fs"),1),L=A(require("path"),1);w();gt();ne();Et();xe();Le();Tt()});var Ln={};_e(Ln,{buildProgram:()=>_t});module.exports=zt(Ln);var z=require("fs"),fe=A(require("path"),1);w();var U=require("commander"),he=require("yoctocolors");w();var Te=require("zod");var ve=require("zod"),te={apiUrl:ve.z.string().url().optional(),token:ve.z.string().min(1).optional()};ne();var Zt=Te.z.object(te).strict(),Qt={apiUrl:"SHIP_API_URL",token:"SHIP_TOKEN"};function q(){if(V()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL||void 0,token:process.env.SHIP_TOKEN||void 0};try{return Zt.parse(e)}catch(t){if(t instanceof Te.z.ZodError){let n=t.issues[0],o=n.path[0],s=(o&&Qt[o])??"SHIP environment configuration";throw l.config(`Invalid ${s}: ${n.message}`)}throw l.config("Invalid environment configuration")}}var b=A(require("fs"),1),Re=A(require("os"),1),F=A(require("path"),1);var Ce=A(require("columnify"),1),S=require("yoctocolors"),Ye=["isCreate","claim"],C=(e,t,n)=>n?t:e(t),en=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),oe=e=>/^[A-Z][a-z]/.test(e)?e.charAt(0).toLowerCase()+e.slice(1):e,O=(e,t,n)=>{console.log(t?`${JSON.stringify({success:e},null,2)}
|
|
3
|
-
`:`${
|
|
4
|
-
`)},
|
|
5
|
-
`);else{let o=
|
|
2
|
+
"use strict";var jt=Object.create;var Z=Object.defineProperty;var Ht=Object.getOwnPropertyDescriptor;var Bt=Object.getOwnPropertyNames;var zt=Object.getPrototypeOf,Vt=Object.prototype.hasOwnProperty;var P=(e,t)=>()=>(e&&(t=e(e=0)),t);var _e=(e,t)=>{for(var n in t)Z(e,n,{get:t[n],enumerable:!0})},Ue=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Bt(t))!Vt.call(e,s)&&s!==n&&Z(e,s,{get:()=>t[s],enumerable:!(o=Ht(t,s))||o.enumerable});return e};var C=(e,t,n)=>(n=e!=null?jt(zt(e)):{},Ue(t||!e||!e.__esModule?Z(n,"default",{value:e,enumerable:!0}):n,e)),qt=e=>Ue(Z({},"__esModule",{value:!0}),e);function je(e){if(e==null)return;if(typeof e!="string")throw l.validation("Idempotency key must be a string.");let t=e.trim();if(!t)throw l.validation("Idempotency key must not be empty.");if(t.length>Me.MAX_LENGTH)throw l.validation(`Idempotency key must be at most ${Me.MAX_LENGTH} characters.`);return t}function k(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function Se(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return!1;let n=e.slice(t+1).toLowerCase();return Xt.has(n)}function He(e){return Jt.test(e)}function Ee(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>be.has(n))}function Wt(e){return e.startsWith(Be.PREFIX)?z.API_KEY:e.startsWith(ze.PREFIX)?z.DEPLOY_TOKEN:z.OPAQUE}function qe(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n;try{n=JSON.parse(t)}catch(o){throw l.config(`invalid JSON format in config: ${o.message}`,{filePath:N})}if(n===null||typeof n!="object"||Array.isArray(n))throw l.config(`${N} must contain a JSON object`,{filePath:N})}function Ke(e,t,n){if(!e.startsWith(t.PREFIX))throw l.validation(`${n} must start with "${t.PREFIX}"`);if(e.length!==t.TOTAL_LENGTH)throw l.validation(`${n} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let o=e.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(o))throw l.validation(`${n} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function Zt(e){Ke(e,Be,"API key")}function Qt(e){Ke(e,ze,"Deploy token")}function j(e){switch(Wt(e)){case z.API_KEY:Zt(e);return;case z.DEPLOY_TOKEN:Qt(e);return;case z.OPAQUE:if(!e)throw l.validation("Token must be a non-empty string")}}function Ye(e){if(!e||e.length>De.MAX_LENGTH||!De.PATTERN.test(e))throw l.validation(`Caller must be 1-${De.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function Xe(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw l.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw l.validation("API URL must not contain a path");if(t.search||t.hash)throw l.validation("API URL must not contain query parameters or fragments")}catch(t){throw k(t)?t:l.validation("API URL must be a valid URL")}}function Te(e){if(e==null)return;if(typeof e!="string")throw l.validation("Password must be a string");let t=e.trim();if(t.length<Q.MIN_LENGTH||t.length>Q.MAX_LENGTH)throw l.validation(`Password must be between ${Q.MIN_LENGTH} and ${Q.MAX_LENGTH} characters`);return t}var b,Me,g,Kt,ye,Yt,l,Xt,Jt,be,Ge,Be,ze,De,z,N,Ve,ee,M,Je,Q,T=P(()=>{"use strict";b={DEPLOYMENTS:"/deployments",DEPLOYMENT:e=>`/deployments/${e}`,DEPLOYMENT_CONFIG:e=>`/deployments/${e}/config`,DOMAINS:"/domains",DOMAIN:e=>`/domains/${e}`,DOMAIN_VERIFY:e=>`/domains/${e}/verify`,DOMAIN_DNS:e=>`/domains/${e}/dns`,DOMAIN_RECORDS:e=>`/domains/${e}/records`,DOMAIN_SHARE:e=>`/domains/${e}/share`,DOMAIN_PROPAGATION:e=>`/domains/${e}/propagation`,DOMAINS_VALIDATE:"/domains/validate",TOKENS:"/tokens",TOKEN:e=>`/tokens/${e}`,ACCOUNT:"/account",ACCOUNT_KEY:"/account/key",ACCOUNT_CLAIM:"/account/claim",ACTIVITIES:"/activities",LABELS:"/labels",LIMITS:"/limits",PING:"/ping",SETUP:"/setup",SPA_CHECK:"/spa-check",UPLOAD:"/upload"},Me={MAX_LENGTH:256,WINDOW_SECONDS:1440*60};g={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},Kt=new Set([g.Network,g.Cancelled,g.File,g.Config]),ye={client:new Set([g.Business,g.Config,g.File,g.Forbidden,g.NotFound,g.RateLimit,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},Yt=new Set(Object.values(g).filter(e=>!Kt.has(e))),l=class e extends Error{type;status;details;constructor(t,n,o,s){super(n),this.type=t,this.status=o,this.details=s,this.name="ShipError"}toResponse(){let t=this.details,n=this.type===g.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:n}}static async fromHttpResponse(t,n){let o,s,r;try{if(t.headers.get("content-type")?.includes("application/json")){let d=await t.json();if(d&&typeof d=="object"){let i=d;typeof i.message=="string"?o=i.message:typeof i.error=="string"&&(o=i.error),s=i.details,typeof i.error=="string"&&Yt.has(i.error)&&(r=i.error)}}else{let d=await t.text();d&&(o=d)}}catch{}let a=t.headers.get("retry-after");if(a!==null){let u=a.trim(),d=/^\d+$/.test(u)?Number(u):Math.ceil((Date.parse(u)-Date.now())/1e3);if(Number.isFinite(d)&&d>=0){let i=s&&typeof s=="object"?s:{};i.retryAfter===void 0&&(s={...i,retryAfter:d})}}o=o||`${n||"Request"} failed with status ${t.status}`;let m=r??(t.status===401?g.Authentication:t.status===403?g.Forbidden:t.status===429?g.RateLimit:g.Api);return new e(m,o,t.status,s)}static fromFetchError(t,n){if(k(t))return t;let o=n||"Request";return t instanceof Error?t.name==="AbortError"?e.cancelled(`${o} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?e.network(`${o} failed: ${t.message}`,{cause:t}):new e(g.Api,`${o} failed: ${t.message}`):new e(g.Api,`${o} failed: Unknown error`)}static validation(t,n){return new e(g.Validation,t,400,n)}static notFound(t,n){let o=n?`${t} ${n} not found`:`${t} not found`;return new e(g.NotFound,o,404)}static forbidden(t,n){return new e(g.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(g.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(g.Authentication,t,401,n)}static business(t,n=400,o){return new e(g.Business,t,n,o)}static network(t,n){return new e(g.Network,t,void 0,n)}static cancelled(t,n){return new e(g.Cancelled,t,void 0,n)}static file(t,n){return new e(g.File,t,void 0,n)}static config(t,n){return new e(g.Config,t,void 0,n)}static api(t,n=500,o){return new e(g.Api,t,n,o)}isClientError(){return ye.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return ye.network.has(this.type)}isAuthError(){return ye.auth.has(this.type)}isType(t){return this.type===t}};Xt=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"]);Jt=/[\x00-\x1f\x7f#?%\\<>"]/;be=new Set(["node_modules","package.json"]);Ge={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},Be={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},ze={PREFIX:"deploy-",HEX_LENGTH:64,TOTAL_LENGTH:71},De={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},z={API_KEY:Ge.API_KEY,DEPLOY_TOKEN:Ge.TOKEN,OPAQUE:"opaque"};N="ship.json",Ve={rewrites:[{source:"/(.*)",destination:"/index.html"}]};ee="https://api.shipstatic.com",M={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},Je=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Q={MIN_LENGTH:6,MAX_LENGTH:128}});function en(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function V(){return We||en()}var We,ne=P(()=>{"use strict";We=null});async function cn(e){let t=(await import("spark-md5")).default,n=new t.ArrayBuffer,o=2097152;for(let s=0;s<e.size;s+=o){let r=Math.min(s+o,e.size);n.append(await e.slice(s,r).arrayBuffer())}return{md5:n.end()}}async function dn(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function mn(e){let{createHash:t}=await import("crypto"),{createReadStream:n}=await import("fs");return new Promise((o,s)=>{let r=t("md5"),a=n(e);a.on("error",m=>s(l.business(`Failed to read file for MD5: ${m.message}`))),a.on("data",m=>r.update(m)),a.on("end",()=>o({md5:r.digest("hex")}))})}async function le(e){if(e instanceof Blob)return cn(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return dn(e);if(typeof e=="string")return mn(e);throw l.business("Invalid input for MD5 calculation")}var Ie=P(()=>{"use strict";T()});function yt(e){if(!e||e.length===0)return"";let t=e.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(r=>r.split("/").filter(Boolean)),o=[],s=Math.min(...n.map(r=>r.length));for(let r=0;r<s;r++){let a=n[0][r];if(n.every(m=>m[r]===a))o.push(a);else break}return o.join("/")}function ce(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var xe=P(()=>{"use strict"});function Dt(e,t={}){if(t.flatten===!1)return e.map(o=>({path:ce(o),name:Le(o)}));let n=fn(e);return e.map(o=>{let s=ce(o);if(n){let r=n.endsWith("/")?n:`${n}/`;s.startsWith(r)&&(s=s.substring(r.length))}return s||(s=Le(o)),{path:s,name:Le(o)}})}function fn(e){if(!e.length)return"";let n=e.map(r=>ce(r)).map(r=>r.split("/")),o=[],s=Math.min(...n.map(r=>r.length));for(let r=0;r<s-1;r++){let a=n[0][r];if(n.every(m=>m[r]===a))o.push(a);else break}return o.join("/")}function Le(e){return e.split(/[/\\]/).pop()||e}var St=P(()=>{"use strict";xe()});function bt(e){if(He(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 t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,n=e.split("/").pop()||e;return t.test(n)?{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=P(()=>{"use strict";T()});function wt(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(o=>o&&Ee(o)))throw l.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(n=>{if(!n)return!1;let o=n.replace(/\\/g,"/").split("/").filter(Boolean);if(o.length===0)return!0;let s=o[o.length-1];if((0,Tt.isJunk)(s))return!1;for(let a of o)if(a!==".well-known"&&(a.startsWith(".")||a.length>255))return!1;let r=o.slice(0,-1);for(let a of r)if(hn.some(m=>a.toLowerCase()===m.toLowerCase()))return!1;return!0})}var Tt,hn,Ot=P(()=>{"use strict";T();Tt=require("junk"),hn=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Rt(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw l.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function vt(e,t){let n=bt(e);if(!n.valid)throw l.business(n.reason||"Invalid file name");if(Se(e))throw l.business(`File extension not allowed: "${t}"`)}var At=P(()=>{"use strict";T();Et()});var It={};_e(It,{processFilesForNode:()=>gn});function Ct(e,t=new Set){let n=[],o=I.realpathSync(e);if(t.has(o))return n;t.add(o);let s=I.readdirSync(e);for(let r of s){let a=x.join(e,r),m=I.statSync(a);if(m.isDirectory()){let u=Ct(a,t);n.push(...u)}else m.isFile()&&n.push(a)}return n}async function gn(e,t={},n){if(V()!=="node")throw l.business("processFilesForNode can only be called in Node.js environment.");for(let f of e){let y=x.resolve(f);try{if(I.statSync(y).isDirectory()){let O=I.readdirSync(y).find(R=>be.has(R));if(O)throw l.business(`"${O}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(O){if(k(O))throw O}}let o=e.flatMap(f=>{let y=x.resolve(f);try{return I.statSync(y).isDirectory()?Ct(y):[y]}catch{throw l.file(`Path does not exist: ${f}`,{filePath:f})}}),s=[...new Set(o)],r=e.map(f=>x.resolve(f)),a=yt(r.map(f=>{try{return I.statSync(f).isDirectory()?f:x.dirname(f)}catch{return x.dirname(f)}})),m=s.map(f=>{if(a&&a.length>0){let y=x.relative(a,f);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return x.basename(f)}),d=Dt(m,{flatten:t.pathDetect!==!1}).map(f=>f.path),i=new Set(wt(d));if(i.size===0)return[];let p=[],c=[];for(let f=0;f<s.length;f++)i.has(d[f])&&(p.push(s[f]),c.push(d[f]));let h=[],S=0;if(!n)throw l.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let f=0;f<p.length;f++){let y=p[f],O=c[f];try{Rt(O,y);let R=I.statSync(y);if(R.size===0)continue;if(vt(O,y),R.size>n.maxFileSize)throw l.business(`File ${y} is too large. Maximum allowed size is ${n.maxFileSize/(1024*1024)}MB.`);if(S+=R.size,S>n.maxTotalSize)throw l.business(`Total deploy size is too large. Maximum allowed is ${n.maxTotalSize/(1024*1024)}MB.`);let L=I.readFileSync(y),{md5:ge}=await le(L);h.push({path:O,content:L,size:L.length,md5:ge})}catch(R){if(k(R))throw R;let L=R instanceof Error?R.message:String(R);throw l.file(`Failed to read file "${y}": ${L}`,{filePath:y})}}if(h.length>n.maxFilesCount)throw l.business(`Too many files to deploy. Maximum allowed is ${n.maxFilesCount} files.`);return h}var I,x,xt=P(()=>{"use strict";I=C(require("fs"),1),x=C(require("path"),1);T();St();ne();Ot();Ie();xe();At()});var $n={};_e($n,{buildProgram:()=>Gt});module.exports=qt($n);var B=require("fs"),fe=C(require("path"),1);T();var U=require("commander"),he=require("yoctocolors");T();var Oe=require("zod");var we=require("zod"),te={apiUrl:we.z.string().url().optional(),token:we.z.string().min(1).optional()};ne();var tn=Oe.z.object(te).strict(),nn={apiUrl:"SHIP_API_URL",token:"SHIP_TOKEN"};function q(){if(V()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL||void 0,token:process.env.SHIP_TOKEN||void 0};try{return tn.parse(e)}catch(t){if(t instanceof Oe.z.ZodError){let n=t.issues[0],o=n.path[0],s=(o&&nn[o])??"SHIP environment configuration";throw l.config(`Invalid ${s}: ${n.message}`)}throw l.config("Invalid environment configuration")}}var E=C(require("fs"),1),Ae=C(require("os"),1),$=C(require("path"),1);var Re=C(require("columnify"),1),D=require("yoctocolors"),Ze=["isCreate","claim"],v=(e,t,n)=>n?t:e(t),on=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),oe=e=>/^[A-Z][a-z]/.test(e)?e.charAt(0).toLowerCase()+e.slice(1):e,w=(e,t,n)=>{console.log(t?`${JSON.stringify({success:e},null,2)}
|
|
3
|
+
`:`${v(D.green,oe(e).replace(/\.$/,""),n)}
|
|
4
|
+
`)},A=(e,t,n)=>{if(t)console.error(`${JSON.stringify({error:e},null,2)}
|
|
5
|
+
`);else{let o=v(r=>(0,D.inverse)((0,D.red)(r)),`${v(D.hidden,"[",n)}error${v(D.hidden,"]",n)}`,n),s=v(D.red,oe(e).replace(/\.$/,""),n);console.error(`${o} ${s}
|
|
6
6
|
`)}},ie=(e,t,n)=>{if(t)console.log(`${JSON.stringify({warning:e},null,2)}
|
|
7
|
-
`);else{let o=
|
|
8
|
-
`)}},
|
|
9
|
-
`);else{let o=
|
|
10
|
-
`)}},
|
|
7
|
+
`);else{let o=v(r=>(0,D.inverse)((0,D.yellow)(r)),`${v(D.hidden,"[",n)}warning${v(D.hidden,"]",n)}`,n),s=v(D.yellow,oe(e).replace(/\.$/,""),n);console.log(`${o} ${s}
|
|
8
|
+
`)}},G=(e,t,n)=>{if(t)console.log(`${JSON.stringify({info:e},null,2)}
|
|
9
|
+
`);else{let o=v(r=>(0,D.inverse)((0,D.blue)(r)),`${v(D.hidden,"[",n)}info${v(D.hidden,"]",n)}`,n),s=v(D.blue,oe(e).replace(/\.$/,""),n);console.log(`${o} ${s}
|
|
10
|
+
`)}},sn=(e,t="details",n)=>{if(e==null||e===0)return"-";let o=new Date(e*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return t==="table"?o.replace(/T/,v(D.hidden,"T",n)).replace(/Z$/,v(D.hidden,"Z",n)):o},ve=(e,t,n="details",o)=>{if(t===null||Array.isArray(t)&&t.length===0)return"-";if(typeof t=="number"&&(e==="created"||e==="activated"||e==="expires"||e==="linked"||e==="grace"||e==="used"))return sn(t,n,o);if(e==="size"&&typeof t=="number"){let s=t/1048576;return s>=1?`${s.toFixed(1)}Mb`:`${(t/1024).toFixed(1)}Kb`}if(e==="config"||e==="password"){if(typeof t=="boolean")return t?"yes":"no";if(typeof t=="number")return t===1?"yes":"no"}if(on(t)){let s=Object.entries(t);return s.length===0?"-":s.map(([r,a])=>`${r}=${ve(r,a,n,o)}`).join(", ")}return String(t)},Y=(e,t,n,o)=>{if(!e||e.length===0)return"";let s=e[0],r=t||Object.keys(s).filter(u=>s[u]!==void 0&&!Ze.includes(u)),a=e.map(u=>{let d=u,i={};return r.forEach(p=>{p in d&&d[p]!==void 0&&(i[p]=ve(p,d[p],"table",n))}),i});return`${(0,Re.default)(a,{columnSplitter:" ",columns:r,config:r.reduce((u,d)=>(u[d]={headingTransform:i=>v(D.dim,o?.[i]||i,n)},u),{})}).split(`
|
|
11
11
|
`).map(u=>u.replace(/\0/g,"").replace(/\s+$/,"")).join(`
|
|
12
12
|
`)}
|
|
13
|
-
`},K=(e,t)=>{let n=Object.entries(e).filter(([
|
|
14
|
-
`).map(
|
|
13
|
+
`},K=(e,t)=>{let n=Object.entries(e).filter(([r,a])=>Ze.includes(r)?!1:a!==void 0);if(n.length===0)return"";let o=n.map(([r,a])=>({property:`${r}:`,value:ve(r,a,"details",t)}));return`${(0,Re.default)(o,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:r=>v(D.dim,r,t)}}}).split(`
|
|
14
|
+
`).map(r=>r.replace(/\0/g,"")).join(`
|
|
15
15
|
`)}
|
|
16
|
-
`};function
|
|
16
|
+
`};function Qe(){let e=process.env.SHELL||"";return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":null}function et(e,t){switch(e){case"bash":return{completionFile:$.join(t,".ship_completion.bash"),profileFile:$.join(t,".bash_profile"),scriptName:"ship.bash"};case"zsh":return{completionFile:$.join(t,".ship_completion.zsh"),profileFile:$.join(t,".zshrc"),scriptName:"ship.zsh"};case"fish":return{completionFile:$.join(t,".config/fish/completions/ship.fish"),profileFile:null,scriptName:"ship.fish"}}}function tt(e,t={}){let{json:n,noColor:o}=t,s=Qe(),r=Ae.homedir();if(!s){A(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,n,o);return}let a=et(s,r),m=$.join(e,a.scriptName);try{if(s==="fish"){let d=$.dirname(a.completionFile);E.existsSync(d)||E.mkdirSync(d,{recursive:!0}),E.copyFileSync(m,a.completionFile),w("fish completion installed successfully",n,o),G("please restart your shell to apply the changes",n,o);return}E.copyFileSync(m,a.completionFile);let u=`# ship
|
|
17
17
|
source '${a.completionFile}'
|
|
18
18
|
# ship end
|
|
19
|
-
`;if(a.profileFile){if(
|
|
19
|
+
`;if(a.profileFile){if(E.existsSync(a.profileFile)){let d=E.readFileSync(a.profileFile,"utf-8");if(!d.includes("# ship")||!d.includes("# ship end")){let i=d.length>0&&!d.endsWith(`
|
|
20
20
|
`)?`
|
|
21
|
-
`:"";
|
|
22
|
-
`),u=[],d=0,
|
|
23
|
-
`)),
|
|
24
|
-
`);return}let
|
|
25
|
-
`,{mode:384}),(0,
|
|
21
|
+
`:"";E.appendFileSync(a.profileFile,i+u)}}else E.writeFileSync(a.profileFile,u);w(`completion script installed for ${s}`,n,o),ie(`run "source ${a.profileFile}" or restart your shell`,n,o)}}catch(u){let d=u instanceof Error?u.message:String(u);A(`could not install completion script: ${d}`,n,o)}}function nt(e={}){let{json:t,noColor:n}=e,o=Qe(),s=Ae.homedir();if(!o){A(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,t,n);return}let r=et(o,s);try{if(o==="fish"){E.existsSync(r.completionFile)?(E.unlinkSync(r.completionFile),w("fish completion uninstalled successfully",t,n)):ie("fish completion was not installed",t,n),G("please restart your shell to apply the changes",t,n);return}if(E.existsSync(r.completionFile)&&E.unlinkSync(r.completionFile),!r.profileFile)return;if(!E.existsSync(r.profileFile)){A("profile file not found",t,n);return}let m=E.readFileSync(r.profileFile,"utf-8").split(`
|
|
22
|
+
`),u=[],d=0,i=!1;for(;d<m.length;)if(m[d].trim()==="# ship"){for(i=!0,d++;d<m.length&&m[d].trim()!=="# ship end";)d++;d<m.length&&d++}else u.push(m[d]),d++;i?(E.writeFileSync(r.profileFile,u.join(`
|
|
23
|
+
`)),w(`completion script uninstalled for ${o}`,t,n),ie(`run "source ${r.profileFile}" or restart your shell`,t,n)):A("completion was not found in profile",t,n)}catch(a){let m=a instanceof Error?a.message:String(a);A(`could not uninstall completion script: ${m}`,t,n)}}var F=require("fs"),st=require("os"),rt=require("path"),at=require("readline/promises");T();var se=require("yoctocolors"),H=(0,rt.join)((0,st.homedir)(),".shiprc");function ot(e){return e.length<13?"...":`${e.slice(0,9)}...${e.slice(-4)}`}function it(){try{return(0,F.existsSync)(H)?JSON.parse((0,F.readFileSync)(H,"utf-8")):{}}catch{return{}}}async function lt(e={}){let{noColor:t,json:n}=e,o=i=>t?i:(0,se.dim)(i),s=i=>t?i:(0,se.green)(i);if(n){let i=it(),p=typeof i.token=="string"?i.token:void 0,c=typeof i.apiUrl=="string"?i.apiUrl:void 0;console.log(`${JSON.stringify({path:H,exists:(0,F.existsSync)(H),...p?{token:ot(p)}:{},...c&&c!==ee?{apiUrl:c}:{}},null,2)}
|
|
24
|
+
`);return}let r=it(),a=typeof r.token=="string"?r.token:void 0,m=(0,at.createInterface)({input:process.stdin,output:process.stdout});console.log(""),console.log(` ${o("Create a free API key at")} https://my.shipstatic.com/api-key`),console.log("");let u=a?` Token (${o(ot(a))}): `:" Token: ",d;try{d=(await m.question(u)).trim()}finally{m.close()}d&&(j(d),r.token=d),(0,F.writeFileSync)(H,`${JSON.stringify(r,null,2)}
|
|
25
|
+
`,{mode:384}),(0,F.chmodSync)(H,384),console.log(`
|
|
26
26
|
${s("saved to")} ${o(H)}
|
|
27
|
-
`)}w();w();w();var re=class{constructor(){this.handlers=new Map}on(t,n){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(n)}off(t,n){let o=this.handlers.get(t);o&&(o.delete(n),o.size===0&&this.handlers.delete(t))}emit(t,...n){let o=this.handlers.get(t);if(!o)return;let s=Array.from(o);for(let i of s)try{i(...n)}catch(a){o.delete(i),t!=="error"&&setTimeout(()=>{let m=a instanceof Error?a:new Error(String(a));this.emit("error",m,String(t))},0)}}};w();w();function X(e){if(e==null)return;if(e.length===0)return e;if(e.length>M.MAX_COUNT)throw l.validation(`Maximum ${M.MAX_COUNT} labels allowed`);let t=e.map((o,s)=>{if(typeof o!="string")throw l.validation(`Label at index ${s} must be a string`);let i=o.trim().toLowerCase();if(i.length<M.MIN_LENGTH)throw l.validation(`Labels must be at least ${M.MIN_LENGTH} characters long`);if(i.length>M.MAX_LENGTH)throw l.validation(`Labels must be no more than ${M.MAX_LENGTH} characters long`);if(!Je.test(i))throw l.validation(`Labels must start and end with alphanumeric characters, with optional separators (${M.SEPARATORS}) between segments`);return i}),n=[...new Set(t)];if(n.length!==t.length)throw l.validation("Duplicate labels are not allowed");return n}async function at(e){let t=e.find(s=>s.path===$||s.path===`/${$}`);if(!t)return;let n=t.content,o=typeof n.text=="function"?await n.text():t.content.toString("utf8");Be(o)}var E={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},nn=3e4,on="sdk";function Ae(e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor!==void 0&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}var ae=class extends re{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||ee,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??nn,this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.createDeployBody=n.createDeployBody,this.deployEndpoint=n.deployEndpoint||E.DEPLOYMENTS}setGlobalHeaders(n){this.globalHeaders=n}async executeRequest(n,o,s){let i=()=>{};try{let a=await this.mergeHeaders(o.headers),m=this.createTimeoutSignal(o.signal);i=m.cleanup;let u={...o,headers:a,credentials:this.session&&!a.Authorization?"include":void 0,signal:m.signal};this.emit("request",n,u);let d=await this.fetch(n,u);if(i(),!d.ok)throw await l.fromHttpResponse(d,s);return this.emit("response",this.safeClone(d),n),{data:await this.parseResponse(this.safeClone(d)),status:d.status}}catch(a){i();let m=l.fromFetchError(a,s);throw this.emit("error",m,n),m}}async request(n,o,s){let{data:i}=await this.executeRequest(n,o,s);return i}async requestWithStatus(n,o,s){return this.executeRequest(n,o,s)}async mergeHeaders(n={}){return{...this.globalHeaders,...this.caller?{"X-Caller":this.caller}:{},...await this.getAuthHeadersCallback(),...n}}createTimeoutSignal(n){let o=new AbortController,s=setTimeout(()=>o.abort(),this.timeout);if(n){let i=()=>o.abort();n.addEventListener("abort",i),n.aborted&&o.abort()}return{signal:o.signal,cleanup:()=>clearTimeout(s)}}safeClone(n){try{return n.clone()}catch{return n}}async parseResponse(n){if(!(n.headers.get("Content-Length")==="0"||n.status===204))return n.json()}async deploy(n,o={}){if(!n.length)throw l.business("No files to deploy");for(let u of n)if(!u.md5)throw l.file(`MD5 checksum missing for file: ${u.path}`,{filePath:u.path});we(o.password);let s=X(o.labels);await at(n);let i=o.build||o.prerender||o.spa?{build:o.build,prerender:o.prerender,spa:o.spa}:void 0,{body:a,headers:m}=await this.createDeployBody(n,{labels:s,via:o.via??on,password:o.password,flags:i,captcha:o.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:a,headers:m,signal:o.signal||null},"Deploy")}async listDeployments(n){return this.request(`${this.apiUrl}${E.DEPLOYMENTS}${Ae(n)}`,{method:"GET"},"List deployments")}async getDeployment(n){return this.request(`${this.apiUrl}${E.DEPLOYMENTS}/${encodeURIComponent(n)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(n,o){let s=X(o);return this.request(`${this.apiUrl}${E.DEPLOYMENTS}/${encodeURIComponent(n)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:s})},"Update deployment labels")}async removeDeployment(n){await this.request(`${this.apiUrl}${E.DEPLOYMENTS}/${encodeURIComponent(n)}`,{method:"DELETE"},"Remove deployment")}async setDomain(n,o,s){let i=X(s),a={};o&&(a.deployment=o),i!==void 0&&(a.labels=i);let{data:m,status:u}=await this.requestWithStatus(`${this.apiUrl}${E.DOMAINS}/${encodeURIComponent(n)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)},"Set domain");return{...m,isCreate:u===201}}async listDomains(n){return this.request(`${this.apiUrl}${E.DOMAINS}${Ae(n)}`,{method:"GET"},"List domains")}async getDomain(n){return this.request(`${this.apiUrl}${E.DOMAINS}/${encodeURIComponent(n)}`,{method:"GET"},"Get domain")}async removeDomain(n){await this.request(`${this.apiUrl}${E.DOMAINS}/${encodeURIComponent(n)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(n){return this.request(`${this.apiUrl}${E.DOMAINS}/${encodeURIComponent(n)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(n){return this.request(`${this.apiUrl}${E.DOMAINS}/${encodeURIComponent(n)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(n){return this.request(`${this.apiUrl}${E.DOMAINS}/${encodeURIComponent(n)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(n){return this.request(`${this.apiUrl}${E.DOMAINS}/${encodeURIComponent(n)}/share`,{method:"GET"},"Get domain share")}async validateDomain(n){return this.request(`${this.apiUrl}${E.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:n})},"Validate domain")}async createToken(n,o){let s=X(o),i={};return n!==void 0&&(i.ttl=n),s!==void 0&&(i.labels=s),this.request(`${this.apiUrl}${E.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(n){return this.request(`${this.apiUrl}${E.TOKENS}${Ae(n)}`,{method:"GET"},"List tokens")}async removeToken(n){await this.request(`${this.apiUrl}${E.TOKENS}/${encodeURIComponent(n)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${E.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${E.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return(await this.request(`${this.apiUrl}${E.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(n,o={}){let s=n.find(u=>u.path==="index.html"||u.path==="/index.html");if(!s||s.size>100*1024)return!1;let i;if(typeof Buffer<"u"&&Buffer.isBuffer(s.content))i=s.content.toString("utf-8");else if(typeof Blob<"u"&&s.content instanceof Blob)i=await s.content.text();else if(typeof File<"u"&&s.content instanceof File)i=await s.content.text();else return!1;let a={files:n.map(u=>u.path),index:i};return(await this.request(`${this.apiUrl}${E.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)},"SPA check")).isSPA}};w();w();xe();async function ln(){let e=JSON.stringify(ze,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await le(t);return{path:$,content:t,size:e.length,md5:n}}async function lt(e,t,n){if(n.spaDetect===!1||n.spa||n.build||n.prerender||e.some(o=>o.path===$))return e;try{if(await t.checkSPA(e,n)){let s=await ln();return[...e,s]}}catch{}return e}function pt(e){let{getApi:t,ensureInit:n,processInput:o}=e;return{upload:async(s,i={})=>{if(await n(),!o)throw l.config("processInput function is not provided.");let a=t(),m=await o(s,i);return m=await lt(m,a,i),a.deploy(m,i)},list:async s=>(await n(),t().listDeployments(s)),get:async s=>(await n(),t().getDeployment(s)),set:async(s,i)=>(await n(),t().updateDeploymentLabels(s,i.labels)),remove:async s=>{await n(),await t().removeDeployment(s)}}}function ct(e){let{getApi:t,ensureInit:n}=e;return{set:async(o,s={})=>(await n(),t().setDomain(o,s.deployment,s.labels)),list:async o=>(await n(),t().listDomains(o)),get:async o=>(await n(),t().getDomain(o)),remove:async o=>{await n(),await t().removeDomain(o)},verify:async o=>(await n(),t().verifyDomain(o)),validate:async o=>(await n(),t().validateDomain(o)),dns:async o=>(await n(),t().getDomainDns(o)),records:async o=>(await n(),t().getDomainRecords(o)),share:async o=>(await n(),t().getDomainShare(o))}}function dt(e){let{getApi:t,ensureInit:n}=e;return{get:async()=>(await n(),t().getAccount())}}function mt(e){let{getApi:t,ensureInit:n}=e;return{create:async(o={})=>(await n(),t().createToken(o.ttl,o.labels)),list:async o=>(await n(),t().listTokens(o)),remove:async o=>{await n(),await t().removeToken(o)}}}var pe=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.credential=null;if(t={...t,apiUrl:t.apiUrl||void 0,token:t.token||void 0,caller:t.caller||void 0},this.clientOptions=t,t.caller!==void 0&&qe(t.caller),t.token&&t.session)throw l.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(G(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new ae({...t,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=pt({...n,processInput:(o,s)=>this.processInput(o,s)}),this.domains=ct(n),this.account=dt(n),this.tokens=mt(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(t){throw this.initPromise=null,t}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,n){return this.deployments.upload(t,n)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,n){this.http.on(t,n)}off(t,n){this.http.off(t,n)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw l.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw l.business("Invalid token provided. Token must be a non-empty string.");G(t),this.credential=t;return}if(typeof t!="function")throw l.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw l.authentication("Token provider returned no token.");if(typeof t!="string")throw l.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};ne();w();async function ut(e,t={}){let{FormData:n,File:o}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),{labels:i,via:a,password:m,flags:u,captcha:d}=t,r=new n,p=[];for(let f of e){if(!Buffer.isBuffer(f.content)&&!(typeof Blob<"u"&&f.content instanceof Blob))throw l.file(`Unsupported file.content type for Node.js: ${f.path}`,{filePath:f.path});if(!f.md5)throw l.file(`File missing md5 checksum: ${f.path}`,{filePath:f.path});let y=new o([f.content],f.path,{type:"application/octet-stream"});r.append("files[]",y),p.push(f.md5)}r.append("checksums",JSON.stringify(p)),i&&i.length>0&&r.append("labels",JSON.stringify(i)),a&&r.append("via",a),m&&r.append("password",m),u?.build&&r.append("build","true"),u?.prerender&&r.append("prerender","true"),u?.spa&&r.append("spa","true"),d&&r.append("captcha",d);let c=new s(r),h=[];for await(let f of c.encode())h.push(Buffer.from(f));let D=Buffer.concat(h);return{body:D.buffer.slice(D.byteOffset,D.byteOffset+D.byteLength),headers:{"Content-Type":c.contentType,"Content-Length":Buffer.byteLength(D).toString()}}}var de=class extends pe{constructor(t={}){if(V()!=="node")throw l.business("Node.js Ship class can only be used in Node.js environment.");let n=q();super({...t,apiUrl:t.apiUrl||n.apiUrl,token:t.token||(t.session?void 0:n.token)})}async deploy(t,n){return super.deploy(t,n)}async processInput(t,n){let o=typeof t=="string"?[t]:t;if(!Array.isArray(o)||!o.every(i=>typeof i=="string"))throw l.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw l.business("No files to deploy.");let{processFilesForNode:s}=await Promise.resolve().then(()=>(Rt(),Ot));return s(o,n,this.platformLimits??void 0)}getDeployBodyCreator(){return ut}};var At=require("os");w();var xt=require("cosmiconfig"),Pe=require("zod");var mn=Pe.z.object(te).strict(),Ie="ship";function me(e){let t=e||void 0,n=(0,At.homedir)(),o=(0,xt.cosmiconfigSync)(Ie,{searchPlaces:[`.${Ie}rc`,"package.json",`${n}/.${Ie}rc`],stopDir:n}),s;try{s=t?o.load(t):o.search()}catch(i){if(I(i))throw i;let a=i instanceof Error?i.message:String(i),m=t?` (${t})`:"";throw l.config(`Failed to read ship config${m}: ${a}`)}if(!s?.config)return{};try{return mn.parse(s.config)}catch(i){if(i instanceof Pe.z.ZodError){let a=i.issues[0];if(a.code==="unrecognized_keys"){let u=a.keys.filter(d=>d==="apiKey"||d==="deployToken");if(u.length>0){let d=u.map(r=>`"${r}"`).join(" and ");throw l.config(`Invalid config in ${s.filepath}: ${d} ${u.length>1?"are":"is"} no longer supported \u2014 the key is now "token". Run \`ship config\` to rewrite it.`)}}let m=a.path.length>0?` at ${a.path.join(".")}`:"";throw l.config(`Invalid config in ${s.filepath}${m}: ${a.message}`)}throw l.config(`Invalid config in ${s.filepath}`)}}function $e(e,t,n){return{apiUrl:e.apiUrl||t.apiUrl||n.apiUrl,token:e.token||t.token||n.token}}function Lt(e={}){return new de($e(e,q(),me(e.config)))}w();function kt(e){return I(e)?e:e instanceof Error?l.business(e.message):l.business(String(e??"Unknown error"))}function It(e,t,n){return e.isAuthError()?n?.token?"authentication failed: invalid or expired token":"authentication required: pass --token, set SHIP_TOKEN, or run ship config":e.isNetworkError()?"network error: could not reach the API. check your internet connection":e.isClientError()?e.message:"server error: please try again or check https://status.shipstatic.com"}function Pt(e,t){return JSON.stringify({error:e,...t?{details:t}:{}},null,2)}var Fe=(e,t)=>`https://setup.shipstatic.com/${e}/${t}`;function un(e,t,n){let{noColor:o}=n;if(e.deployments.length===0){console.log("no deployments found"),console.log();return}let s=["deployment","labels","files","size","created","via"];console.log(J(e.deployments,s,o)),Ne(e.cursor,o)}function Ne(e,t){e&&j(`more results available \u2014 rerun with --cursor ${e}`,!1,t)}function fn(e,t,n){let{noColor:o}=n;if(e.domains.length===0){console.log("no domains found"),console.log();return}let s=["domain","deployment","labels","linked","links","created"];console.log(J(e.domains,s,o)),Ne(e.cursor,o)}function hn(e,t,n){let{noColor:o}=n,{_dnsRecords:s,_shareHash:i,isCreate:a,...m}=e;if(t.operation==="set"){let u=a?"created":"updated";O(`${e.url} domain ${u}`,!1,o)}s&&s.length>0&&(console.log(),j("DNS Records to configure:",!1,o),s.forEach(u=>{console.log(` ${u.type}: ${u.name} \u2192 ${u.value}`)})),i&&(console.log(),j(`Setup instructions: ${Fe(i,e.domain)}`,!1,o)),console.log(K(m,o))}function gn(e,t,n){let{noColor:o}=n;t.operation==="upload"&&O(`${e.url} deployment uploaded`,!1,o),console.log(K(e,o));let s=e.claim;if(s){let i=e.expires?Math.round((e.expires-e.created)/86400):null;console.log(`IMPORTANT: this deployment${i?` expires in ${i} day${i!==1?"s":""}`:" will expire"}, claim it to keep permanently:
|
|
27
|
+
`)}T();T();T();var re=class{constructor(){this.handlers=new Map}on(t,n){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(n)}off(t,n){let o=this.handlers.get(t);o&&(o.delete(n),o.size===0&&this.handlers.delete(t))}emit(t,...n){let o=this.handlers.get(t);if(!o)return;let s=Array.from(o);for(let r of s)try{r(...n)}catch(a){o.delete(r),t!=="error"&&setTimeout(()=>{let m=a instanceof Error?a:new Error(String(a));this.emit("error",m,String(t))},0)}}};T();T();function X(e){if(e==null)return;if(e.length===0)return e;if(e.length>M.MAX_COUNT)throw l.validation(`Maximum ${M.MAX_COUNT} labels allowed`);let t=e.map((o,s)=>{if(typeof o!="string")throw l.validation(`Label at index ${s} must be a string`);let r=o.trim().toLowerCase();if(r.length<M.MIN_LENGTH)throw l.validation(`Labels must be at least ${M.MIN_LENGTH} characters long`);if(r.length>M.MAX_LENGTH)throw l.validation(`Labels must be no more than ${M.MAX_LENGTH} characters long`);if(!Je.test(r))throw l.validation(`Labels must start and end with alphanumeric characters, with optional separators (${M.SEPARATORS}) between segments`);return r}),n=[...new Set(t)];if(n.length!==t.length)throw l.validation("Duplicate labels are not allowed");return n}async function pt(e){let t=e.find(s=>s.path===N||s.path===`/${N}`);if(!t)return;let n=t.content,o=typeof n.text=="function"?await n.text():t.content.toString("utf8");qe(o)}var rn=3e4,ct=3e5,an=3e5,ln=ct+an,pn="sdk";function Ce(e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor!==void 0&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}var ae=class extends re{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||ee,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??rn,this.deployTimeout=n.timeout??ct,this.deployBuildTimeout=n.timeout??ln,this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.createDeployBody=n.createDeployBody,this.deployEndpoint=n.deployEndpoint||b.DEPLOYMENTS}setGlobalHeaders(n){this.globalHeaders=n}async executeRequest(n,o,s,r=this.timeout){let a=()=>{};try{let m=await this.mergeHeaders(o.headers),u=this.createTimeoutSignal(o.signal,r);a=u.cleanup;let d={...o,headers:m,credentials:this.session&&!m.Authorization?"include":void 0,signal:u.signal};this.emit("request",n,d);let i=await this.fetch(n,d);if(a(),!i.ok)throw await l.fromHttpResponse(i,s);return this.emit("response",this.safeClone(i),n),{data:await this.parseResponse(this.safeClone(i)),status:i.status}}catch(m){a();let u=l.fromFetchError(m,s);throw this.emit("error",u,n),u}}async request(n,o,s,r){let{data:a}=await this.executeRequest(n,o,s,r);return a}async requestWithStatus(n,o,s){return this.executeRequest(n,o,s)}async mergeHeaders(n={}){return{...this.globalHeaders,...this.caller?{"X-Caller":this.caller}:{},...await this.getAuthHeadersCallback(),...n}}createTimeoutSignal(n,o=this.timeout){let s=new AbortController,r=setTimeout(()=>s.abort(),o);if(n){let a=()=>s.abort();n.addEventListener("abort",a),n.aborted&&s.abort()}return{signal:s.signal,cleanup:()=>clearTimeout(r)}}safeClone(n){try{return n.clone()}catch{return n}}async parseResponse(n){if(!(n.headers.get("Content-Length")==="0"||n.status===204))return n.json()}async deploy(n,o={}){if(!n.length)throw l.business("No files to deploy");for(let d of n)if(!d.md5)throw l.file(`MD5 checksum missing for file: ${d.path}`,{filePath:d.path});Te(o.password);let s=je(o.idempotencyKey),r=X(o.labels);await pt(n);let a=o.build||o.prerender||o.spa?{build:o.build,prerender:o.prerender,spa:o.spa}:void 0,{body:m,headers:u}=await this.createDeployBody(n,{labels:r,via:o.via??pn,password:o.password,flags:a,captcha:o.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:m,headers:s?{...u,"Idempotency-Key":s}:u,signal:o.signal||null},"Deploy",o.build||o.prerender?this.deployBuildTimeout:this.deployTimeout)}async listDeployments(n){return this.request(`${this.apiUrl}${b.DEPLOYMENTS}${Ce(n)}`,{method:"GET"},"List deployments")}async getDeployment(n){return this.request(`${this.apiUrl}${b.DEPLOYMENT(encodeURIComponent(n))}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(n,o){let s=X(o);return this.request(`${this.apiUrl}${b.DEPLOYMENT(encodeURIComponent(n))}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:s})},"Update deployment labels")}async removeDeployment(n){return this.request(`${this.apiUrl}${b.DEPLOYMENT(encodeURIComponent(n))}`,{method:"DELETE"},"Remove deployment")}async setDomain(n,o,s){let r=X(s),a={};o&&(a.deployment=o),r!==void 0&&(a.labels=r);let{data:m,status:u}=await this.requestWithStatus(`${this.apiUrl}${b.DOMAIN(encodeURIComponent(n))}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)},"Set domain");return{...m,isCreate:u===201}}async listDomains(n){return this.request(`${this.apiUrl}${b.DOMAINS}${Ce(n)}`,{method:"GET"},"List domains")}async getDomain(n){return this.request(`${this.apiUrl}${b.DOMAIN(encodeURIComponent(n))}`,{method:"GET"},"Get domain")}async removeDomain(n){return this.request(`${this.apiUrl}${b.DOMAIN(encodeURIComponent(n))}`,{method:"DELETE"},"Remove domain")}async verifyDomain(n){return this.request(`${this.apiUrl}${b.DOMAIN_VERIFY(encodeURIComponent(n))}`,{method:"POST"},"Verify domain")}async getDomainDns(n){return this.request(`${this.apiUrl}${b.DOMAIN_DNS(encodeURIComponent(n))}`,{method:"GET"},"Get domain DNS")}async getDomainRecords(n){return this.request(`${this.apiUrl}${b.DOMAIN_RECORDS(encodeURIComponent(n))}`,{method:"GET"},"Get domain records")}async getDomainShare(n){return this.request(`${this.apiUrl}${b.DOMAIN_SHARE(encodeURIComponent(n))}`,{method:"GET"},"Get domain share")}async validateDomain(n){return this.request(`${this.apiUrl}${b.DOMAINS_VALIDATE}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:n})},"Validate domain")}async createToken(n,o){let s=X(o),r={};return n!==void 0&&(r.ttl=n),s!==void 0&&(r.labels=s),this.request(`${this.apiUrl}${b.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"Create token")}async listTokens(n){return this.request(`${this.apiUrl}${b.TOKENS}${Ce(n)}`,{method:"GET"},"List tokens")}async removeToken(n){return this.request(`${this.apiUrl}${b.TOKEN(encodeURIComponent(n))}`,{method:"DELETE"},"Remove token")}async getToken(n){return this.request(`${this.apiUrl}${b.TOKEN(encodeURIComponent(n))}`,{method:"GET"},"Get token")}async getAccount(){return this.request(`${this.apiUrl}${b.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${b.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return(await this.request(`${this.apiUrl}${b.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(n,o={}){let s=n.find(u=>u.path==="index.html"||u.path==="/index.html");if(!s||s.size>100*1024)return!1;let r;if(typeof Buffer<"u"&&Buffer.isBuffer(s.content))r=s.content.toString("utf-8");else if(typeof Blob<"u"&&s.content instanceof Blob)r=await s.content.text();else if(typeof File<"u"&&s.content instanceof File)r=await s.content.text();else return!1;let a={files:n.map(u=>u.path),index:r};return(await this.request(`${this.apiUrl}${b.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)},"SPA check")).isSPA}};T();T();Ie();async function un(){let e=JSON.stringify(Ve,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await le(t);return{path:N,content:t,size:e.length,md5:n}}async function dt(e,t,n){if(n.spaDetect===!1||n.spa||n.build||n.prerender||e.some(o=>o.path===N))return e;try{if(await t.checkSPA(e,n)){let s=await un();return[...e,s]}}catch{}return e}function mt(e){let{getApi:t,ensureInit:n,processInput:o}=e;return{upload:async(s,r={})=>{if(await n(),!o)throw l.config("processInput function is not provided.");let a=t(),m=await o(s,r);return m=await dt(m,a,r),a.deploy(m,r)},list:async s=>(await n(),t().listDeployments(s)),get:async s=>(await n(),t().getDeployment(s)),set:async(s,r)=>(await n(),t().updateDeploymentLabels(s,r.labels)),remove:async s=>(await n(),t().removeDeployment(s))}}function ut(e){let{getApi:t,ensureInit:n}=e;return{set:async(o,s={})=>(await n(),t().setDomain(o,s.deployment,s.labels)),list:async o=>(await n(),t().listDomains(o)),get:async o=>(await n(),t().getDomain(o)),remove:async o=>(await n(),t().removeDomain(o)),verify:async o=>(await n(),t().verifyDomain(o)),validate:async o=>(await n(),t().validateDomain(o)),dns:async o=>(await n(),t().getDomainDns(o)),records:async o=>(await n(),t().getDomainRecords(o)),share:async o=>(await n(),t().getDomainShare(o))}}function ft(e){let{getApi:t,ensureInit:n}=e;return{get:async()=>(await n(),t().getAccount())}}function ht(e){let{getApi:t,ensureInit:n}=e;return{create:async(o={})=>(await n(),t().createToken(o.ttl,o.labels)),list:async o=>(await n(),t().listTokens(o)),get:async o=>(await n(),t().getToken(o)),remove:async o=>(await n(),t().removeToken(o))}}var pe=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.credential=null;if(t={...t,apiUrl:t.apiUrl||void 0,token:t.token||void 0,caller:t.caller||void 0},this.clientOptions=t,t.caller!==void 0&&Ye(t.caller),t.token&&t.session)throw l.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(j(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new ae({...t,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=mt({...n,processInput:(o,s)=>this.processInput(o,s)}),this.domains=ut(n),this.account=ft(n),this.tokens=ht(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(t){throw this.initPromise=null,t}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,n){return this.deployments.upload(t,n)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,n){this.http.on(t,n)}off(t,n){this.http.off(t,n)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw l.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw l.business("Invalid token provided. Token must be a non-empty string.");j(t),this.credential=t;return}if(typeof t!="function")throw l.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw l.authentication("Token provider returned no token.");if(typeof t!="string")throw l.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};ne();T();async function gt(e,t={}){let{FormData:n,File:o}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),{labels:r,via:a,password:m,flags:u,captcha:d}=t,i=new n,p=[];for(let f of e){if(!Buffer.isBuffer(f.content)&&!(typeof Blob<"u"&&f.content instanceof Blob))throw l.file(`Unsupported file.content type for Node.js: ${f.path}`,{filePath:f.path});if(!f.md5)throw l.file(`File missing md5 checksum: ${f.path}`,{filePath:f.path});let y=new o([f.content],f.path,{type:"application/octet-stream"});i.append("files[]",y),p.push(f.md5)}i.append("checksums",JSON.stringify(p)),r&&r.length>0&&i.append("labels",JSON.stringify(r)),a&&i.append("via",a),m&&i.append("password",m),u?.build&&i.append("build","true"),u?.prerender&&i.append("prerender","true"),u?.spa&&i.append("spa","true"),d&&i.append("captcha",d);let c=new s(i),h=[];for await(let f of c.encode())h.push(Buffer.from(f));let S=Buffer.concat(h);return{body:S.buffer.slice(S.byteOffset,S.byteOffset+S.byteLength),headers:{"Content-Type":c.contentType,"Content-Length":Buffer.byteLength(S).toString()}}}var de=class extends pe{constructor(t={}){if(V()!=="node")throw l.business("Node.js Ship class can only be used in Node.js environment.");let n=q();super({...t,apiUrl:t.apiUrl||n.apiUrl,token:t.token||(t.session?void 0:n.token)})}async deploy(t,n){return super.deploy(t,n)}async processInput(t,n){let o=typeof t=="string"?[t]:t;if(!Array.isArray(o)||!o.every(r=>typeof r=="string"))throw l.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw l.business("No files to deploy.");let{processFilesForNode:s}=await Promise.resolve().then(()=>(xt(),It));return s(o,n,this.platformLimits??void 0)}getDeployBodyCreator(){return gt}};var Lt=require("os");T();var kt=require("cosmiconfig"),Pe=require("zod");var yn=Pe.z.object(te).strict(),ke="ship";function me(e){let t=e||void 0,n=(0,Lt.homedir)(),o=(0,kt.cosmiconfigSync)(ke,{searchPlaces:[`.${ke}rc`,"package.json",`${n}/.${ke}rc`],stopDir:n}),s;try{s=t?o.load(t):o.search()}catch(r){if(k(r))throw r;let a=r instanceof Error?r.message:String(r),m=t?` (${t})`:"";throw l.config(`Failed to read ship config${m}: ${a}`)}if(!s?.config)return{};try{return yn.parse(s.config)}catch(r){if(r instanceof Pe.z.ZodError){let a=r.issues[0];if(a.code==="unrecognized_keys"){let u=a.keys.filter(d=>d==="apiKey"||d==="deployToken");if(u.length>0){let d=u.map(i=>`"${i}"`).join(" and ");throw l.config(`Invalid config in ${s.filepath}: ${d} ${u.length>1?"are":"is"} no longer supported \u2014 the key is now "token". Run \`ship config\` to rewrite it.`)}}let m=a.path.length>0?` at ${a.path.join(".")}`:"";throw l.config(`Invalid config in ${s.filepath}${m}: ${a.message}`)}throw l.config(`Invalid config in ${s.filepath}`)}}function Ne(e,t,n){return{apiUrl:e.apiUrl||t.apiUrl||n.apiUrl,token:e.token||t.token||n.token}}function Pt(e={}){return new de(Ne(e,q(),me(e.config)))}T();function Nt(e){return k(e)?e:e instanceof Error?l.business(e.message):l.business(String(e??"Unknown error"))}function $t(e,t,n){return e.isAuthError()?n?.token?"authentication failed: invalid or expired token":"authentication required: pass --token, set SHIP_TOKEN, or run ship config":e.isNetworkError()?"network error: could not reach the API. check your internet connection":e.isClientError()?e.message:"server error: please try again or check https://status.shipstatic.com"}function Ft(e,t){return JSON.stringify({error:e,...t?{details:t}:{}},null,2)}var $e=(e,t)=>`https://setup.shipstatic.com/${e}/${t}`;function Dn(e,t,n){let{noColor:o}=n;if(e.deployments.length===0){console.log("no deployments found"),console.log();return}let s=["deployment","labels","files","size","created","via"];console.log(Y(e.deployments,s,o)),Fe(e.cursor,o)}function Fe(e,t){e&&G(`more results available \u2014 rerun with --cursor ${e}`,!1,t)}function Sn(e,t,n){let{noColor:o}=n;if(e.domains.length===0){console.log("no domains found"),console.log();return}let s=["domain","deployment","labels","linked","links","created"];console.log(Y(e.domains,s,o)),Fe(e.cursor,o)}function bn(e,t,n){let{noColor:o}=n,{_dnsRecords:s,_shareHash:r,isCreate:a,...m}=e;if(t.operation==="set"){let u=a?"created":"updated";w(`${e.url} domain ${u}`,!1,o)}s&&s.length>0&&(console.log(),G("DNS Records to configure:",!1,o),s.forEach(u=>{console.log(` ${u.type}: ${u.name} \u2192 ${u.value}`)})),r&&(console.log(),G(`Setup instructions: ${$e(r,e.domain)}`,!1,o)),console.log(K(m,o))}function En(e,t,n){let{noColor:o}=n;t.operation==="upload"&&w(`${e.url} deployment uploaded`,!1,o),console.log(K(e,o));let s=e.claim;if(s){let r=e.expires?Math.round((e.expires-e.created)/86400):null;console.log(`IMPORTANT: this deployment${r?` expires in ${r} day${r!==1?"s":""}`:" will expire"}, claim it to keep permanently:
|
|
28
28
|
${s}
|
|
29
|
-
`),
|
|
29
|
+
`),G("configure a free API key with 'ship config' to deploy to your own account",!1,o)}}function Tn(e,t,n){let{noColor:o}=n;console.log(K(e,o))}function wn(e,t,n){w(`${e.domain} dns verification queued`,!1,n.noColor)}function On(e,t,n){let{noColor:o}=n;if(e.valid){if(w("domain is valid",!1,o),console.log(),e.normalized&&console.log(` normalized: ${e.normalized}`),e.available!==null){let s=e.available?o?"available":"available \u2713":"already taken";console.log(` availability: ${s}`)}console.log()}else A(e.error||"domain is invalid",!1,o)}function Rn(e,t,n){let{noColor:o}=n;if(e.records.length===0){console.log("no records found"),console.log();return}let s=["type","name","value"];console.log(Y(e.records,s,o))}function vn(e,t,n){let{noColor:o}=n,s=e.dns?.provider?.name||null;console.log(K({domain:e.domain,provider:s},o))}function An(e,t,n){let{noColor:o}=n;w($e(e.hash,e.domain),!1,o)}function Cn(e,t,n){let{noColor:o}=n;if(e.tokens.length===0){console.log("no tokens found"),console.log();return}let s=["token","labels","created","expires"];console.log(Y(e.tokens,s,o)),Fe(e.cursor,o)}function In(e,t,n){let{noColor:o}=n;t.operation==="create"&&e.token&&w(`token ${e.token} created`,!1,o),console.log(K(e,o))}function _t(e,t,n){let{json:o,quiet:s,noColor:r}=n;if(s){if(e===void 0||typeof e=="boolean")return;if(e!==null&&typeof e=="object"){if("deployments"in e)for(let a of e.deployments)console.log(a.deployment);else if("domains"in e)for(let a of e.domains)console.log(a.domain);else if("tokens"in e)for(let a of e.tokens)console.log(a.token);else if("records"in e)for(let a of e.records)console.log(`${a.type} ${a.name} ${a.value}`);else if("hash"in e){let a=e;console.log($e(a.hash,a.domain))}else if("dns"in e){let a=e.dns?.provider?.name;a&&console.log(a)}else if("domain"in e)console.log(e.domain);else if("deployment"in e)console.log(e.deployment);else if("secret"in e)console.log(e.secret);else if("email"in e)console.log(e.email);else if("valid"in e){let a=e;a.valid&&a.normalized&&console.log(a.normalized)}}return}if(t.operation==="remove"){t.resourceType&&t.resourceId?w(`${t.resourceId} ${t.resourceType.toLowerCase()} removed`,o,r):w("removed successfully",o,r);return}if(e===void 0){w("removed successfully",o,r);return}if(typeof e=="boolean"){e?w("api reachable",o,r):A("api unreachable",o,r);return}if(o&&e!==null&&typeof e=="object"){let a={...e};delete a._dnsRecords,delete a._shareHash,delete a.isCreate,console.log(JSON.stringify(a,null,2)),console.log();return}e!==null&&typeof e=="object"?"deployments"in e?Dn(e,t,n):"domains"in e?Sn(e,t,n):"tokens"in e?Cn(e,t,n):"records"in e?Rn(e,t,n):"hash"in e?An(e,t,n):"dns"in e?vn(e,t,n):"domain"in e&&!("url"in e)?wn(e,t,n):"domain"in e?bn(e,t,n):"deployment"in e?En(e,t,n):"token"in e?In(e,t,n):"email"in e?Tn(e,t,n):"valid"in e?On(e,t,n):w("success",o,r):w("success",o,r)}function xn(){let e=[fe.resolve(__dirname,"../package.json"),fe.resolve(__dirname,"../../package.json")];for(let t of e)try{return JSON.parse((0,B.readFileSync)(t,"utf-8"))}catch{}return{version:"0.0.0"}}var Ln=xn();function kn(e){let t=r=>e?r:(0,he.bold)(r),n=r=>e?r:(0,he.dim)(r),o=r=>e?"":`${r} `;return`${t("USAGE")}
|
|
30
30
|
ship <path> ${o("\u{1F680}")}Deploy static sites with simplicity
|
|
31
31
|
|
|
32
32
|
${t("COMMANDS")}
|
|
33
33
|
${o("\u{1F4E6}")}${t("Deployments")}
|
|
34
|
-
ship deployments list List
|
|
34
|
+
ship deployments list List deployments
|
|
35
35
|
ship deployments upload <path> Upload deployment from file or directory
|
|
36
36
|
ship deployments get <deployment> Show deployment information
|
|
37
37
|
ship deployments set <deployment> Set deployment labels
|
|
38
38
|
ship deployments remove <deployment> Delete deployment permanently
|
|
39
39
|
|
|
40
40
|
${o("\u{1F30E}")}${t("Domains")}
|
|
41
|
-
ship domains list List
|
|
41
|
+
ship domains list List domains
|
|
42
42
|
ship domains set <name> [deployment] Create domain, link to deployment, or update labels
|
|
43
43
|
ship domains get <name> Show domain information
|
|
44
44
|
ship domains validate <name> Check if domain name is valid and available
|
|
@@ -49,7 +49,7 @@ ${t("COMMANDS")}
|
|
|
49
49
|
ship domains remove <name> Delete domain permanently
|
|
50
50
|
|
|
51
51
|
${o("\u{1F511}")}${t("Tokens")}
|
|
52
|
-
ship tokens list List
|
|
52
|
+
ship tokens list List deploy tokens
|
|
53
53
|
ship tokens create Create a new deploy token
|
|
54
54
|
ship tokens remove <token> Delete token permanently
|
|
55
55
|
|
|
@@ -79,9 +79,9 @@ ${t("EXAMPLES")}
|
|
|
79
79
|
ship ./dist -q | ship domains set www.example.com
|
|
80
80
|
|
|
81
81
|
${n("Please report any issues to https://github.com/shipstatic/ship/issues")}
|
|
82
|
-
`}function
|
|
83
|
-
`),process.exitCode=1}}function n(
|
|
84
|
-
`):(
|
|
85
|
-
`:U.Help.prototype.formatHelp.call(p,
|
|
86
|
-
`:" "))}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish")?
|
|
82
|
+
`}function J(e,t=[]){return t.concat([e])}function ue(e){let t=Number.parseInt(e,10);if(Number.isNaN(t))throw new U.InvalidArgumentError("Not a number.");return t}function W(e,t){let n=e?.label?.length?e.label:t?.label;if(!n?.length)return;let o=n.filter(s=>s!=="");return o.length?o:[]}function Ut(e,t){return e?.password??t?.password??(process.env.SHIP_PASSWORD||void 0)}function _(e){let t=e.optsWithGlobals();t.color===!1&&(t.noColor=!0);let n=!!process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0";return!t.noColor&&!n&&(!process.stdout.isTTY||process.env.NO_COLOR!==void 0)&&(t.noColor=!0),t}function Pn(e){let t={};try{t=me(e.config)}catch{}let n=Ne(e,q(),t).token;return typeof n=="string"?n:void 0}async function Mt(e,t,n,o,s,r){if(!(0,B.existsSync)(t))throw l.file(`${t} path does not exist`,{filePath:t});let a=(0,B.statSync)(t);if(!a.isDirectory()&&!a.isFile())throw l.file(`${t} path must be a file or directory`,{filePath:t});let m={via:process.env.SHIP_VIA||"cli"};n!==void 0&&(m.labels=n),o!==void 0&&(m.password=o),s?.noPathDetect!==void 0&&(m.pathDetect=!s.noPathDetect),s?.noSpaDetect!==void 0&&(m.spaDetect=!s.noSpaDetect);let u=new AbortController;m.signal=u.signal;let d=null;if(process.stdout.isTTY&&!r.json&&!r.quiet&&!r.noColor){let{default:p}=await import("yocto-spinner");d=p({text:"uploading\u2026"}).start()}let i=()=>{u.abort(),d&&d.stop(),process.exit(130)};process.on("SIGINT",i);try{return await e.deployments.upload(t,m)}finally{process.removeListener("SIGINT",i),d&&d.stop()}}function Gt(){let e=new U.Command;e.exitOverride(i=>{if(i.code==="commander.help"||i.code==="commander.version"||i.exitCode===0)throw i;let p=_(e),c=i.message||"unknown command error";throw c=c.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),A(c,p.json,p.noColor),p.json||e.outputHelp(),i}).configureOutput({writeErr:i=>{i.startsWith("error:")||process.stderr.write(i)},writeOut:i=>process.stdout.write(i)});function t(i,p){return(...c)=>{let h=_(e),S=c[c.length-1];if(S?.args?.length){let f=S.args.find(y=>!p.includes(y));f&&A(`unknown command '${f}'`,h.json,h.noColor)}h.json||console.log(`usage: ship ${i} <${p.join("|")}>
|
|
83
|
+
`),process.exitCode=1}}function n(i,p){let c=_(e),h=Nt(i),S=$t(h,p,{token:Pn(e.opts())});c.json?console.error(`${Ft(S,h.details)}
|
|
84
|
+
`):(A(S,!1,c.noColor),h.type===g.Validation&&S.includes("unknown command")&&e.outputHelp()),process.exitCode=1}function o(i,p){return async function(...c){let h=_(this),S=p?{operation:p.operation,resourceType:p.resourceType,resourceId:p.getResourceId?.(...c)}:{};try{let{config:f,apiUrl:y,token:O}=e.opts(),R=Pt({config:f,apiUrl:y,token:O}),L=await i(R,h,...c);_t(L,S,{json:h.json,quiet:h.quiet,noColor:h.noColor})}catch(f){n(f,S)}}}e.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(Ln.version,"-V, --version","Show version information").option("--token <token>","Any ship token: API key (ship-\u2026) or deploy token (deploy-\u2026)").option("--config <file>","Custom config file path").option("--api-url <url>","API URL (for development)").option("--json","Output results in JSON format").option("-q, --quiet","Output only the resource identifier").option("--no-color","Disable colored output").helpOption("-h, --help","Display help for command").helpCommand("help [command]","Display help for command").configureHelp({formatHelp:(i,p)=>i.parent===null?`${kn(_(i).noColor)}
|
|
85
|
+
`:U.Help.prototype.formatHelp.call(p,i,p)}).allowExcessArguments(),e.hook("preAction",i=>{let p=_(i);try{p.token&&typeof p.token=="string"&&j(p.token),p.apiUrl&&typeof p.apiUrl=="string"&&Xe(p.apiUrl)}catch(c){throw k(c)?(A(c.message,p.json,p.noColor),new U.CommanderError(1,"ship.invalidOption",c.message)):c}}),e.command("ping").description("Check API connectivity").action(o(async(i,p)=>{let c=await i.ping();return c||(process.exitCode=1),c})),e.command("whoami").description("Get current account information").action(o((i,p)=>i.whoami(),{operation:"get",resourceType:"Account"}));let s=e.command("deployments").description("Manage deployments").enablePositionalOptions().action(t("deployments",["list","upload","get","set","remove"]));s.command("list").description("List deployments (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",ue).option("--cursor <cursor>","Continue from a previous page's cursor").action(o((i,p,c)=>i.deployments.list(c))),s.command("upload <path>").description("Upload deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",J,[]).option("--password <password>","Password-protect this deployment").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(o((i,p,c,h)=>Mt(i,c,W(h,e.opts()),Ut(h,e.opts()),h,p),{operation:"upload"})),s.command("get <deployment>").description("Show deployment information").action(o((i,p,c)=>i.deployments.get(c),{operation:"get",resourceType:"Deployment",getResourceId:i=>i})),s.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",J,[]).action(o(async(i,p,c,h)=>{let S=W(h,e.opts())||[];return i.deployments.set(c,{labels:S})},{operation:"set",resourceType:"Deployment",getResourceId:i=>i})),s.command("remove <deployment>").description("Delete deployment permanently").action(o((i,p,c)=>i.deployments.remove(c),{operation:"remove",resourceType:"Deployment",getResourceId:i=>i}));let r=e.command("domains").description("Manage domains").enablePositionalOptions().action(t("domains",["list","get","set","validate","records","dns","share","verify","remove"]));r.command("list").description("List domains (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",ue).option("--cursor <cursor>","Continue from a previous page's cursor").action(o((i,p,c)=>i.domains.list(c))),r.command("get <name>").description("Show domain information").action(o((i,p,c)=>i.domains.get(c),{operation:"get",resourceType:"Domain",getResourceId:i=>i})),r.command("validate <name>").description("Check if domain name is valid and available").action(o(async(i,p,c)=>{let h=await i.domains.validate(c);return h.valid||(process.exitCode=1),h},{operation:"validate",resourceType:"Domain",getResourceId:i=>i})),r.command("verify <name>").description("Trigger DNS verification for external domain").action(o((i,p,c)=>i.domains.verify(c),{operation:"verify",resourceType:"Domain",getResourceId:i=>i})),r.command("records <name>").description("Show required DNS records for domain setup").action(o((i,p,c)=>i.domains.records(c),{operation:"records",resourceType:"Domain",getResourceId:i=>i})),r.command("dns <name>").description("Look up DNS provider for a domain").action(o((i,p,c)=>i.domains.dns(c),{operation:"dns",resourceType:"Domain",getResourceId:i=>i})),r.command("share <name>").description("Get shareable DNS setup link").action(o((i,p,c)=>i.domains.share(c),{operation:"share",resourceType:"Domain",getResourceId:i=>i})),r.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",J,[]).action(o(async(i,p,c,h,S)=>{!h&&!process.stdin.isTTY&&(h=await new Promise(R=>{let L="";process.stdin.on("data",ge=>L+=ge),process.stdin.on("end",()=>R(L.trim()||void 0))}));let f=W(S,e.opts()),y={};h&&(y.deployment=h),f!==void 0&&(y.labels=f);let O=await i.domains.set(c,y);if(O.isCreate&&c.includes("."))try{let[R,L]=await Promise.all([i.domains.records(c),i.domains.share(c)]);return{...O,_dnsRecords:R.records,_shareHash:L.hash}}catch{}return O},{operation:"set",resourceType:"Domain",getResourceId:i=>i})),r.command("remove <name>").description("Delete domain permanently").action(o((i,p,c)=>i.domains.remove(c),{operation:"remove",resourceType:"Domain",getResourceId:i=>i}));let a=e.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(t("tokens",["list","create","remove"]));a.command("list").description("List deploy tokens (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",ue).option("--cursor <cursor>","Continue from a previous page's cursor").action(o((i,p,c)=>i.tokens.list(c))),a.command("create").description("Create a new deploy token").option("--ttl <seconds>","Time to live in seconds (default: never expires)",ue).option("--label <label>","Label to set (can be repeated)",J,[]).action(o((i,p,c)=>{let h={};c?.ttl!==void 0&&(h.ttl=c.ttl);let S=W(c,e.opts());return S!==void 0&&(h.labels=S),i.tokens.create(h)},{operation:"create",resourceType:"Token"})),a.command("get <token>").description("Show one deploy token").action(o((i,p,c)=>i.tokens.get(c))),a.command("remove <token>").description("Delete token permanently").action(o((i,p,c)=>i.tokens.remove(c),{operation:"remove",resourceType:"Token",getResourceId:i=>i})),e.command("account").description("Manage account").action(t("account",["get"])).command("get").description("Show account information").action(o((i,p)=>i.whoami(),{operation:"get",resourceType:"Account"}));let u=e.command("completion").description("Setup shell completion").action(t("completion",["install","uninstall"]));u.command("install").description("Install shell completion script").action(()=>{let i=_(e),p=fe.resolve(__dirname,"completions");tt(p,{json:i.json,noColor:i.noColor})}),u.command("uninstall").description("Uninstall shell completion script").action(()=>{let i=_(e);nt({json:i.json,noColor:i.noColor})}),e.command("config").description("Save your token").action(async()=>{let i=_(e);try{await lt({noColor:i.noColor,json:i.json})}catch(p){n(p)}});let d=o((i,p,c,h)=>Mt(i,c,W(h,e.opts()),Ut(h,e.opts()),h,p),{operation:"upload"});return e.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",J,[]).option("--password <password>","Password-protect this deployment").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(async function(i,p){if(!i){this.outputHelp();return}if(!(0,B.existsSync)(i)&&!i.includes("/")&&!i.includes("\\")&&!i.includes(".")&&!i.startsWith("~")){n(l.validation(`unknown command '${i}'`),{operation:"upload"});return}return d.call(this,i,p)}),e}function Nn(){let e=process.argv.includes("--compfish");console.log(["ping","whoami","deployments","domains","tokens","account","config","completion"].join(e?`
|
|
86
|
+
`:" "))}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish")?Nn():Gt().parseAsync(process.argv).catch(t=>{if(t instanceof U.CommanderError){process.exitCode=t.exitCode;return}throw t}));0&&(module.exports={buildProgram});
|
|
87
87
|
//# sourceMappingURL=cli.cjs.map
|