@shipstatic/ship 2.9.4-beta.2 → 2.9.4-beta.3
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/THIRD-PARTY-LICENSES.md +1 -1
- package/dist/browser.d.ts +18 -3
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +2 -2
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +18 -3
- package/dist/index.d.ts +18 -3
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/cli.cjs
CHANGED
|
@@ -230,7 +230,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
230
230
|
${n("saved to")} ${o(r)}
|
|
231
231
|
`)}M();M();Hi();var Ix=$e.object(Ht).strict(),Ox={apiUrl:tn.API_URL,token:tn.TOKEN};function Mn(){if(Wt()!=="node")return{};let e={apiUrl:process.env[tn.API_URL]||void 0,token:process.env[tn.TOKEN]||void 0};try{return Ix.parse(e)}catch(t){if(t instanceof $e.ZodError){let r=t.issues[0],o=r.path[0],n=(o&&Ox[o])??"SHIP environment configuration";throw k.config(`Invalid ${n}: ${r.message}`)}throw k.config("Invalid environment configuration")}}M();M();M();var Ji=class{constructor(){this.handlers=new Map}on(t,r){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(r)}off(t,r){let o=this.handlers.get(t);o&&(o.delete(r),o.size===0&&this.handlers.delete(t))}emit(t,...r){let o=this.handlers.get(t);if(!o)return;let n=Array.from(o);for(let i of n)try{i(...r)}catch(a){o.delete(i),t!=="error"&&setTimeout(()=>{let s=a instanceof Error?a:new Error(String(a));this.emit("error",s,String(t))},0)}}};var zx=3e4,Ex=2,Dx=300,Tx=2e3,Px=new Set([500,502,503,504]);function Ax(e,t){return new Promise((r,o)=>{if(t?.aborted){o(t.reason);return}let n=()=>{clearTimeout(a),t?.removeEventListener("abort",i)},i=()=>{n(),o(t?.reason)},a=setTimeout(()=>{n(),r()},e);t?.addEventListener("abort",i)})}var wh=3e5,Cx=3e5,jx=wh+Cx,Wi=class extends Ji{constructor(r){super();this.globalHeaders={};this.apiUrl=r.apiUrl||jd,this.getAuthHeadersCallback=r.getAuthHeaders,this.session=r.session??!1,this.caller=r.caller,this.timeout=r.timeout??zx,this.maxRetries=Math.max(0,r.maxRetries??Ex),this.fetch=r.fetch??globalThis.fetch.bind(globalThis),this.deploy={endpoint:r.deployEndpoint||Z.DEPLOYMENTS,timeout:r.timeout??wh,buildTimeout:r.timeout??jx}}setGlobalHeaders(r){this.globalHeaders=r}async executeRequest(r,o,n,i=this.timeout){for(let a=0;;a++)try{return await this.attemptOnce(r,o,n,i)}catch(s){let c=k.fromFetchError(s,n);if(a>=this.maxRetries||!this.isRetryable(c,o))throw this.emit("error",c,r),c;this.emit("retry",c,r,a+1);let u=Math.min(Tx,Dx*2**a);try{await Ax(Math.random()*u,o.signal)}catch(l){let f=k.fromFetchError(l,n);throw this.emit("error",f,r),f}}}isRetryable(r,o){if(o.signal?.aborted||r.isType(P.Maintenance)||r.isType(P.Cancelled)||!(r.isNetworkError()||r.status!==void 0&&Px.has(r.status)))return!1;let i=(o.method??"GET").toUpperCase();return i==="GET"||i==="HEAD"?!0:i==="PUT"||i==="DELETE"?!1:this.hasIdempotencyKey(o.headers)}hasIdempotencyKey(r){if(!r)return!1;let o=lt.HEADER.toLowerCase();return Object.keys(r).some(n=>n.toLowerCase()===o)}async attemptOnce(r,o,n,i=this.timeout){let a=()=>{};try{let s=await this.mergeHeaders(o.headers),c=this.createTimeoutSignal(o.signal,i);a=c.cleanup;let u={...o,headers:s,credentials:this.session&&!s.Authorization?"include":void 0,signal:c.signal};this.emit("request",r,u);let l=await this.fetch(r,u);if(a(),!l.ok)throw await k.fromHttpResponse(l,n);return this.emit("response",this.safeClone(l),r),{data:await this.parseResponse(this.safeClone(l)),status:l.status}}catch(s){throw a(),k.fromFetchError(s,n)}}async request(r,o,n,i){let{data:a}=await this.executeRequest(`${this.apiUrl}${r}`,o,n,i);return a}async requestWithStatus(r,o,n){return this.executeRequest(`${this.apiUrl}${r}`,o,n)}async mergeHeaders(r={}){return{...this.globalHeaders,...this.caller?{[Xt.HEADER]:this.caller}:{},...await this.getAuthHeadersCallback(),...r}}createTimeoutSignal(r,o=this.timeout){let n=new AbortController,i=setTimeout(()=>n.abort(new DOMException(`Timed out after ${o}ms`,"TimeoutError")),o),a=r?()=>n.abort(r.reason):void 0;return r&&a&&(r.addEventListener("abort",a),r.aborted&&n.abort(r.reason)),{signal:n.signal,cleanup:()=>{clearTimeout(i),r&&a&&r.removeEventListener("abort",a)}}}safeClone(r){try{return r.clone()}catch{return r}}async parseResponse(r){if(!(r.headers.get("Content-Length")==="0"||r.status===204))return r.json()}};M();M();async function Ih(e,t={}){let{labels:r,via:o,password:n,ttl:i,flags:a,captcha:s}=t,c=new FormData,u=[];for(let l of e){if(typeof l.content=="string"||l.content===null||l.content===void 0)throw k.file(`Unsupported file.content type: ${l.path}`,{filePath:l.path});if(!l.md5)throw k.file(`File missing md5 checksum: ${l.path}`,{filePath:l.path});c.append(se.FILES,new File([l.content],l.path,{type:"application/octet-stream"})),u.push(l.md5)}return c.append(se.CHECKSUMS,JSON.stringify(u)),r&&r.length>0&&c.append(se.LABELS,JSON.stringify(r)),o&&c.append(se.VIA,o),n&&c.append(se.PASSWORD,n),i!==void 0&&c.append(se.TTL,String(i)),a?.build&&c.append(se.BUILD,"true"),a?.prerender&&c.append(se.PRERENDER,"true"),a?.spa&&c.append(se.SPA,"true"),a?.buildCommand&&c.append(se.BUILD_COMMAND,a.buildCommand),a?.outputDir&&c.append(se.OUTPUT_DIR,a.outputDir),s&&c.append(se.CAPTCHA,s),c}M();Xl();async function Lx(){let e=JSON.stringify(Pd,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:r}=await qi(t);return{path:Ee,content:t,size:e.length,md5:r}}async function Fx(e,t){let r=e.find(a=>a.path===Yn.INDEX_FILE||a.path===`/${Yn.INDEX_FILE}`);if(!r||r.size>Yn.MAX_INDEX_BYTES)return!1;let o;if(typeof Buffer<"u"&&Buffer.isBuffer(r.content))o=r.content.toString("utf-8");else if(typeof Blob<"u"&&r.content instanceof Blob)o=await r.content.text();else if(typeof File<"u"&&r.content instanceof File)o=await r.content.text();else return!1;let n={files:e.map(a=>a.path),index:o};return(await t.request(Z.SPA_CHECK,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"SPA check")).isSPA}async function Dh(e,t,r){if(r.spaDetect===!1||r.spa||r.build||r.prerender||e.some(o=>o.path===Ee))return e;try{if(await Fx(e,t)){let n=await Lx();return[...e,n]}}catch{}return e}M();M();function Vn(e){if(e==null)return;if(e.length===0)return e;if(e.length>Ue.MAX_COUNT)throw k.validation(`Maximum ${Ue.MAX_COUNT} labels allowed`);let t=e.map((o,n)=>{if(typeof o!="string")throw k.validation(`Label at index ${n} must be a string`);let i=o.trim().toLowerCase();if(i.length<Ue.MIN_LENGTH)throw k.validation(`Labels must be at least ${Ue.MIN_LENGTH} characters long`);if(i.length>Ue.MAX_LENGTH)throw k.validation(`Labels must be no more than ${Ue.MAX_LENGTH} characters long`);if(!Ld.test(i))throw k.validation(`Labels must start and end with alphanumeric characters, with optional separators (${Ue.SEPARATORS}) between segments`);return i}),r=[...new Set(t)];if(r.length!==t.length)throw k.validation("Duplicate labels are not allowed");return r}async function Th(e){let t=e.find(n=>n.path===Ee||n.path===`/${Ee}`);if(!t)return;let r=t.content,o=typeof r.text=="function"?await r.text():t.content.toString("utf8");Ad(o)}var Ki={"Content-Type":"application/json"},Zx="sdk";function Yl(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 r=t.toString();return r?`?${r}`:""}function Ph(e){let{getApi:t,processInput:r}=e;return{upload:async(o,n={})=>{if(!r)throw k.config("processInput function is not provided.");let i=t(),a=await r(o,n),s=await Dh(a,i,n);if(!s.length)throw k.business("No files to deploy");for(let E of s)if(!E.md5)throw k.file(`MD5 checksum missing for file: ${E.path}`,{filePath:E.path});Co(n.password);let c=Ao(n.ttl),u=zd(n.idempotencyKey),l=Vn(n.labels);await Th(s);let f=Fd(n.buildCommand),p=Zd(n.outputDir),_=n.build||n.prerender||n.spa?{build:n.build,prerender:n.prerender,spa:n.spa,buildCommand:f,outputDir:p}:void 0,b=await Ih(s,{labels:l,via:n.via??Zx,password:n.password,ttl:c,flags:_,captcha:n.captcha});return i.request(i.deploy.endpoint,{method:"POST",body:b,...u?{headers:{[lt.HEADER]:u}}:{},signal:n.signal||null},"Deploy",n.build||n.prerender?i.deploy.buildTimeout:i.deploy.timeout)},list:async o=>t().request(`${Z.DEPLOYMENTS}${Yl(o)}`,{method:"GET"},"List deployments"),get:async o=>t().request(Z.DEPLOYMENT(encodeURIComponent(o)),{method:"GET"},"Get deployment"),set:async(o,n)=>t().request(Z.DEPLOYMENT(encodeURIComponent(o)),{method:"PATCH",headers:Ki,body:JSON.stringify({labels:Vn(n.labels)})},"Update deployment labels"),delete:async o=>t().request(Z.DEPLOYMENT(encodeURIComponent(o)),{method:"DELETE"},"Delete deployment")}}function Ah(e){let{getApi:t}=e;return{set:async(r,o={})=>{let n=Vn(o.labels),i={};o.deployment&&(i.deployment=o.deployment),n!==void 0&&(i.labels=n);let{data:a,status:s}=await t().requestWithStatus(Z.DOMAIN(encodeURIComponent(r)),{method:"PUT",headers:Ki,body:JSON.stringify(i)},"Set domain");return{...a,isCreate:s===201}},list:async r=>t().request(`${Z.DOMAINS}${Yl(r)}`,{method:"GET"},"List domains"),get:async r=>t().request(Z.DOMAIN(encodeURIComponent(r)),{method:"GET"},"Get domain"),delete:async r=>t().request(Z.DOMAIN(encodeURIComponent(r)),{method:"DELETE"},"Delete domain"),verify:async r=>t().request(Z.DOMAIN_VERIFY(encodeURIComponent(r)),{method:"POST"},"Verify domain"),validate:async r=>t().request(Z.DOMAINS_VALIDATE,{method:"POST",headers:Ki,body:JSON.stringify({domain:r})},"Validate domain"),dns:async r=>t().request(Z.DOMAIN_DNS(encodeURIComponent(r)),{method:"GET"},"Get domain DNS"),records:async r=>t().request(Z.DOMAIN_RECORDS(encodeURIComponent(r)),{method:"GET"},"Get domain records"),share:async r=>t().request(Z.DOMAIN_SHARE(encodeURIComponent(r)),{method:"GET"},"Get domain share")}}function Ch(e){let{getApi:t}=e;return{get:async()=>t().request(Z.ACCOUNT,{method:"GET"},"Get account")}}function jh(e){let{getApi:t}=e;return{create:async(r={})=>{let o=Ao(r.ttl),n=Vn(r.labels),i={};return o!==void 0&&(i.ttl=o),n!==void 0&&(i.labels=n),t().request(Z.TOKENS,{method:"POST",headers:Ki,body:JSON.stringify(i)},"Create token")},list:async r=>t().request(`${Z.TOKENS}${Yl(r)}`,{method:"GET"},"List tokens"),get:async r=>t().request(Z.TOKEN(encodeURIComponent(r)),{method:"GET"},"Get token"),delete:async r=>t().request(Z.TOKEN(encodeURIComponent(r)),{method:"DELETE"},"Delete token")}}var Xi=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&&Cd(t.caller),t.token&&t.session)throw k.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(Ye(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new Wi({...t,getAuthHeaders:()=>this.getAuthHeaders()});let r={getApi:()=>this.http};this.deployments=Ph({...r,processInput:async(o,n)=>(await this.ensureInitialized(),this.processInput(o,n))}),this.domains=Ah(r),this.account=Ch(r),this.tokens=jh(r)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.request(Z.LIMITS,{method:"GET"},"Get limits")}catch(t){throw this.initPromise=null,t}}async ping(){return this.http.request(Z.PING,{method:"GET"},"Ping")}async deploy(t,r){return this.deployments.upload(t,r)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,r){this.http.on(t,r)}off(t,r){this.http.off(t,r)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw k.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw k.business("Invalid token provided. Token must be a non-empty string.");Ye(t),this.credential=t;return}if(typeof t!="function")throw k.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 k.authentication("Token provider returned no token.");if(typeof t!="string")throw k.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};Hi();var eo=class extends Xi{constructor(t={}){if(Wt()!=="node")throw k.business("Node.js Ship class can only be used in Node.js environment.");let r=Mn();super({...t,apiUrl:t.apiUrl||r.apiUrl,token:t.token||(t.session?void 0:r.token)})}async deploy(t,r){return super.deploy(t,r)}async processInput(t,r){let o=typeof t=="string"?[t]:t;if(!Array.isArray(o)||!o.every(i=>typeof i=="string"))throw k.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw k.business("No files to deploy.");let{processFilesForNode:n}=await Promise.resolve().then(()=>(Qh(),Yh));return n(o,r,this.platformLimits??void 0)}};function eg(e,t,r){return{apiUrl:e.apiUrl||t.apiUrl||r.apiUrl,token:e.token||t.token||r.token}}function tg(e={}){let t=eg(e,Mn(),Wl(e.config));return t.apiUrl&&Qn(t.apiUrl),new eo(t)}function to(e){let t={};try{t=Wl(e.config)}catch{}let r=eg(e,Mn(),t).token;return typeof r=="string"?r:void 0}M();function ng(e){return ce(e)?e:e instanceof Error?k.business(e.message):k.business(String(e??"Unknown error"))}var no="pass --token, set SHIP_TOKEN, or run ship config";function rg(e,t){return e.isAuthError()?t?.token?"authentication failed: invalid or expired token":`authentication required: ${no}`:e.isType(P.Timeout)?e.message:e.isNetworkError()?"network error: could not reach the API. check your internet connection":e.isType(P.Maintenance)?`${e.message.replace(/\.$/,"")} \u2014 check https://status.shipstatic.com`:e.isClientError()?e.message:`${e.message.replace(/\.$/,"")} \u2014 try again, or check https://status.shipstatic.com`}M();function nd(e,t){return e[t]}var Yx={[Id.DELETING]:"served until cleanup completes"},Qx={upload:"uploaded",create:"created",delete:"deleted",verify:"verification queued"};function ag(e,t){let{operation:r,resource:o}=t;if(!o||e===null||typeof e!="object")return null;let n=r==="set"?nd(e,"isCreate")?"created":"updated":Qx[r];if(!n)return null;let i=nd(e,o);if(typeof i!="string")return null;let a=nd(e,"status"),s=typeof a=="string"?Yx[a]:void 0;return`${i} ${o} ${s?`${a} \u2014 ${s}`:n}`}function sg(e,t,r){if(r.json||r.quiet)return;let o=ag(e,t);o&&be(o,!1,r.noColor)}function eb(e,t){let{noColor:r}=t;if(e.deployments.length===0){console.log("no deployments found"),console.log();return}let o=["deployment","labels","files","size","created","via"];console.log(cn(e.deployments,o,r)),id(e.cursor,r)}function id(e,t){e&&Le(`more results available \u2014 rerun with --cursor ${e}`,!1,t)}function tb(e,t){let{noColor:r}=t;if(e.domains.length===0){console.log("no domains found"),console.log();return}let o=["domain","deployment","labels","linked","links","created"];console.log(cn(e.domains,o,r)),id(e.cursor,r)}function ig(e,t){let{noColor:r}=t,{_dnsRecords:o,_shareUrl:n,isCreate:i,...a}=e;o&&o.length>0&&(console.log(),Le("DNS records to configure:",!1,r),o.forEach(s=>{console.log(` ${s.type}: ${s.name} \u2192 ${s.value}`)})),n&&(console.log(),Le(`Setup instructions: ${n}`,!1,r)),console.log(Fe(a,r))}function rd(e,t){let{noColor:r}=t;console.log(Fe(e,r));let o=e.claim;if(o){let n=e.expires?Rd(e.expires):null;console.log(`IMPORTANT: this deployment ${n?`expires in ${n}`:"will expire"}, claim it to keep permanently:
|
|
232
232
|
${o}
|
|
233
|
-
`),Le("configure a free API key with 'ship config' to deploy to your own account",!1,r)}}function nb(e,t){let{noColor:r}=t;console.log(Fe(e,r))}function rb(e,t){let{noColor:r}=t;if(e.valid){if(be(`${e.normalized??"domain"} domain is valid`,!1,r),console.log(),e.available!==null){let o=e.available?r?"available":"available \u2713":"already taken";console.log(` availability: ${o}`)}console.log()}else console.log(`${pt(e.reason??"domain is invalid")}
|
|
233
|
+
`),Le("configure a free API key with 'ship config' to deploy to your own account",!1,r)}}function nb(e,t){let{noColor:r}=t;console.log(Fe(e,r))}function rb(e,t){let{noColor:r}=t;if(e.valid){if(be(`${e.normalized??"domain"} domain is valid`,!1,r),console.log(),e.available!==null){let o=e.available?r?"available":"available \u2713":e.reason??"already taken";console.log(` availability: ${o}`)}console.log()}else console.log(`${pt(e.reason??"domain is invalid")}
|
|
234
234
|
`)}function ib(e,t){let{noColor:r}=t;if(e.records.length===0){console.log("no records found"),console.log();return}let o=["type","name","value"];console.log(cn(e.records,o,r))}function ob(e,t){let{noColor:r}=t,o=e.dns?.provider?.name||null;console.log(Fe({domain:e.domain,provider:o},r))}function ab(e,t){let{noColor:r}=t;console.log(Fe(e,r))}function sb(e,t){let{noColor:r}=t;if(e.tokens.length===0){console.log("no tokens found"),console.log();return}let o=["token","labels","created","expires"];console.log(cn(e.tokens,o,r)),id(e.cursor,r)}function og(e,t){let{noColor:r}=t;console.log(Fe(e,r))}var G=e=>e,cb=e=>e.resource?`${e.resource}.${e.operation}`:e.operation,ub={"deployment.list":G({quiet:e=>e.deployments.map(t=>t.deployment),text:eb}),"deployment.upload":G({quiet:e=>[e.deployment],text:rd}),"deployment.get":G({quiet:e=>[e.deployment],text:rd}),"deployment.set":G({quiet:e=>[e.deployment],text:rd}),"deployment.delete":G({quiet:e=>[e.deployment],text:()=>{}}),"domain.list":G({quiet:e=>e.domains.map(t=>t.domain),text:tb}),"domain.get":G({quiet:e=>[e.domain],text:ig}),"domain.set":G({quiet:e=>[e.domain],text:ig}),"domain.validate":G({quiet:e=>e.valid&&e.normalized?[e.normalized]:[],text:rb}),"domain.verify":G({quiet:e=>[e.domain],text:()=>{}}),"domain.records":G({quiet:e=>e.records.map(t=>`${t.type} ${t.name} ${t.value}`),text:ib}),"domain.dns":G({quiet:e=>e.dns?.provider?.name?[e.dns.provider.name]:[],text:ob}),"domain.share":G({quiet:e=>[e.url],text:ab}),"domain.delete":G({quiet:e=>[e.domain],text:()=>{}}),"token.list":G({quiet:e=>e.tokens.map(t=>t.token),text:sb}),"token.create":G({quiet:e=>[e.secret],text:og}),"token.get":G({quiet:e=>[e.token],text:og}),"token.delete":G({quiet:e=>[e.token],text:()=>{}}),"account.get":G({quiet:e=>[e.email],text:nb}),ping:G({quiet:()=>[],text:(e,t)=>be("api reachable",!1,t.noColor)})};function cg(e,t,r){let{json:o,quiet:n,noColor:i}=r,a=ub[cb(t)];if(n){for(let c of a?.quiet(e)??[])console.log(c);return}if(o&&e!==null&&typeof e=="object"){let c={...e};delete c._dnsRecords,delete c._shareUrl,delete c.isCreate,console.log(JSON.stringify(c,null,2)),console.log();return}let s=ag(e,t);s&&be(s,!1,i),a?a.text(e,r):e!==null&&typeof e=="object"&&console.log(Fe(e,i))}function vb(){let e=[ud.resolve(__dirname,"../package.json"),ud.resolve(__dirname,"../../package.json")];for(let t of e)try{return JSON.parse((0,ut.readFileSync)(t,"utf-8"))}catch{}return{version:"0.0.0"}}var _b=vb();function yb(e){let t=i=>e?i:jo(i),r=i=>e?i:Re(i),o=i=>e?"":`${i} `;return`${t("USAGE")}
|
|
235
235
|
ship <path> ${o("\u{1F680}")}Deploy static sites with simplicity
|
|
236
236
|
|
|
@@ -290,5 +290,5 @@ ${t("EXAMPLES")}
|
|
|
290
290
|
${r("Please report any issues to https://github.com/shipstatic/ship/issues")}
|
|
291
291
|
`}var qt=e=>new k(P.Validation,e);function ro(e,t=[]){return t.concat([e])}function cd(e){let t=Number.parseInt(e,10);if(Number.isNaN(t))throw new wo("Not a number.");return t}var $b={s:1,m:60,h:3600,d:1440*60};function fg(e){let t=/^(\d+)([smhd])?$/.exec(e.trim().toLowerCase());if(!t)throw new wo("Expected seconds or a duration like 90s, 30m, 1h, 7d.");return Number.parseInt(t[1],10)*(t[2]?$b[t[2]]:1)}function io(e){let t=e.label;if(!t?.length)return;let r=t.filter(o=>o!=="");return r.length?r:[]}function xb(e){return e.password??(process.env.SHIP_PASSWORD||void 0)}function oo(e){return e.ttl}var bb=new Set(["--token","--config","--api-url","--json","--quiet","--no-color","--version"]);function vg(e){let t=[];for(let r=e;r?.parent;r=r.parent)t.unshift(r.name());return t.length||t.push(...e.registeredArguments.map(r=>`<${r.name()}>`)),t.join(" ")}function _g(e,t){return[...e.options.some(r=>r.long===t)?[vg(e)]:[],...e.commands.flatMap(r=>_g(r,t))]}function Sb(e,t){if(t!==e)for(let r of e.options){let o=r.long;if(!o||bb.has(o)||e.getOptionValueSource(r.attributeName())!=="cli"||t.options.some(i=>i.long===o))continue;let n=_g(e,o).map(i=>`ship ${i}`);throw qt(`option '${o}' does not apply to 'ship ${vg(t)}'${n.length?` \u2014 it belongs to ${n.join(", ")}`:""}`)}}function Oe(e){let t=e.optsWithGlobals();t.color===!1&&(t.noColor=!0);let r=!!process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0";return!t.noColor&&!r&&(!process.stdout.isTTY||process.env.NO_COLOR!==void 0)&&(t.noColor=!0),t}function Gn(){let e=Oe(this),t=fe(this).map(o=>o.name()),r=this.args.find(o=>!t.includes(o));r&&ft(qt(`unknown command '${r}'`),e.json,e.noColor),e.json||console.log(`usage: ship ${this.name()} <${t.join("|")}>
|
|
292
292
|
`),process.exitCode=1}async function hg(e,t,r){if(!(0,ut.existsSync)(t))throw k.file(`${t} path does not exist`,{filePath:t});let o=(0,ut.statSync)(t);if(!o.isDirectory()&&!o.isFile())throw k.file(`${t} path must be a file or directory`,{filePath:t});let n={via:Od(process.env[Nd])??Eo.CLI},i=io(r);i!==void 0&&(n.labels=i);let a=process.env.SHIP_IDEMPOTENCY_KEY||void 0;a!==void 0&&(n.idempotencyKey=a);let s=xb(r);s!==void 0&&(n.password=s);let c=oo(r);c!==void 0&&(n.ttl=c),r.pathDetect!==void 0&&(n.pathDetect=r.pathDetect),r.spaDetect!==void 0&&(n.spaDetect=r.spaDetect);let u=new AbortController;n.signal=u.signal;let l=null;if(process.stdout.isTTY&&!r.json&&!r.quiet&&!r.noColor){let{default:p}=await Promise.resolve().then(()=>(mg(),pg));l=p({text:"uploading\u2026"}).start()}let f=()=>{u.abort(),l&&l.stop(),process.exit(130)};process.on("SIGINT",f);try{return await e.deployments.upload(t,n)}finally{process.removeListener("SIGINT",f),l&&l.stop()}}async function gg(e,t,r){let o=await e.domains.set(t,r);if(o.isCreate&&t.includes("."))try{let[n,i]=await Promise.all([e.domains.records(t),e.domains.share(t)]);return{...o,_dnsRecords:n.records,_shareUrl:i.url}}catch{}return o}function yg(){let e=new kd;e.exitOverride(p=>{if(p.code==="commander.help"||p.code==="commander.version"||p.exitCode===0)throw p;let _=Oe(e),b=p.message||"unknown command error";throw b=b.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),ft(qt(b),_.json,_.noColor),_.json||e.outputHelp(),p}).configureOutput({writeErr:p=>{p.startsWith("error:")||process.stderr.write(p)},writeOut:p=>process.stdout.write(p)});function t(p){let _=Oe(e),b=ng(p);if(_.json)ft(b,!0,_.noColor);else{let E=rg(b,{token:b.isAuthError()?to(e.opts()):void 0});ft(E,!1,_.noColor),b.type===P.Validation&&E.includes("unknown command")&&e.outputHelp()}process.exitCode=1}function r(p,_){return async function(...b){let E=Oe(this);try{let{config:D,apiUrl:x,token:$}=e.opts(),m=tg({config:D,apiUrl:x,token:$}),d=await p(m,E,...b);cg(d,_,{json:E.json,quiet:E.quiet,noColor:E.noColor})}catch(D){t(D)}}}e.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(_b.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:(p,_)=>p.parent===null?`${yb(Oe(p).noColor)}
|
|
293
|
-
`:wd.prototype.formatHelp.call(_,p,_)}).allowExcessArguments(),e.hook("preAction",(p,_)=>{let b=Oe(p);try{Sb(e,_),b.token&&typeof b.token=="string"&&Ye(b.token),b.apiUrl&&typeof b.apiUrl=="string"&&Qn(b.apiUrl)}catch(E){throw ce(E)?(ft(E,b.json,b.noColor),new qn(1,"ship.invalidOption",E.message)):E}}),e.command("ping").description("Check API connectivity").action(r((p,_)=>p.ping(),{operation:"ping"})),e.command("whoami").description("Get current account information").action(r((p,_)=>p.whoami(),{operation:"get",resource:"account"}));let o=r((p,_,b)=>{if(oo(_)!==void 0&&!to(e.opts()))throw k.config(`--ttl sets an expiry, which needs a token: ${no}`);return hg(p,b,_)},{operation:"upload",resource:"deployment"}),n=p=>r(async(_,b,E)=>{if(!to(e.opts()))throw k.config(`--domain links a domain, which needs a token: ${no}`);if(oo(b)!==void 0)throw qt("--ttl and --domain cannot be combined: a domain cannot point at a deployment that expires.");let D=await hg(_,E,b);return sg(D,{operation:"upload",resource:"deployment"},b),gg(_,p,{deployment:D.deployment})},{operation:"set",resource:"domain"});function i(p){let{domain:_}=Oe(this);return(_?n(_):o).call(this,p)}let a=p=>p.option("--domain <domain>","Serve this deployment at a domain (needs a token)").option("--label <label>","Label to add (can be repeated)",ro,[]).option("--password <password>","Password-protect this deployment").option("--ttl <duration>","Expire after this long \u2014 3600, 1h, 7d (needs a token)",fg).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration"),s=e.command("deployments").description("Manage deployments").enablePositionalOptions().action(Gn);s.command("list").description("List deployments (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",cd).option("--cursor <cursor>","Continue from a previous page's cursor").action(r((p,_,b)=>p.deployments.list(b),{operation:"list",resource:"deployment"})),a(s.command("upload <path>").description("Upload deployment from file or directory").passThroughOptions()).action(i),s.command("get <deployment>").description("Show deployment information").action(r((p,_,b)=>p.deployments.get(b),{operation:"get",resource:"deployment"})),s.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",ro,[]).action(r(async(p,_,b)=>p.deployments.set(b,{labels:io(_)||[]}),{operation:"set",resource:"deployment"})),s.command("delete <deployment>").description("Delete deployment permanently").action(r((p,_,b)=>p.deployments.delete(b),{operation:"delete",resource:"deployment"}));let c=e.command("domains").description("Manage domains").enablePositionalOptions().action(Gn);c.command("list").description("List domains (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",cd).option("--cursor <cursor>","Continue from a previous page's cursor").action(r((p,_,b)=>p.domains.list(b),{operation:"list",resource:"domain"})),c.command("get <name>").description("Show domain information").action(r((p,_,b)=>p.domains.get(b),{operation:"get",resource:"domain"})),c.command("validate <name>").description("Check if domain name is valid and available").action(r(async(p,_,b)=>{let E=await p.domains.validate(b);return
|
|
293
|
+
`:wd.prototype.formatHelp.call(_,p,_)}).allowExcessArguments(),e.hook("preAction",(p,_)=>{let b=Oe(p);try{Sb(e,_),b.token&&typeof b.token=="string"&&Ye(b.token),b.apiUrl&&typeof b.apiUrl=="string"&&Qn(b.apiUrl)}catch(E){throw ce(E)?(ft(E,b.json,b.noColor),new qn(1,"ship.invalidOption",E.message)):E}}),e.command("ping").description("Check API connectivity").action(r((p,_)=>p.ping(),{operation:"ping"})),e.command("whoami").description("Get current account information").action(r((p,_)=>p.whoami(),{operation:"get",resource:"account"}));let o=r((p,_,b)=>{if(oo(_)!==void 0&&!to(e.opts()))throw k.config(`--ttl sets an expiry, which needs a token: ${no}`);return hg(p,b,_)},{operation:"upload",resource:"deployment"}),n=p=>r(async(_,b,E)=>{if(!to(e.opts()))throw k.config(`--domain links a domain, which needs a token: ${no}`);if(oo(b)!==void 0)throw qt("--ttl and --domain cannot be combined: a domain cannot point at a deployment that expires.");let D=await hg(_,E,b);return sg(D,{operation:"upload",resource:"deployment"},b),gg(_,p,{deployment:D.deployment})},{operation:"set",resource:"domain"});function i(p){let{domain:_}=Oe(this);return(_?n(_):o).call(this,p)}let a=p=>p.option("--domain <domain>","Serve this deployment at a domain (needs a token)").option("--label <label>","Label to add (can be repeated)",ro,[]).option("--password <password>","Password-protect this deployment").option("--ttl <duration>","Expire after this long \u2014 3600, 1h, 7d (needs a token)",fg).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration"),s=e.command("deployments").description("Manage deployments").enablePositionalOptions().action(Gn);s.command("list").description("List deployments (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",cd).option("--cursor <cursor>","Continue from a previous page's cursor").action(r((p,_,b)=>p.deployments.list(b),{operation:"list",resource:"deployment"})),a(s.command("upload <path>").description("Upload deployment from file or directory").passThroughOptions()).action(i),s.command("get <deployment>").description("Show deployment information").action(r((p,_,b)=>p.deployments.get(b),{operation:"get",resource:"deployment"})),s.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",ro,[]).action(r(async(p,_,b)=>p.deployments.set(b,{labels:io(_)||[]}),{operation:"set",resource:"deployment"})),s.command("delete <deployment>").description("Delete deployment permanently").action(r((p,_,b)=>p.deployments.delete(b),{operation:"delete",resource:"deployment"}));let c=e.command("domains").description("Manage domains").enablePositionalOptions().action(Gn);c.command("list").description("List domains (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",cd).option("--cursor <cursor>","Continue from a previous page's cursor").action(r((p,_,b)=>p.domains.list(b),{operation:"list",resource:"domain"})),c.command("get <name>").description("Show domain information").action(r((p,_,b)=>p.domains.get(b),{operation:"get",resource:"domain"})),c.command("validate <name>").description("Check if domain name is valid and available").action(r(async(p,_,b)=>{let E=await p.domains.validate(b);return(!E.valid||E.available===!1)&&(process.exitCode=1),E},{operation:"validate",resource:"domain"})),c.command("verify <name>").description("Trigger DNS verification for external domain").action(r((p,_,b)=>p.domains.verify(b),{operation:"verify",resource:"domain"})),c.command("records <name>").description("Show required DNS records for domain setup").action(r((p,_,b)=>p.domains.records(b),{operation:"records",resource:"domain"})),c.command("dns <name>").description("Look up DNS provider for a domain").action(r((p,_,b)=>p.domains.dns(b),{operation:"dns",resource:"domain"})),c.command("share <name>").description("Get shareable DNS setup link").action(r((p,_,b)=>p.domains.share(b),{operation:"share",resource:"domain"})),c.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",ro,[]).action(r(async(p,_,b,E)=>{!E&&!process.stdin.isTTY&&(E=await new Promise($=>{let m="";process.stdin.on("data",d=>m+=d),process.stdin.on("end",()=>$(m.trim()||void 0))}));let D=io(_),x={};return E&&(x.deployment=E),D!==void 0&&(x.labels=D),gg(p,b,x)},{operation:"set",resource:"domain"})),c.command("delete <name>").description("Delete domain permanently").action(r((p,_,b)=>p.domains.delete(b),{operation:"delete",resource:"domain"}));let u=e.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(Gn);u.command("list").description("List deploy tokens (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",cd).option("--cursor <cursor>","Continue from a previous page's cursor").action(r((p,_,b)=>p.tokens.list(b),{operation:"list",resource:"token"})),u.command("create").description("Create a new deploy token").option("--ttl <duration>","Expire after this long \u2014 3600, 1h, 7d",fg).option("--label <label>","Label to set (can be repeated)",ro,[]).action(r((p,_)=>{let b={},E=oo(_);E!==void 0&&(b.ttl=E);let D=io(_);return D!==void 0&&(b.labels=D),p.tokens.create(b)},{operation:"create",resource:"token"})),u.command("get <token>").description("Show one deploy token").action(r((p,_,b)=>p.tokens.get(b),{operation:"get",resource:"token"})),u.command("delete <token>").description("Delete token permanently").action(r((p,_,b)=>p.tokens.delete(b),{operation:"delete",resource:"token"})),e.command("account").description("Manage account").action(Gn).command("get").description("Show account information").action(r((p,_)=>p.whoami(),{operation:"get",resource:"account"}));let f=e.command("completion").description("Setup shell completion").action(Gn);return f.command("install").description("Install shell completion script").action(()=>{let p=Oe(e);try{hp(e,{json:p.json,noColor:p.noColor})}catch(_){t(_)}}),f.command("uninstall").description("Uninstall shell completion script").action(()=>{let p=Oe(e);try{gp({json:p.json,noColor:p.noColor})}catch(_){t(_)}}),e.command("config").description("Save your token").action(async()=>{let p=Oe(e);try{if(p.json)throw qt("ship config is interactive \u2014 run it without --json (it shows the token already saved)");await Sh({noColor:p.noColor,configFile:p.config})}catch(_){t(_)}}),a(e.argument("[path]","Path to deploy")).action(async function(p){if(!p){this.outputHelp();return}if(!(0,ut.existsSync)(p)&&!p.includes("/")&&!p.includes("\\")&&!p.includes(".")&&!p.startsWith("~")){t(qt(`unknown command '${p}'`));return}return i.call(this,p)}),e}yg().parseAsync(process.argv).catch(e=>{if(e instanceof qn){process.exitCode=e.exitCode;return}throw e});
|
|
294
294
|
//# sourceMappingURL=cli.cjs.map
|