@shipstatic/ship 0.8.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,14 +15,29 @@ npm install @shipstatic/ship
15
15
  ## CLI Usage
16
16
 
17
17
  ```bash
18
- # Deploy a directory (shortcut)
18
+ # Deploy a directory
19
19
  ship ./dist
20
20
 
21
21
  # Deploy with labels
22
22
  ship ./dist --label production --label v1.0.0
23
23
 
24
- # Disable automatic detection
25
- ship ./dist --no-path-detect --no-spa-detect
24
+ # Deploy and link to a domain in one pipe
25
+ ship ./dist -q | ship domains set www.example.com
26
+ ```
27
+
28
+ ### Composability
29
+
30
+ The `-q` flag outputs only the resource identifier — perfect for piping and scripting:
31
+
32
+ ```bash
33
+ # Deploy and link domain
34
+ ship ./dist -q | ship domains set www.example.com
35
+
36
+ # Deploy and open in browser
37
+ open https://$(ship ./dist -q)
38
+
39
+ # Batch operations
40
+ ship deployments list -q | xargs -I{} ship deployments remove {} -q
26
41
  ```
27
42
 
28
43
  ### Deployments
@@ -31,22 +46,22 @@ ship ./dist --no-path-detect --no-spa-detect
31
46
  ship deployments list
32
47
  ship deployments upload <path> # Upload from file or directory
33
48
  ship deployments upload <path> --label production # Upload with labels
34
- ship deployments get <id>
35
- ship deployments set <id> --label production # Update labels
36
- ship deployments remove <id>
49
+ ship deployments get <deployment>
50
+ ship deployments set <deployment> --label production
51
+ ship deployments remove <deployment>
37
52
  ```
38
53
 
39
54
  ### Domains
40
55
 
41
56
  ```bash
42
57
  ship domains list
43
- ship domains set staging # Reserve domain (no deployment yet)
44
- ship domains set staging <deployment-id> # Link domain to deployment
45
- ship domains set staging --label production # Update labels only
46
- ship domains get staging
58
+ ship domains set www.example.com # Reserve domain (no deployment yet)
59
+ ship domains set www.example.com <deployment> # Link domain to deployment
60
+ ship domains set www.example.com --label prod # Update labels only
61
+ ship domains get www.example.com
47
62
  ship domains validate www.example.com # Check if domain is valid and available
48
63
  ship domains verify www.example.com # Trigger DNS verification
49
- ship domains remove staging
64
+ ship domains remove www.example.com
50
65
  ```
51
66
 
52
67
  ### Tokens
@@ -60,8 +75,7 @@ ship tokens remove <token>
60
75
  ### Account & Setup
61
76
 
62
77
  ```bash
63
- ship whoami # Get current account (alias for account get)
64
- ship account get
78
+ ship whoami
65
79
  ship config # Create or update ~/.shiprc
66
80
  ship ping # Check API connectivity
67
81
  ```
@@ -80,10 +94,11 @@ ship completion uninstall
80
94
  --deploy-token <token> Deploy token for single-use deployments
81
95
  --config <file> Custom config file path
82
96
  --label <label> Add label (repeatable)
83
- --no-path-detect Disable automatic path optimization and flattening
84
- --no-spa-detect Disable automatic SPA detection and configuration
97
+ --no-path-detect Disable automatic path optimization
98
+ --no-spa-detect Disable automatic SPA detection
85
99
  --no-color Disable colored output
86
100
  --json Output results in JSON format
101
+ -q, --quiet Output only the resource identifier
87
102
  --version Show version information
88
103
  ```
89
104
 
@@ -107,12 +122,12 @@ const deployment = await ship.deployments.upload('./dist', {
107
122
  });
108
123
 
109
124
  // Manage domains
110
- await ship.domains.set('staging', { deployment: deployment.id });
125
+ await ship.domains.set('www.example.com', { deployment: deployment.deployment });
111
126
  await ship.domains.list();
112
127
 
113
128
  // Update labels
114
- await ship.deployments.set(deployment.id, { labels: ['production', 'v1.0'] });
115
- await ship.domains.set('staging', { labels: ['live'] });
129
+ await ship.deployments.set(deployment.deployment, { labels: ['production', 'v1.0'] });
130
+ await ship.domains.set('www.example.com', { labels: ['live'] });
116
131
  ```
117
132
 
118
133
  ## Browser Usage
@@ -187,11 +202,11 @@ ship.setDeployToken(token) // Set deploy token after construction
187
202
  ### Deployments
188
203
 
189
204
  ```typescript
190
- ship.deployments.upload(input, options?) // Upload new deployment
191
- ship.deployments.list() // List all deployments
192
- ship.deployments.get(id) // Get deployment details
193
- ship.deployments.set(id, { labels }) // Update deployment labels
194
- ship.deployments.remove(id) // Delete deployment
205
+ ship.deployments.upload(input, options?) // Upload new deployment
206
+ ship.deployments.list() // List all deployments
207
+ ship.deployments.get(deployment) // Get deployment details
208
+ ship.deployments.set(deployment, { labels }) // Update deployment labels
209
+ ship.deployments.remove(deployment) // Delete deployment
195
210
  ```
196
211
 
197
212
  ### Domains
@@ -228,19 +243,19 @@ ship.account.get() // Get current account
228
243
 
229
244
  ```typescript
230
245
  // Reserve domain (no deployment yet)
231
- ship.domains.set('staging');
246
+ ship.domains.set('www.example.com');
232
247
 
233
248
  // Link domain to deployment
234
- ship.domains.set('staging', { deployment: 'abc123' });
249
+ ship.domains.set('www.example.com', { deployment: 'happy-cat-abc1234.shipstatic.com' });
235
250
 
236
251
  // Switch to a different deployment (atomic)
237
- ship.domains.set('staging', { deployment: 'xyz789' });
252
+ ship.domains.set('www.example.com', { deployment: 'other-deploy-xyz7890.shipstatic.com' });
238
253
 
239
254
  // Update labels only (deployment preserved)
240
- ship.domains.set('staging', { labels: ['prod', 'v2'] });
255
+ ship.domains.set('www.example.com', { labels: ['prod', 'v2'] });
241
256
 
242
257
  // Update both
243
- ship.domains.set('staging', { deployment: 'abc123', labels: ['prod'] });
258
+ ship.domains.set('www.example.com', { deployment: 'happy-cat-abc1234.shipstatic.com', labels: ['prod'] });
244
259
  ```
245
260
 
246
261
  **No unlinking:** Once a domain is linked, `{ deployment: null }` returns a 400 error. To take a site offline, deploy a maintenance page. To clean up, delete the domain.
@@ -248,8 +263,8 @@ ship.domains.set('staging', { deployment: 'abc123', labels: ['prod'] });
248
263
  **Domain format:** Domain names are FQDNs. The SDK accepts any format (case-insensitive, Unicode) — the API normalizes:
249
264
 
250
265
  ```typescript
251
- ship.domains.set('Example.COM', { deployment: 'abc' }); // → normalized to 'example.com'
252
- ship.domains.set('münchen.de', { deployment: 'abc' }); // → Unicode supported
266
+ ship.domains.set('WWW.Example.COM'); // → normalized to 'www.example.com'
267
+ ship.domains.set('www.münchen.de'); // → Unicode supported
253
268
  ```
254
269
 
255
270
  ### Deploy Options
@@ -263,7 +278,6 @@ ship.deploy('./dist', {
263
278
  spaDetect?: boolean, // Auto-detect SPA (default: true)
264
279
  maxConcurrency?: number, // Concurrent uploads (default: 4)
265
280
  timeout?: number, // Request timeout (ms)
266
- subdomain?: string, // Suggested subdomain
267
281
  via?: string, // Client identifier (e.g. 'sdk', 'cli')
268
282
  apiKey?: string, // Per-request API key override
269
283
  deployToken?: string, // Per-request deploy token override
package/SKILL.md CHANGED
@@ -40,10 +40,17 @@ Alternative: set the `SHIP_API_KEY` environment variable or pass `--api-key` per
40
40
  ```bash
41
41
  ship ./dist
42
42
  ship ./dist --label production --label v1.0
43
- ship ./dist --json # Returns {"deployment": "<id>", "url": "https://..."}
43
+ ship ./dist --json # Returns {"deployment": "happy-cat-abc1234.shipstatic.com", ...}
44
44
  ```
45
45
 
46
- ## Workflow 2 — Reserve a Domain
46
+ ## Workflow 2 — Deploy and Link Domain
47
+
48
+ ```bash
49
+ # Deploy and link in one pipe
50
+ ship ./dist -q | ship domains set www.example.com
51
+ ```
52
+
53
+ ## Workflow 3 — Reserve a Domain
47
54
 
48
55
  ```bash
49
56
  # Pre-flight check
@@ -53,21 +60,21 @@ ship domains validate www.example.com
53
60
  ship domains set www.example.com
54
61
 
55
62
  # Or reserve an internal subdomain (instant, no DNS)
56
- ship domains set my-site
63
+ ship domains set my-site.shipstatic.com
57
64
  ```
58
65
 
59
66
  Internal domains (`my-site.shipstatic.com`) are free and instant. Custom domains require DNS configuration — the CLI prints the required records.
60
67
 
61
68
  **Apex domains are not supported.** Always use a subdomain: `www.example.com`, not `example.com`.
62
69
 
63
- ## Workflow 3 — Link Domain to Deployment
70
+ ## Workflow 4 — Link Domain to Deployment
64
71
 
65
72
  ```bash
66
73
  # Link domain to a deployment
67
- ship domains set www.example.com <deployment-id>
74
+ ship domains set www.example.com <deployment>
68
75
 
69
76
  # Switch to a different deployment (instant rollback)
70
- ship domains set www.example.com <other-deployment-id>
77
+ ship domains set www.example.com <other-deployment>
71
78
 
72
79
  # For custom domains: verify DNS after configuring records
73
80
  ship domains verify www.example.com
@@ -78,9 +85,9 @@ ship domains verify www.example.com
78
85
  ```bash
79
86
  # Deployments
80
87
  ship deployments list
81
- ship deployments get <id>
82
- ship deployments set <id> --label production
83
- ship deployments remove <id>
88
+ ship deployments get <deployment>
89
+ ship deployments set <deployment> --label production
90
+ ship deployments remove <deployment>
84
91
 
85
92
  # Domains
86
93
  ship domains list
@@ -94,4 +101,4 @@ ship whoami
94
101
  ship ping
95
102
  ```
96
103
 
97
- Use `--json` on any command for machine-readable output.
104
+ Use `--json` on any command for machine-readable output. Use `-q` for the key identifier only.
package/dist/cli.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Ot=Object.create;var fe=Object.defineProperty;var Rt=Object.getOwnPropertyDescriptor;var kt=Object.getOwnPropertyNames;var It=Object.getPrototypeOf,Ft=Object.prototype.hasOwnProperty;var F=(e,o)=>()=>(e&&(o=e(e=0)),o);var Pt=(e,o)=>{for(var t in o)fe(e,t,{get:o[t],enumerable:!0})},$t=(e,o,t,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of kt(o))!Ft.call(e,i)&&i!==t&&fe(e,i,{get:()=>o[i],enumerable:!(n=Rt(o,i))||n.enumerable});return e};var T=(e,o,t)=>(t=e!=null?Ot(It(e)):{},$t(o||!e||!e.__esModule?fe(t,"default",{value:e,enumerable:!0}):t,e));function R(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function Se(e){let o=e.lastIndexOf(".");if(o===-1||o===e.length-1)return!1;let t=e.slice(o+1).toLowerCase();return Lt.has(t)}function Pe(e){return Nt.test(e)}function De(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(t=>be.has(t))}function te(e){if(!e.startsWith(j))throw p.validation(`API key must start with "${j}"`);if(e.length!==Ie)throw p.validation(`API key must be ${Ie} characters total (${j} + ${ge} hex chars)`);let o=e.slice(j.length);if(!/^[a-f0-9]{64}$/i.test(o))throw p.validation(`API key must contain ${ge} hexadecimal characters after "${j}" prefix`)}function $e(e){if(!e.startsWith(K))throw p.validation(`Deploy token must start with "${K}"`);if(e.length!==Fe)throw p.validation(`Deploy token must be ${Fe} characters total (${K} + ${ye} hex chars)`);let o=e.slice(K.length);if(!/^[a-f0-9]{64}$/i.test(o))throw p.validation(`Deploy token must contain ${ye} hexadecimal characters after "${K}" prefix`)}function Le(e){try{let o=new URL(e);if(!["http:","https:"].includes(o.protocol))throw p.validation("API URL must use http:// or https:// protocol");if(o.pathname!=="/"&&o.pathname!=="")throw p.validation("API URL must not contain a path");if(o.search||o.hash)throw p.validation("API URL must not contain query parameters or fragments")}catch(o){throw R(o)?o:p.validation("API URL must be a valid URL")}}var g,he,p,Lt,Nt,be,j,ge,Ie,K,ye,Fe,Ce,M,C=F(()=>{"use strict";(function(e){e.Validation="validation_failed",e.NotFound="not_found",e.RateLimit="rate_limit_exceeded",e.Authentication="authentication_failed",e.Business="business_logic_error",e.Api="internal_server_error",e.Network="network_error",e.Cancelled="operation_cancelled",e.File="file_error",e.Config="config_error"})(g||(g={}));he={client:new Set([g.Business,g.Config,g.File,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},p=class e extends Error{type;status;details;constructor(o,t,n,i){super(t),this.type=o,this.status=n,this.details=i,this.name="ShipError"}toResponse(){let o=this.type===g.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:o}}static fromResponse(o){return new e(o.error,o.message,o.status,o.details)}static validation(o,t){return new e(g.Validation,o,400,t)}static notFound(o,t){let n=t?`${o} ${t} not found`:`${o} not found`;return new e(g.NotFound,n,404)}static rateLimit(o="Too many requests"){return new e(g.RateLimit,o,429)}static authentication(o="Authentication required",t){return new e(g.Authentication,o,401,t)}static business(o,t=400){return new e(g.Business,o,t)}static network(o,t){return new e(g.Network,o,void 0,{cause:t})}static cancelled(o){return new e(g.Cancelled,o)}static file(o,t){return new e(g.File,o,void 0,{filePath:t})}static config(o,t){return new e(g.Config,o,void 0,t)}static api(o,t=500){return new e(g.Api,o,t)}static database(o,t=500){return new e(g.Api,o,t)}static storage(o,t=500){return new e(g.Api,o,t)}get filePath(){return this.details?.filePath}isClientError(){return he.client.has(this.type)}isNetworkError(){return he.network.has(this.type)}isAuthError(){return he.auth.has(this.type)}isValidationError(){return this.type===g.Validation}isFileError(){return this.type===g.File}isConfigError(){return this.type===g.Config}isType(o){return this.type===o}};Lt=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);Nt=/[\x00-\x1f\x7f#?%\\<>"]/;be=new Set(["node_modules","package.json"]);j="ship-",ge=64,Ie=j.length+ge,K="token-",ye=64,Fe=K.length+ye,Ce="ship.json";M="https://api.shipstatic.com"});function Ne(e){ve=e}function ne(){if(ve===null)throw p.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ve}var ve,ie=F(()=>{"use strict";C();ve=null});function Ut(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function P(){return Ue||Ut()}var Ue,J=F(()=>{"use strict";Ue=null});async function jt(e){let o=(await import("spark-md5")).default;return new Promise((t,n)=>{let s=Math.ceil(e.size/2097152),r=0,a=new o.ArrayBuffer,l=new FileReader,c=()=>{let d=r*2097152,h=Math.min(d+2097152,e.size);l.readAsArrayBuffer(e.slice(d,h))};l.onload=d=>{let h=d.target?.result;if(!h){n(p.business("Failed to read file chunk"));return}a.append(h),r++,r<s?c():t({md5:a.end()})},l.onerror=()=>{n(p.business("Failed to calculate MD5: FileReader error"))},c()})}async function Kt(e){let o=await import("crypto");if(Buffer.isBuffer(e)){let n=o.createHash("md5");return n.update(e),{md5:n.digest("hex")}}let t=await import("fs");return new Promise((n,i)=>{let s=o.createHash("md5"),r=t.createReadStream(e);r.on("error",a=>i(p.business(`Failed to read file for MD5: ${a.message}`))),r.on("data",a=>s.update(a)),r.on("end",()=>n({md5:s.digest("hex")}))})}async function se(e){let o=P();if(o==="browser"){if(!(e instanceof Blob))throw p.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return jt(e)}if(o==="node"){if(!(Buffer.isBuffer(e)||typeof e=="string"))throw p.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Kt(e)}throw p.business("Unknown or unsupported execution environment for MD5 calculation.")}var Ee=F(()=>{"use strict";J();C()});function Je(e,o){if(!e||e.length===0)return[];if(!o?.allowUnbuilt&&e.find(n=>n&&De(n)))throw p.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(t=>{if(!t)return!1;let n=t.replace(/\\/g,"/").split("/").filter(Boolean);if(n.length===0)return!0;let i=n[n.length-1];if((0,qe.isJunk)(i))return!1;for(let r of n)if(r!==".well-known"&&(r.startsWith(".")||r.length>255))return!1;let s=n.slice(0,-1);for(let r of s)if(Ht.some(a=>r.toLowerCase()===a.toLowerCase()))return!1;return!0})}var qe,Ht,We=F(()=>{"use strict";qe=require("junk");C();Ht=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ye(e){if(!e||e.length===0)return"";let o=e.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(o.length===0)return"";if(o.length===1)return o[0];let t=o.map(s=>s.split("/").filter(Boolean)),n=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i;s++){let r=t[0][s];if(t.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function ae(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Ae=F(()=>{"use strict"});function Xe(e,o={}){if(o.flatten===!1)return e.map(n=>({path:ae(n),name:xe(n)}));let t=Gt(e);return e.map(n=>{let i=ae(n);if(t){let s=t.endsWith("/")?t:`${t}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=xe(n)),{path:i,name:xe(n)}})}function Gt(e){if(!e.length)return"";let t=e.map(s=>ae(s)).map(s=>s.split("/")),n=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i-1;s++){let r=t[0][s];if(t.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function xe(e){return e.split(/[/\\]/).pop()||e}var Ze=F(()=>{"use strict";Ae()});function Qe(e){if(Pe(e))return{valid:!1,reason:"File name contains unsafe characters"};if(e.startsWith(" ")||e.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(e.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let o=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,t=e.split("/").pop()||e;return o.test(t)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}var et=F(()=>{"use strict";C()});function tt(e,o){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${e}" for file: ${o}`)}function ot(e,o){let t=Qe(e);if(!t.valid)throw p.business(t.reason||"Invalid file name");if(Se(e))throw p.business(`File extension not allowed: "${o}"`)}var nt=F(()=>{"use strict";C();et()});var st={};Pt(st,{processFilesForNode:()=>Vt});function it(e,o=new Set){let t=[],n=x.realpathSync(e);if(o.has(n))return t;o.add(n);let i=x.readdirSync(e);for(let s of i){let r=O.join(e,s),a=x.statSync(r);if(a.isDirectory()){let l=it(r,o);t.push(...l)}else a.isFile()&&t.push(r)}return t}async function Vt(e,o={}){if(P()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");for(let m of e){let D=O.resolve(m);try{if(x.statSync(D).isDirectory()){let k=x.readdirSync(D).find(I=>be.has(I));if(k)throw p.business(`"${k}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(k){if(R(k))throw k}}let t=e.flatMap(m=>{let D=O.resolve(m);try{return x.statSync(D).isDirectory()?it(D):[D]}catch{throw p.file(`Path does not exist: ${m}`,m)}}),n=[...new Set(t)],i=e.map(m=>O.resolve(m)),s=Ye(i.map(m=>{try{return x.statSync(m).isDirectory()?m:O.dirname(m)}catch{return O.dirname(m)}})),r=n.map(m=>{if(s&&s.length>0){let D=O.relative(s,m);if(D&&typeof D=="string"&&!D.startsWith(".."))return D.replace(/\\/g,"/")}return O.basename(m)}),a=new Set(Je(r));if(a.size===0)return[];let l=[],c=[];for(let m=0;m<n.length;m++)a.has(r[m])&&(l.push(n[m]),c.push(r[m]));let d=Xe(c,{flatten:o.pathDetect!==!1}),h=[],S=0,N=ne();for(let m=0;m<l.length;m++){let D=l[m],k=d[m].path;try{tt(k,D);let I=x.statSync(D);if(I.size===0)continue;if(ot(k,D),I.size>N.maxFileSize)throw p.business(`File ${D} is too large. Maximum allowed size is ${N.maxFileSize/(1024*1024)}MB.`);if(S+=I.size,S>N.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${N.maxTotalSize/(1024*1024)}MB.`);let q=x.readFileSync(D),{md5:xt}=await se(q);h.push({path:k,content:q,size:q.length,md5:xt})}catch(I){if(R(I))throw I;let q=I instanceof Error?I.message:String(I);throw p.file(`Failed to read file "${D}": ${q}`,D)}}if(h.length>N.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${N.maxFilesCount} files.`);return h}var x,O,rt=F(()=>{"use strict";J();Ee();We();nt();C();ie();Ze();Ae();x=T(require("fs"),1),O=T(require("path"),1)});var wt=require("commander");C();var oe=class{constructor(){this.handlers=new Map}on(o,t){this.handlers.has(o)||this.handlers.set(o,new Set),this.handlers.get(o).add(t)}off(o,t){let n=this.handlers.get(o);n&&(n.delete(t),n.size===0&&this.handlers.delete(o))}emit(o,...t){let n=this.handlers.get(o);if(!n)return;let i=Array.from(n);for(let s of i)try{s(...t)}catch(r){n.delete(s),o!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(o)):this.emit("error",new Error(String(r)),String(o))},0)}}transfer(o){this.handlers.forEach((t,n)=>{t.forEach(i=>{o.on(n,i)})})}clear(){this.handlers.clear()}};var b={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},_t=3e4,B=class extends oe{constructor(t){super();this.globalHeaders={};this.apiUrl=t.apiUrl||M,this.getAuthHeadersCallback=t.getAuthHeaders,this.useCredentials=t.useCredentials??!1,this.timeout=t.timeout??_t,this.createDeployBody=t.createDeployBody,this.deployEndpoint=t.deployEndpoint||b.DEPLOYMENTS}setGlobalHeaders(t){this.globalHeaders=t}transferEventsTo(t){this.transfer(t)}async executeRequest(t,n,i){let s=this.mergeHeaders(n.headers),{signal:r,cleanup:a}=this.createTimeoutSignal(n.signal),l={...n,headers:s,credentials:this.useCredentials&&!s.Authorization?"include":void 0,signal:r};this.emit("request",t,l);try{let c=await fetch(t,l);return a(),c.ok||await this.handleResponseError(c,i),this.emit("response",this.safeClone(c),t),{data:await this.parseResponse(this.safeClone(c)),status:c.status}}catch(c){a();let d=c instanceof Error?c:new Error(String(c));this.emit("error",d,t),this.handleFetchError(c,i)}}async request(t,n,i){let{data:s}=await this.executeRequest(t,n,i);return s}async requestWithStatus(t,n,i){return this.executeRequest(t,n,i)}mergeHeaders(t={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...t}}createTimeoutSignal(t){let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeout);if(t){let s=()=>n.abort();t.addEventListener("abort",s),t.aborted&&n.abort()}return{signal:n.signal,cleanup:()=>clearTimeout(i)}}safeClone(t){try{return t.clone()}catch{return t}}async parseResponse(t){if(!(t.headers.get("Content-Length")==="0"||t.status===204))return t.json()}async handleResponseError(t,n){let i={};try{if(t.headers.get("content-type")?.includes("application/json")){let a=await t.json();if(a&&typeof a=="object"){let l=a;typeof l.message=="string"&&(i.message=l.message),typeof l.error=="string"&&(i.error=l.error)}}else i={message:await t.text()}}catch{i={message:"Failed to parse error response"}}let s=i.message||i.error||`${n} failed`;throw t.status===401?p.authentication(s):p.api(s,t.status)}handleFetchError(t,n){throw R(t)?t:t instanceof Error&&t.name==="AbortError"?p.cancelled(`${n} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?p.network(`${n} failed: ${t.message}`,t):t instanceof Error?p.business(`${n} failed: ${t.message}`):p.business(`${n} failed: Unknown error`)}async deploy(t,n={}){if(!t.length)throw p.business("No files to deploy");for(let l of t)if(!l.md5)throw p.file(`MD5 checksum missing for file: ${l.path}`,l.path);let i=n.build||n.prerender?{build:n.build,prerender:n.prerender}:void 0,{body:s,headers:r}=await this.createDeployBody(t,n.labels,n.via,i),a={};return n.deployToken?a.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(a.Authorization=`Bearer ${n.apiKey}`),n.caller&&(a["X-Caller"]=n.caller),this.request(`${n.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:s,headers:{...r,...a},signal:n.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${b.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(t){return this.request(`${this.apiUrl}${b.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(t,n){return this.request(`${this.apiUrl}${b.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:n})},"Update deployment labels")}async removeDeployment(t){await this.request(`${this.apiUrl}${b.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove deployment")}async setDomain(t,n,i){let s={};n&&(s.deployment=n),i!==void 0&&(s.labels=i);let{data:r,status:a}=await this.requestWithStatus(`${this.apiUrl}${b.DOMAINS}/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Set domain");return{...r,isCreate:a===201}}async listDomains(){return this.request(`${this.apiUrl}${b.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(t){return this.request(`${this.apiUrl}${b.DOMAINS}/${encodeURIComponent(t)}`,{method:"GET"},"Get domain")}async removeDomain(t){await this.request(`${this.apiUrl}${b.DOMAINS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(t){return this.request(`${this.apiUrl}${b.DOMAINS}/${encodeURIComponent(t)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(t){return this.request(`${this.apiUrl}${b.DOMAINS}/${encodeURIComponent(t)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(t){return this.request(`${this.apiUrl}${b.DOMAINS}/${encodeURIComponent(t)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(t){return this.request(`${this.apiUrl}${b.DOMAINS}/${encodeURIComponent(t)}/share`,{method:"GET"},"Get domain share")}async validateDomain(t){return this.request(`${this.apiUrl}${b.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:t})},"Validate domain")}async createToken(t,n){let i={};return t!==void 0&&(i.ttl=t),n!==void 0&&(i.labels=n),this.request(`${this.apiUrl}${b.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${b.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(t){await this.request(`${this.apiUrl}${b.TOKENS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${b.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${b.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${b.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(t,n={}){let i=t.find(c=>c.path==="index.html"||c.path==="/index.html");if(!i||i.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(i.content))s=i.content.toString("utf-8");else if(typeof Blob<"u"&&i.content instanceof Blob)s=await i.content.text();else if(typeof File<"u"&&i.content instanceof File)s=await i.content.text();else return!1;let r={"Content-Type":"application/json"};n.deployToken?r.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(r.Authorization=`Bearer ${n.apiKey}`);let a={files:t.map(c=>c.path),index:s};return(await this.request(`${this.apiUrl}${b.SPA_CHECK}`,{method:"POST",headers:r,body:JSON.stringify(a)},"SPA check")).isSPA}};C();ie();C();C();function we(e={},o={}){let t={apiUrl:e.apiUrl||o.apiUrl||M,apiKey:e.apiKey!==void 0?e.apiKey:o.apiKey,deployToken:e.deployToken!==void 0?e.deployToken:o.deployToken},n={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(n.apiKey=t.apiKey),t.deployToken!==void 0&&(n.deployToken=t.deployToken),n}function _e(e,o){let t={...e};return t.apiUrl===void 0&&o.apiUrl!==void 0&&(t.apiUrl=o.apiUrl),t.apiKey===void 0&&o.apiKey!==void 0&&(t.apiKey=o.apiKey),t.deployToken===void 0&&o.deployToken!==void 0&&(t.deployToken=o.deployToken),t.timeout===void 0&&o.timeout!==void 0&&(t.timeout=o.timeout),t.maxConcurrency===void 0&&o.maxConcurrency!==void 0&&(t.maxConcurrency=o.maxConcurrency),t.onProgress===void 0&&o.onProgress!==void 0&&(t.onProgress=o.onProgress),t.caller===void 0&&o.caller!==void 0&&(t.caller=o.caller),t}C();Ee();async function Mt(){let o=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(o,"utf-8"):t=new Blob([o],{type:"application/json"});let{md5:n}=await se(t);return{path:Ce,content:t,size:o.length,md5:n}}async function je(e,o,t){if(t.spaDetect===!1||t.build||t.prerender||e.some(n=>n.path===Ce))return e;try{if(await o.checkSPA(e,t)){let i=await Mt();return[...e,i]}}catch{}return e}function Ke(e){let{getApi:o,ensureInit:t,processInput:n,clientDefaults:i,hasAuth:s}=e;return{upload:async(r,a={})=>{await t();let l=i?_e(a,i):a;if(s&&!s()&&!l.deployToken&&!l.apiKey)throw p.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw p.config("processInput function is not provided.");let c=o(),d=await n(r,l);return d=await je(d,c,l),c.deploy(d,l)},list:async()=>(await t(),o().listDeployments()),get:async r=>(await t(),o().getDeployment(r)),set:async(r,a)=>(await t(),o().updateDeploymentLabels(r,a.labels)),remove:async r=>{await t(),await o().removeDeployment(r)}}}function Me(e){let{getApi:o,ensureInit:t}=e;return{set:async(n,i={})=>(await t(),o().setDomain(n,i.deployment,i.labels)),list:async()=>(await t(),o().listDomains()),get:async n=>(await t(),o().getDomain(n)),remove:async n=>{await t(),await o().removeDomain(n)},verify:async n=>(await t(),o().verifyDomain(n)),validate:async n=>(await t(),o().validateDomain(n)),dns:async n=>(await t(),o().getDomainDns(n)),records:async n=>(await t(),o().getDomainRecords(n)),share:async n=>(await t(),o().getDomainShare(n))}}function Be(e){let{getApi:o,ensureInit:t}=e;return{get:async()=>(await t(),o().getAccount())}}function ze(e){let{getApi:o,ensureInit:t}=e;return{create:async(n={})=>(await t(),o().createToken(n.ttl,n.labels)),list:async()=>(await t(),o().listTokens()),remove:async n=>{await t(),await o().removeToken(n)}}}var re=class{constructor(o={}){this.initPromise=null;this._config=null;this.auth=null;this.customHeaders={};this.clientOptions=o,o.deployToken?this.auth={type:"token",value:o.deployToken}:o.apiKey&&(this.auth={type:"apiKey",value:o.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(o);this.http=new B({...o,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=Ke({...n,processInput:(i,s)=>this.processInput(i,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=Me(n),this._account=Be(n),this._tokens=ze(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(o,t){return this.deployments.upload(o,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=ne(),this._config)}on(o,t){this.http.on(o,t)}off(o,t){this.http.off(o,t)}setHeaders(o){this.customHeaders=o,this.http.setGlobalHeaders(o)}clearHeaders(){this.customHeaders={},this.http.setGlobalHeaders({})}replaceHttpClient(o){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(o)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=o,Object.keys(this.customHeaders).length>0&&this.http.setGlobalHeaders(this.customHeaders)}setDeployToken(o){if(!o||typeof o!="string")throw p.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:o}}setApiKey(o){if(!o||typeof o!="string")throw p.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:o}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};C();J();var z=require("zod");C();J();var Te="ship",Bt=z.z.object({apiUrl:z.z.string().url().optional(),apiKey:z.z.string().optional(),deployToken:z.z.string().optional()}).strict();function He(e){try{return Bt.parse(e)}catch(o){if(o instanceof z.z.ZodError){let t=o.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw p.config(`Configuration validation failed${n}: ${t.message}`)}throw p.config("Configuration validation failed")}}async function zt(e){try{if(P()!=="node")return{};let{cosmiconfigSync:o}=await import("cosmiconfig"),t=await import("os"),n=o(Te,{searchPlaces:[`.${Te}rc`,"package.json",`${t.homedir()}/.${Te}rc`],stopDir:t.homedir()}),i;if(e?i=n.load(e):i=n.search(),i&&i.config)return He(i.config)}catch(o){if(R(o))throw o}return{}}async function Ge(e){if(P()!=="node")return{};let o={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await zt(e),n={apiUrl:o.apiUrl??t.apiUrl,apiKey:o.apiKey??t.apiKey,deployToken:o.deployToken??t.deployToken};return He(n)}ie();C();async function Ve(e,o,t,n){let{FormData:i,File:s}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),a=new i,l=[];for(let S of e){if(!Buffer.isBuffer(S.content)&&!(typeof Blob<"u"&&S.content instanceof Blob))throw p.file(`Unsupported file.content type for Node.js: ${S.path}`,S.path);if(!S.md5)throw p.file(`File missing md5 checksum: ${S.path}`,S.path);let N=new s([S.content],S.path,{type:"application/octet-stream"});a.append("files[]",N),l.push(S.md5)}a.append("checksums",JSON.stringify(l)),o&&o.length>0&&a.append("labels",JSON.stringify(o)),t&&a.append("via",t),n?.build&&a.append("build","true"),n?.prerender&&a.append("prerender","true");let c=new r(a),d=[];for await(let S of c.encode())d.push(Buffer.from(S));let h=Buffer.concat(d);return{body:h.buffer.slice(h.byteOffset,h.byteOffset+h.byteLength),headers:{"Content-Type":c.contentType,"Content-Length":Buffer.byteLength(h).toString()}}}var le=class extends re{constructor(o={}){if(P()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");super(o)}resolveInitialConfig(o){return we(o,{})}async loadFullConfig(){try{let o=await Ge(this.clientOptions.configFile),t=we(this.clientOptions,o);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let n=new B({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();Ne(i)}catch(o){throw this.initPromise=null,o}}async processInput(o,t){let n=typeof o=="string"?[o]:o;if(!Array.isArray(n)||!n.every(s=>typeof s=="string"))throw p.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw p.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(rt(),st));return i(n,t)}getDeployBodyCreator(){return Ve}};C();var U=require("fs"),ue=T(require("path"),1);var Oe=T(require("columnify"),1),u=require("yoctocolors"),at=["isCreate"],w=(e,o,t)=>t?o:e(o),E=(e,o,t)=>{console.log(o?JSON.stringify({success:e},null,2)+`
2
+ "use strict";var Rt=Object.create;var fe=Object.defineProperty;var kt=Object.getOwnPropertyDescriptor;var Ot=Object.getOwnPropertyNames;var It=Object.getPrototypeOf,Ft=Object.prototype.hasOwnProperty;var F=(e,o)=>()=>(e&&(o=e(e=0)),o);var Pt=(e,o)=>{for(var t in o)fe(e,t,{get:o[t],enumerable:!0})},$t=(e,o,t,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of Ot(o))!Ft.call(e,i)&&i!==t&&fe(e,i,{get:()=>o[i],enumerable:!(n=kt(o,i))||n.enumerable});return e};var T=(e,o,t)=>(t=e!=null?Rt(It(e)):{},$t(o||!e||!e.__esModule?fe(t,"default",{value:e,enumerable:!0}):t,e));function k(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function Se(e){let o=e.lastIndexOf(".");if(o===-1||o===e.length-1)return!1;let t=e.slice(o+1).toLowerCase();return Lt.has(t)}function Pe(e){return Nt.test(e)}function De(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(t=>be.has(t))}function te(e){if(!e.startsWith(j))throw c.validation(`API key must start with "${j}"`);if(e.length!==Ie)throw c.validation(`API key must be ${Ie} characters total (${j} + ${ge} hex chars)`);let o=e.slice(j.length);if(!/^[a-f0-9]{64}$/i.test(o))throw c.validation(`API key must contain ${ge} hexadecimal characters after "${j}" prefix`)}function $e(e){if(!e.startsWith(M))throw c.validation(`Deploy token must start with "${M}"`);if(e.length!==Fe)throw c.validation(`Deploy token must be ${Fe} characters total (${M} + ${ye} hex chars)`);let o=e.slice(M.length);if(!/^[a-f0-9]{64}$/i.test(o))throw c.validation(`Deploy token must contain ${ye} hexadecimal characters after "${M}" prefix`)}function Le(e){try{let o=new URL(e);if(!["http:","https:"].includes(o.protocol))throw c.validation("API URL must use http:// or https:// protocol");if(o.pathname!=="/"&&o.pathname!=="")throw c.validation("API URL must not contain a path");if(o.search||o.hash)throw c.validation("API URL must not contain query parameters or fragments")}catch(o){throw k(o)?o:c.validation("API URL must be a valid URL")}}var g,he,c,Lt,Nt,be,j,ge,Ie,M,ye,Fe,Ce,K,C=F(()=>{"use strict";(function(e){e.Validation="validation_failed",e.NotFound="not_found",e.RateLimit="rate_limit_exceeded",e.Authentication="authentication_failed",e.Business="business_logic_error",e.Api="internal_server_error",e.Network="network_error",e.Cancelled="operation_cancelled",e.File="file_error",e.Config="config_error"})(g||(g={}));he={client:new Set([g.Business,g.Config,g.File,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},c=class e extends Error{type;status;details;constructor(o,t,n,i){super(t),this.type=o,this.status=n,this.details=i,this.name="ShipError"}toResponse(){let o=this.type===g.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:o}}static fromResponse(o){return new e(o.error,o.message,o.status,o.details)}static validation(o,t){return new e(g.Validation,o,400,t)}static notFound(o,t){let n=t?`${o} ${t} not found`:`${o} not found`;return new e(g.NotFound,n,404)}static rateLimit(o="Too many requests"){return new e(g.RateLimit,o,429)}static authentication(o="Authentication required",t){return new e(g.Authentication,o,401,t)}static business(o,t=400){return new e(g.Business,o,t)}static network(o,t){return new e(g.Network,o,void 0,{cause:t})}static cancelled(o){return new e(g.Cancelled,o)}static file(o,t){return new e(g.File,o,void 0,{filePath:t})}static config(o,t){return new e(g.Config,o,void 0,t)}static api(o,t=500){return new e(g.Api,o,t)}static database(o,t=500){return new e(g.Api,o,t)}static storage(o,t=500){return new e(g.Api,o,t)}get filePath(){return this.details?.filePath}isClientError(){return he.client.has(this.type)}isNetworkError(){return he.network.has(this.type)}isAuthError(){return he.auth.has(this.type)}isValidationError(){return this.type===g.Validation}isFileError(){return this.type===g.File}isConfigError(){return this.type===g.Config}isType(o){return this.type===o}};Lt=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);Nt=/[\x00-\x1f\x7f#?%\\<>"]/;be=new Set(["node_modules","package.json"]);j="ship-",ge=64,Ie=j.length+ge,M="token-",ye=64,Fe=M.length+ye,Ce="ship.json";K="https://api.shipstatic.com"});function Ne(e){ve=e}function ne(){if(ve===null)throw c.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ve}var ve,ie=F(()=>{"use strict";C();ve=null});function Ut(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function P(){return Ue||Ut()}var Ue,J=F(()=>{"use strict";Ue=null});async function jt(e){let o=(await import("spark-md5")).default;return new Promise((t,n)=>{let s=Math.ceil(e.size/2097152),r=0,a=new o.ArrayBuffer,l=new FileReader,p=()=>{let d=r*2097152,h=Math.min(d+2097152,e.size);l.readAsArrayBuffer(e.slice(d,h))};l.onload=d=>{let h=d.target?.result;if(!h){n(c.business("Failed to read file chunk"));return}a.append(h),r++,r<s?p():t({md5:a.end()})},l.onerror=()=>{n(c.business("Failed to calculate MD5: FileReader error"))},p()})}async function Mt(e){let o=await import("crypto");if(Buffer.isBuffer(e)){let n=o.createHash("md5");return n.update(e),{md5:n.digest("hex")}}let t=await import("fs");return new Promise((n,i)=>{let s=o.createHash("md5"),r=t.createReadStream(e);r.on("error",a=>i(c.business(`Failed to read file for MD5: ${a.message}`))),r.on("data",a=>s.update(a)),r.on("end",()=>n({md5:s.digest("hex")}))})}async function se(e){let o=P();if(o==="browser"){if(!(e instanceof Blob))throw c.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return jt(e)}if(o==="node"){if(!(Buffer.isBuffer(e)||typeof e=="string"))throw c.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Mt(e)}throw c.business("Unknown or unsupported execution environment for MD5 calculation.")}var Ee=F(()=>{"use strict";J();C()});function Je(e,o){if(!e||e.length===0)return[];if(!o?.allowUnbuilt&&e.find(n=>n&&De(n)))throw c.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(t=>{if(!t)return!1;let n=t.replace(/\\/g,"/").split("/").filter(Boolean);if(n.length===0)return!0;let i=n[n.length-1];if((0,qe.isJunk)(i))return!1;for(let r of n)if(r!==".well-known"&&(r.startsWith(".")||r.length>255))return!1;let s=n.slice(0,-1);for(let r of s)if(Ht.some(a=>r.toLowerCase()===a.toLowerCase()))return!1;return!0})}var qe,Ht,We=F(()=>{"use strict";qe=require("junk");C();Ht=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ye(e){if(!e||e.length===0)return"";let o=e.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(o.length===0)return"";if(o.length===1)return o[0];let t=o.map(s=>s.split("/").filter(Boolean)),n=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i;s++){let r=t[0][s];if(t.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function ae(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Ae=F(()=>{"use strict"});function Xe(e,o={}){if(o.flatten===!1)return e.map(n=>({path:ae(n),name:xe(n)}));let t=Gt(e);return e.map(n=>{let i=ae(n);if(t){let s=t.endsWith("/")?t:`${t}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=xe(n)),{path:i,name:xe(n)}})}function Gt(e){if(!e.length)return"";let t=e.map(s=>ae(s)).map(s=>s.split("/")),n=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i-1;s++){let r=t[0][s];if(t.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function xe(e){return e.split(/[/\\]/).pop()||e}var Ze=F(()=>{"use strict";Ae()});function Qe(e){if(Pe(e))return{valid:!1,reason:"File name contains unsafe characters"};if(e.startsWith(" ")||e.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(e.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let o=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,t=e.split("/").pop()||e;return o.test(t)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}var et=F(()=>{"use strict";C()});function tt(e,o){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw c.business(`Security error: Unsafe file path "${e}" for file: ${o}`)}function ot(e,o){let t=Qe(e);if(!t.valid)throw c.business(t.reason||"Invalid file name");if(Se(e))throw c.business(`File extension not allowed: "${o}"`)}var nt=F(()=>{"use strict";C();et()});var st={};Pt(st,{processFilesForNode:()=>Vt});function it(e,o=new Set){let t=[],n=x.realpathSync(e);if(o.has(n))return t;o.add(n);let i=x.readdirSync(e);for(let s of i){let r=R.join(e,s),a=x.statSync(r);if(a.isDirectory()){let l=it(r,o);t.push(...l)}else a.isFile()&&t.push(r)}return t}async function Vt(e,o={}){if(P()!=="node")throw c.business("processFilesForNode can only be called in Node.js environment.");for(let m of e){let D=R.resolve(m);try{if(x.statSync(D).isDirectory()){let O=x.readdirSync(D).find(I=>be.has(I));if(O)throw c.business(`"${O}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(O){if(k(O))throw O}}let t=e.flatMap(m=>{let D=R.resolve(m);try{return x.statSync(D).isDirectory()?it(D):[D]}catch{throw c.file(`Path does not exist: ${m}`,m)}}),n=[...new Set(t)],i=e.map(m=>R.resolve(m)),s=Ye(i.map(m=>{try{return x.statSync(m).isDirectory()?m:R.dirname(m)}catch{return R.dirname(m)}})),r=n.map(m=>{if(s&&s.length>0){let D=R.relative(s,m);if(D&&typeof D=="string"&&!D.startsWith(".."))return D.replace(/\\/g,"/")}return R.basename(m)}),a=new Set(Je(r));if(a.size===0)return[];let l=[],p=[];for(let m=0;m<n.length;m++)a.has(r[m])&&(l.push(n[m]),p.push(r[m]));let d=Xe(p,{flatten:o.pathDetect!==!1}),h=[],S=0,N=ne();for(let m=0;m<l.length;m++){let D=l[m],O=d[m].path;try{tt(O,D);let I=x.statSync(D);if(I.size===0)continue;if(ot(O,D),I.size>N.maxFileSize)throw c.business(`File ${D} is too large. Maximum allowed size is ${N.maxFileSize/(1024*1024)}MB.`);if(S+=I.size,S>N.maxTotalSize)throw c.business(`Total deploy size is too large. Maximum allowed is ${N.maxTotalSize/(1024*1024)}MB.`);let q=x.readFileSync(D),{md5:xt}=await se(q);h.push({path:O,content:q,size:q.length,md5:xt})}catch(I){if(k(I))throw I;let q=I instanceof Error?I.message:String(I);throw c.file(`Failed to read file "${D}": ${q}`,D)}}if(h.length>N.maxFilesCount)throw c.business(`Too many files to deploy. Maximum allowed is ${N.maxFilesCount} files.`);return h}var x,R,rt=F(()=>{"use strict";J();Ee();We();nt();C();ie();Ze();Ae();x=T(require("fs"),1),R=T(require("path"),1)});var wt=require("commander");C();var oe=class{constructor(){this.handlers=new Map}on(o,t){this.handlers.has(o)||this.handlers.set(o,new Set),this.handlers.get(o).add(t)}off(o,t){let n=this.handlers.get(o);n&&(n.delete(t),n.size===0&&this.handlers.delete(o))}emit(o,...t){let n=this.handlers.get(o);if(!n)return;let i=Array.from(n);for(let s of i)try{s(...t)}catch(r){n.delete(s),o!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(o)):this.emit("error",new Error(String(r)),String(o))},0)}}transfer(o){this.handlers.forEach((t,n)=>{t.forEach(i=>{o.on(n,i)})})}clear(){this.handlers.clear()}};var b={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},_t=3e4,z=class extends oe{constructor(t){super();this.globalHeaders={};this.apiUrl=t.apiUrl||K,this.getAuthHeadersCallback=t.getAuthHeaders,this.useCredentials=t.useCredentials??!1,this.timeout=t.timeout??_t,this.createDeployBody=t.createDeployBody,this.deployEndpoint=t.deployEndpoint||b.DEPLOYMENTS}setGlobalHeaders(t){this.globalHeaders=t}transferEventsTo(t){this.transfer(t)}async executeRequest(t,n,i){let s=this.mergeHeaders(n.headers),{signal:r,cleanup:a}=this.createTimeoutSignal(n.signal),l={...n,headers:s,credentials:this.useCredentials&&!s.Authorization?"include":void 0,signal:r};this.emit("request",t,l);try{let p=await fetch(t,l);return a(),p.ok||await this.handleResponseError(p,i),this.emit("response",this.safeClone(p),t),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(p){a();let d=p instanceof Error?p:new Error(String(p));this.emit("error",d,t),this.handleFetchError(p,i)}}async request(t,n,i){let{data:s}=await this.executeRequest(t,n,i);return s}async requestWithStatus(t,n,i){return this.executeRequest(t,n,i)}mergeHeaders(t={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...t}}createTimeoutSignal(t){let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeout);if(t){let s=()=>n.abort();t.addEventListener("abort",s),t.aborted&&n.abort()}return{signal:n.signal,cleanup:()=>clearTimeout(i)}}safeClone(t){try{return t.clone()}catch{return t}}async parseResponse(t){if(!(t.headers.get("Content-Length")==="0"||t.status===204))return t.json()}async handleResponseError(t,n){let i={};try{if(t.headers.get("content-type")?.includes("application/json")){let a=await t.json();if(a&&typeof a=="object"){let l=a;typeof l.message=="string"&&(i.message=l.message),typeof l.error=="string"&&(i.error=l.error)}}else i={message:await t.text()}}catch{i={message:"Failed to parse error response"}}let s=i.message||i.error||`${n} failed`;throw t.status===401?c.authentication(s):c.api(s,t.status)}handleFetchError(t,n){throw k(t)?t:t instanceof Error&&t.name==="AbortError"?c.cancelled(`${n} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?c.network(`${n} failed: ${t.message}`,t):t instanceof Error?c.business(`${n} failed: ${t.message}`):c.business(`${n} failed: Unknown error`)}async deploy(t,n={}){if(!t.length)throw c.business("No files to deploy");for(let l of t)if(!l.md5)throw c.file(`MD5 checksum missing for file: ${l.path}`,l.path);let i=n.build||n.prerender?{build:n.build,prerender:n.prerender}:void 0,{body:s,headers:r}=await this.createDeployBody(t,n.labels,n.via,i),a={};return n.deployToken?a.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(a.Authorization=`Bearer ${n.apiKey}`),n.caller&&(a["X-Caller"]=n.caller),this.request(`${n.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:s,headers:{...r,...a},signal:n.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${b.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(t){return this.request(`${this.apiUrl}${b.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(t,n){return this.request(`${this.apiUrl}${b.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:n})},"Update deployment labels")}async removeDeployment(t){await this.request(`${this.apiUrl}${b.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove deployment")}async setDomain(t,n,i){let s={};n&&(s.deployment=n),i!==void 0&&(s.labels=i);let{data:r,status:a}=await this.requestWithStatus(`${this.apiUrl}${b.DOMAINS}/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Set domain");return{...r,isCreate:a===201}}async listDomains(){return this.request(`${this.apiUrl}${b.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(t){return this.request(`${this.apiUrl}${b.DOMAINS}/${encodeURIComponent(t)}`,{method:"GET"},"Get domain")}async removeDomain(t){await this.request(`${this.apiUrl}${b.DOMAINS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(t){return this.request(`${this.apiUrl}${b.DOMAINS}/${encodeURIComponent(t)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(t){return this.request(`${this.apiUrl}${b.DOMAINS}/${encodeURIComponent(t)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(t){return this.request(`${this.apiUrl}${b.DOMAINS}/${encodeURIComponent(t)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(t){return this.request(`${this.apiUrl}${b.DOMAINS}/${encodeURIComponent(t)}/share`,{method:"GET"},"Get domain share")}async validateDomain(t){return this.request(`${this.apiUrl}${b.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:t})},"Validate domain")}async createToken(t,n){let i={};return t!==void 0&&(i.ttl=t),n!==void 0&&(i.labels=n),this.request(`${this.apiUrl}${b.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${b.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(t){await this.request(`${this.apiUrl}${b.TOKENS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${b.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${b.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${b.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(t,n={}){let i=t.find(p=>p.path==="index.html"||p.path==="/index.html");if(!i||i.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(i.content))s=i.content.toString("utf-8");else if(typeof Blob<"u"&&i.content instanceof Blob)s=await i.content.text();else if(typeof File<"u"&&i.content instanceof File)s=await i.content.text();else return!1;let r={"Content-Type":"application/json"};n.deployToken?r.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(r.Authorization=`Bearer ${n.apiKey}`);let a={files:t.map(p=>p.path),index:s};return(await this.request(`${this.apiUrl}${b.SPA_CHECK}`,{method:"POST",headers:r,body:JSON.stringify(a)},"SPA check")).isSPA}};C();ie();C();C();function we(e={},o={}){let t={apiUrl:e.apiUrl||o.apiUrl||K,apiKey:e.apiKey!==void 0?e.apiKey:o.apiKey,deployToken:e.deployToken!==void 0?e.deployToken:o.deployToken},n={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(n.apiKey=t.apiKey),t.deployToken!==void 0&&(n.deployToken=t.deployToken),n}function _e(e,o){let t={...e};return t.apiUrl===void 0&&o.apiUrl!==void 0&&(t.apiUrl=o.apiUrl),t.apiKey===void 0&&o.apiKey!==void 0&&(t.apiKey=o.apiKey),t.deployToken===void 0&&o.deployToken!==void 0&&(t.deployToken=o.deployToken),t.timeout===void 0&&o.timeout!==void 0&&(t.timeout=o.timeout),t.maxConcurrency===void 0&&o.maxConcurrency!==void 0&&(t.maxConcurrency=o.maxConcurrency),t.onProgress===void 0&&o.onProgress!==void 0&&(t.onProgress=o.onProgress),t.caller===void 0&&o.caller!==void 0&&(t.caller=o.caller),t}C();Ee();async function Kt(){let o=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(o,"utf-8"):t=new Blob([o],{type:"application/json"});let{md5:n}=await se(t);return{path:Ce,content:t,size:o.length,md5:n}}async function je(e,o,t){if(t.spaDetect===!1||t.build||t.prerender||e.some(n=>n.path===Ce))return e;try{if(await o.checkSPA(e,t)){let i=await Kt();return[...e,i]}}catch{}return e}function Me(e){let{getApi:o,ensureInit:t,processInput:n,clientDefaults:i,hasAuth:s}=e;return{upload:async(r,a={})=>{await t();let l=i?_e(a,i):a;if(s&&!s()&&!l.deployToken&&!l.apiKey)throw c.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw c.config("processInput function is not provided.");let p=o(),d=await n(r,l);return d=await je(d,p,l),p.deploy(d,l)},list:async()=>(await t(),o().listDeployments()),get:async r=>(await t(),o().getDeployment(r)),set:async(r,a)=>(await t(),o().updateDeploymentLabels(r,a.labels)),remove:async r=>{await t(),await o().removeDeployment(r)}}}function Ke(e){let{getApi:o,ensureInit:t}=e;return{set:async(n,i={})=>(await t(),o().setDomain(n,i.deployment,i.labels)),list:async()=>(await t(),o().listDomains()),get:async n=>(await t(),o().getDomain(n)),remove:async n=>{await t(),await o().removeDomain(n)},verify:async n=>(await t(),o().verifyDomain(n)),validate:async n=>(await t(),o().validateDomain(n)),dns:async n=>(await t(),o().getDomainDns(n)),records:async n=>(await t(),o().getDomainRecords(n)),share:async n=>(await t(),o().getDomainShare(n))}}function ze(e){let{getApi:o,ensureInit:t}=e;return{get:async()=>(await t(),o().getAccount())}}function Be(e){let{getApi:o,ensureInit:t}=e;return{create:async(n={})=>(await t(),o().createToken(n.ttl,n.labels)),list:async()=>(await t(),o().listTokens()),remove:async n=>{await t(),await o().removeToken(n)}}}var re=class{constructor(o={}){this.initPromise=null;this._config=null;this.auth=null;this.customHeaders={};this.clientOptions=o,o.deployToken?this.auth={type:"token",value:o.deployToken}:o.apiKey&&(this.auth={type:"apiKey",value:o.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(o);this.http=new z({...o,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=Me({...n,processInput:(i,s)=>this.processInput(i,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=Ke(n),this._account=ze(n),this._tokens=Be(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(o,t){return this.deployments.upload(o,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=ne(),this._config)}on(o,t){this.http.on(o,t)}off(o,t){this.http.off(o,t)}setHeaders(o){this.customHeaders=o,this.http.setGlobalHeaders(o)}clearHeaders(){this.customHeaders={},this.http.setGlobalHeaders({})}replaceHttpClient(o){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(o)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=o,Object.keys(this.customHeaders).length>0&&this.http.setGlobalHeaders(this.customHeaders)}setDeployToken(o){if(!o||typeof o!="string")throw c.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:o}}setApiKey(o){if(!o||typeof o!="string")throw c.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:o}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};C();J();var B=require("zod");C();J();var Te="ship",zt=B.z.object({apiUrl:B.z.string().url().optional(),apiKey:B.z.string().optional(),deployToken:B.z.string().optional()}).strict();function He(e){try{return zt.parse(e)}catch(o){if(o instanceof B.z.ZodError){let t=o.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw c.config(`Configuration validation failed${n}: ${t.message}`)}throw c.config("Configuration validation failed")}}async function Bt(e){try{if(P()!=="node")return{};let{cosmiconfigSync:o}=await import("cosmiconfig"),t=await import("os"),n=o(Te,{searchPlaces:[`.${Te}rc`,"package.json",`${t.homedir()}/.${Te}rc`],stopDir:t.homedir()}),i;if(e?i=n.load(e):i=n.search(),i&&i.config)return He(i.config)}catch(o){if(k(o))throw o}return{}}async function Ge(e){if(P()!=="node")return{};let o={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await Bt(e),n={apiUrl:o.apiUrl??t.apiUrl,apiKey:o.apiKey??t.apiKey,deployToken:o.deployToken??t.deployToken};return He(n)}ie();C();async function Ve(e,o,t,n){let{FormData:i,File:s}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),a=new i,l=[];for(let S of e){if(!Buffer.isBuffer(S.content)&&!(typeof Blob<"u"&&S.content instanceof Blob))throw c.file(`Unsupported file.content type for Node.js: ${S.path}`,S.path);if(!S.md5)throw c.file(`File missing md5 checksum: ${S.path}`,S.path);let N=new s([S.content],S.path,{type:"application/octet-stream"});a.append("files[]",N),l.push(S.md5)}a.append("checksums",JSON.stringify(l)),o&&o.length>0&&a.append("labels",JSON.stringify(o)),t&&a.append("via",t),n?.build&&a.append("build","true"),n?.prerender&&a.append("prerender","true");let p=new r(a),d=[];for await(let S of p.encode())d.push(Buffer.from(S));let h=Buffer.concat(d);return{body:h.buffer.slice(h.byteOffset,h.byteOffset+h.byteLength),headers:{"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(h).toString()}}}var le=class extends re{constructor(o={}){if(P()!=="node")throw c.business("Node.js Ship class can only be used in Node.js environment.");super(o)}resolveInitialConfig(o){return we(o,{})}async loadFullConfig(){try{let o=await Ge(this.clientOptions.configFile),t=we(this.clientOptions,o);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let n=new z({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();Ne(i)}catch(o){throw this.initPromise=null,o}}async processInput(o,t){let n=typeof o=="string"?[o]:o;if(!Array.isArray(n)||!n.every(s=>typeof s=="string"))throw c.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw c.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(rt(),st));return i(n,t)}getDeployBodyCreator(){return Ve}};C();var U=require("fs"),ue=T(require("path"),1);var Re=T(require("columnify"),1),u=require("yoctocolors"),at=["isCreate"],w=(e,o,t)=>t?o:e(o),E=(e,o,t)=>{console.log(o?JSON.stringify({success:e},null,2)+`
3
3
  `:`${w(u.green,e.toLowerCase().replace(/\.$/,""),t)}
4
4
  `)},A=(e,o,t)=>{if(o)console.error(JSON.stringify({error:e},null,2)+`
5
5
  `);else{let n=w(s=>(0,u.inverse)((0,u.red)(s)),`${w(u.hidden,"[",t)}error${w(u.hidden,"]",t)}`,t),i=w(u.red,e.toLowerCase().replace(/\.$/,""),t);console.error(`${n} ${i}
@@ -7,34 +7,34 @@
7
7
  `);else{let n=w(s=>(0,u.inverse)((0,u.yellow)(s)),`${w(u.hidden,"[",t)}warning${w(u.hidden,"]",t)}`,t),i=w(u.yellow,e.toLowerCase().replace(/\.$/,""),t);console.log(`${n} ${i}
8
8
  `)}},H=(e,o,t)=>{if(o)console.log(JSON.stringify({info:e},null,2)+`
9
9
  `);else{let n=w(s=>(0,u.inverse)((0,u.blue)(s)),`${w(u.hidden,"[",t)}info${w(u.hidden,"]",t)}`,t),i=w(u.blue,e.toLowerCase().replace(/\.$/,""),t);console.log(`${n} ${i}
10
- `)}},qt=(e,o="details",t)=>{if(e==null||e===0)return"-";let n=new Date(e*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return o==="table"?n.replace(/T/,w(u.hidden,"T",t)).replace(/Z$/,w(u.hidden,"Z",t)):n},lt=(e,o,t="details",n)=>{if(o===null)return"-";if(typeof o=="number"&&(e==="created"||e==="activated"||e==="expires"||e==="linked"||e==="grace"))return qt(o,t,n);if(e==="size"&&typeof o=="number"){let i=o/1048576;return i>=1?`${i.toFixed(1)}Mb`:`${(o/1024).toFixed(1)}Kb`}if(e==="config"){if(typeof o=="boolean")return o?"yes":"no";if(typeof o=="number")return o===1?"yes":"no"}return String(o)},ce=(e,o,t,n)=>{if(!e||e.length===0)return"";let i=e[0],s=o||Object.keys(i).filter(l=>i[l]!==void 0&&!at.includes(l)),r=e.map(l=>{let c=l,d={};return s.forEach(h=>{h in c&&c[h]!==void 0&&(d[h]=lt(h,c[h],"table",t))}),d});return(0,Oe.default)(r,{columnSplitter:" ",columns:s,config:s.reduce((l,c)=>(l[c]={headingTransform:d=>w(u.dim,n?.[d]||d,t)},l),{})}).split(`
10
+ `)}},qt=(e,o="details",t)=>{if(e==null||e===0)return"-";let n=new Date(e*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return o==="table"?n.replace(/T/,w(u.hidden,"T",t)).replace(/Z$/,w(u.hidden,"Z",t)):n},lt=(e,o,t="details",n)=>{if(o===null)return"-";if(typeof o=="number"&&(e==="created"||e==="activated"||e==="expires"||e==="linked"||e==="grace"))return qt(o,t,n);if(e==="size"&&typeof o=="number"){let i=o/1048576;return i>=1?`${i.toFixed(1)}Mb`:`${(o/1024).toFixed(1)}Kb`}if(e==="config"){if(typeof o=="boolean")return o?"yes":"no";if(typeof o=="number")return o===1?"yes":"no"}return String(o)},ce=(e,o,t,n)=>{if(!e||e.length===0)return"";let i=e[0],s=o||Object.keys(i).filter(l=>i[l]!==void 0&&!at.includes(l)),r=e.map(l=>{let p=l,d={};return s.forEach(h=>{h in p&&p[h]!==void 0&&(d[h]=lt(h,p[h],"table",t))}),d});return(0,Re.default)(r,{columnSplitter:" ",columns:s,config:s.reduce((l,p)=>(l[p]={headingTransform:d=>w(u.dim,n?.[d]||d,t)},l),{})}).split(`
11
11
  `).map(l=>l.replace(/\0/g,"").replace(/\s+$/,"")).join(`
12
12
  `)+`
13
- `},W=(e,o)=>{let t=Object.entries(e).filter(([s,r])=>at.includes(s)?!1:r!==void 0);if(t.length===0)return"";let n=t.map(([s,r])=>({property:s+":",value:lt(s,r,"details",o)}));return(0,Oe.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>w(u.dim,s,o)}}}).split(`
13
+ `},W=(e,o)=>{let t=Object.entries(e).filter(([s,r])=>at.includes(s)?!1:r!==void 0);if(t.length===0)return"";let n=t.map(([s,r])=>({property:s+":",value:lt(s,r,"details",o)}));return(0,Re.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>w(u.dim,s,o)}}}).split(`
14
14
  `).map(s=>s.replace(/\0/g,"")).join(`
15
15
  `)+`
16
- `};function Jt(e,o,t){let{noColor:n}=t;if(e.deployments.length===0){console.log("no deployments found"),console.log();return}let i=["deployment","labels","created"];console.log(ce(e.deployments,i,n))}function Wt(e,o,t){let{noColor:n}=t;if(e.domains.length===0){console.log("no domains found"),console.log();return}let i=["domain","deployment","labels","linked","created"];console.log(ce(e.domains,i,n))}function Yt(e,o,t){let{noColor:n}=t,{_dnsRecords:i,_shareHash:s,isCreate:r,...a}=e;if(o.operation==="set"){let l=r?"created":"updated";E(`${e.domain} domain ${l}`,!1,n)}i&&i.length>0&&(console.log(),H("DNS Records to configure:",!1,n),i.forEach(l=>{console.log(` ${l.type}: ${l.name} \u2192 ${l.value}`)})),s&&(console.log(),H(`Setup instructions: https://setup.shipstatic.com/${s}/${e.domain}`,!1,n)),console.log(),console.log(W(a,n))}function Xt(e,o,t){let{noColor:n}=t;o.operation==="upload"&&E(`${e.deployment} deployment uploaded`,!1,n),console.log(W(e,n))}function Zt(e,o,t){let{noColor:n}=t;console.log(W(e,n))}function Qt(e,o,t){let{noColor:n}=t;e.message&&E(e.message,!1,n)}function eo(e,o,t){let{noColor:n}=t;if(e.valid){if(E("domain is valid",!1,n),console.log(),e.normalized&&console.log(` normalized: ${e.normalized}`),e.available!==null){let i=e.available?"available \u2713":"already taken";console.log(` availability: ${i}`)}console.log()}else A(e.error||"domain is invalid",!1,n)}function to(e,o,t){let{noColor:n}=t;if(e.tokens.length===0){console.log("no tokens found"),console.log();return}let i=["token","labels","created","expires"];console.log(ce(e.tokens,i,n))}function oo(e,o,t){let{noColor:n}=t;o.operation==="create"&&e.token&&E(`token ${e.token} created`,!1,n),console.log(W(e,n))}function pt(e,o,t){let{json:n,noColor:i}=t;if(e===void 0){o.operation==="remove"&&o.resourceType&&o.resourceId?E(`${o.resourceId} ${o.resourceType.toLowerCase()} removed`,n,i):E("removed successfully",n,i);return}if(typeof e=="boolean"){e?E("api reachable",n,i):A("api unreachable",n,i);return}if(n&&e!==null&&typeof e=="object"){let s={...e};delete s._dnsRecords,delete s._shareHash,delete s.isCreate,console.log(JSON.stringify(s,null,2)),console.log();return}e!==null&&typeof e=="object"?"deployments"in e?Jt(e,o,t):"domains"in e?Wt(e,o,t):"tokens"in e?to(e,o,t):"domain"in e?Yt(e,o,t):"deployment"in e?Xt(e,o,t):"token"in e?oo(e,o,t):"email"in e?Zt(e,o,t):"valid"in e?eo(e,o,t):"message"in e?Qt(e,o,t):E("success",n,i):E("success",n,i)}var y=T(require("fs"),1),$=T(require("path"),1),Re=T(require("os"),1);function ct(){let e=process.env.SHELL||"";return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":null}function dt(e,o){switch(e){case"bash":return{completionFile:$.join(o,".ship_completion.bash"),profileFile:$.join(o,".bash_profile"),scriptName:"ship.bash"};case"zsh":return{completionFile:$.join(o,".ship_completion.zsh"),profileFile:$.join(o,".zshrc"),scriptName:"ship.zsh"};case"fish":return{completionFile:$.join(o,".config/fish/completions/ship.fish"),profileFile:null,scriptName:"ship.fish"}}}function ut(e,o={}){let{json:t,noColor:n}=o,i=ct(),s=Re.homedir();if(!i){A(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,t,n);return}let r=dt(i,s),a=$.join(e,r.scriptName);try{if(i==="fish"){let c=$.dirname(r.completionFile);y.existsSync(c)||y.mkdirSync(c,{recursive:!0}),y.copyFileSync(a,r.completionFile),E("fish completion installed successfully",t,n),H("please restart your shell to apply the changes",t,n);return}y.copyFileSync(a,r.completionFile);let l=`# ship
16
+ `};function Jt(e,o,t){let{noColor:n}=t;if(e.deployments.length===0){console.log("no deployments found"),console.log();return}let i=["deployment","labels","created"];console.log(ce(e.deployments,i,n))}function Wt(e,o,t){let{noColor:n}=t;if(e.domains.length===0){console.log("no domains found"),console.log();return}let i=["domain","deployment","labels","linked","created"];console.log(ce(e.domains,i,n))}function Yt(e,o,t){let{noColor:n}=t,{_dnsRecords:i,_shareHash:s,isCreate:r,...a}=e;if(o.operation==="set"){let l=r?"created":"updated";E(`${e.domain} domain ${l}`,!1,n)}i&&i.length>0&&(console.log(),H("DNS Records to configure:",!1,n),i.forEach(l=>{console.log(` ${l.type}: ${l.name} \u2192 ${l.value}`)})),s&&(console.log(),H(`Setup instructions: https://setup.shipstatic.com/${s}/${e.domain}`,!1,n)),console.log(),console.log(W(a,n))}function Xt(e,o,t){let{noColor:n}=t;o.operation==="upload"&&E(`${e.deployment} deployment uploaded`,!1,n),console.log(W(e,n))}function Zt(e,o,t){let{noColor:n}=t;console.log(W(e,n))}function Qt(e,o,t){let{noColor:n}=t;e.message&&E(e.message,!1,n)}function eo(e,o,t){let{noColor:n}=t;if(e.valid){if(E("domain is valid",!1,n),console.log(),e.normalized&&console.log(` normalized: ${e.normalized}`),e.available!==null){let i=e.available?"available \u2713":"already taken";console.log(` availability: ${i}`)}console.log()}else A(e.error||"domain is invalid",!1,n)}function to(e,o,t){let{noColor:n}=t;if(e.tokens.length===0){console.log("no tokens found"),console.log();return}let i=["token","labels","created","expires"];console.log(ce(e.tokens,i,n))}function oo(e,o,t){let{noColor:n}=t;o.operation==="create"&&e.token&&E(`token ${e.token} created`,!1,n),console.log(W(e,n))}function pt(e,o,t){let{json:n,quiet:i,noColor:s}=t;if(i){if(e===void 0||typeof e=="boolean")return;if(e!==null&&typeof e=="object")if("deployments"in e)e.deployments.forEach(r=>console.log(r.deployment));else if("domains"in e)e.domains.forEach(r=>console.log(r.domain));else if("tokens"in e)e.tokens.forEach(r=>console.log(r.token));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 r=e;r.valid&&r.normalized&&console.log(r.normalized)}else"message"in e&&console.log(e.message);return}if(e===void 0){o.operation==="remove"&&o.resourceType&&o.resourceId?E(`${o.resourceId} ${o.resourceType.toLowerCase()} removed`,n,s):E("removed successfully",n,s);return}if(typeof e=="boolean"){e?E("api reachable",n,s):A("api unreachable",n,s);return}if(n&&e!==null&&typeof e=="object"){let r={...e};delete r._dnsRecords,delete r._shareHash,delete r.isCreate,console.log(JSON.stringify(r,null,2)),console.log();return}e!==null&&typeof e=="object"?"deployments"in e?Jt(e,o,t):"domains"in e?Wt(e,o,t):"tokens"in e?to(e,o,t):"domain"in e?Yt(e,o,t):"deployment"in e?Xt(e,o,t):"token"in e?oo(e,o,t):"email"in e?Zt(e,o,t):"valid"in e?eo(e,o,t):"message"in e?Qt(e,o,t):E("success",n,s):E("success",n,s)}var y=T(require("fs"),1),$=T(require("path"),1),ke=T(require("os"),1);function ct(){let e=process.env.SHELL||"";return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":null}function dt(e,o){switch(e){case"bash":return{completionFile:$.join(o,".ship_completion.bash"),profileFile:$.join(o,".bash_profile"),scriptName:"ship.bash"};case"zsh":return{completionFile:$.join(o,".ship_completion.zsh"),profileFile:$.join(o,".zshrc"),scriptName:"ship.zsh"};case"fish":return{completionFile:$.join(o,".config/fish/completions/ship.fish"),profileFile:null,scriptName:"ship.fish"}}}function ut(e,o={}){let{json:t,noColor:n}=o,i=ct(),s=ke.homedir();if(!i){A(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,t,n);return}let r=dt(i,s),a=$.join(e,r.scriptName);try{if(i==="fish"){let p=$.dirname(r.completionFile);y.existsSync(p)||y.mkdirSync(p,{recursive:!0}),y.copyFileSync(a,r.completionFile),E("fish completion installed successfully",t,n),H("please restart your shell to apply the changes",t,n);return}y.copyFileSync(a,r.completionFile);let l=`# ship
17
17
  source '${r.completionFile}'
18
- # ship end`;if(r.profileFile){if(y.existsSync(r.profileFile)){let c=y.readFileSync(r.profileFile,"utf-8");if(!c.includes("# ship")||!c.includes("# ship end")){let d=c.length>0&&!c.endsWith(`
18
+ # ship end`;if(r.profileFile){if(y.existsSync(r.profileFile)){let p=y.readFileSync(r.profileFile,"utf-8");if(!p.includes("# ship")||!p.includes("# ship end")){let d=p.length>0&&!p.endsWith(`
19
19
  `)?`
20
- `:"";y.appendFileSync(r.profileFile,d+l)}}else y.writeFileSync(r.profileFile,l);E(`completion script installed for ${i}`,t,n),pe(`run "source ${r.profileFile}" or restart your shell`,t,n)}}catch(l){let c=l instanceof Error?l.message:String(l);A(`could not install completion script: ${c}`,t,n)}}function mt(e={}){let{json:o,noColor:t}=e,n=ct(),i=Re.homedir();if(!n){A(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,o,t);return}let s=dt(n,i);try{if(n==="fish"){y.existsSync(s.completionFile)?(y.unlinkSync(s.completionFile),E("fish completion uninstalled successfully",o,t)):pe("fish completion was not installed",o,t),H("please restart your shell to apply the changes",o,t);return}if(y.existsSync(s.completionFile)&&y.unlinkSync(s.completionFile),!s.profileFile)return;if(!y.existsSync(s.profileFile)){A("profile file not found",o,t);return}let r=y.readFileSync(s.profileFile,"utf-8"),a=r.split(`
21
- `),l=[],c=0,d=!1;for(;c<a.length;)if(a[c].trim()==="# ship"){for(d=!0,c++;c<a.length&&a[c].trim()!=="# ship end";)c++;c<a.length&&c++}else l.push(a[c]),c++;if(d){let h=r.endsWith(`
20
+ `:"";y.appendFileSync(r.profileFile,d+l)}}else y.writeFileSync(r.profileFile,l);E(`completion script installed for ${i}`,t,n),pe(`run "source ${r.profileFile}" or restart your shell`,t,n)}}catch(l){let p=l instanceof Error?l.message:String(l);A(`could not install completion script: ${p}`,t,n)}}function mt(e={}){let{json:o,noColor:t}=e,n=ct(),i=ke.homedir();if(!n){A(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,o,t);return}let s=dt(n,i);try{if(n==="fish"){y.existsSync(s.completionFile)?(y.unlinkSync(s.completionFile),E("fish completion uninstalled successfully",o,t)):pe("fish completion was not installed",o,t),H("please restart your shell to apply the changes",o,t);return}if(y.existsSync(s.completionFile)&&y.unlinkSync(s.completionFile),!s.profileFile)return;if(!y.existsSync(s.profileFile)){A("profile file not found",o,t);return}let r=y.readFileSync(s.profileFile,"utf-8"),a=r.split(`
21
+ `),l=[],p=0,d=!1;for(;p<a.length;)if(a[p].trim()==="# ship"){for(d=!0,p++;p<a.length&&a[p].trim()!=="# ship end";)p++;p<a.length&&p++}else l.push(a[p]),p++;if(d){let h=r.endsWith(`
22
22
  `),S=l.length===0?"":l.join(`
23
23
  `)+(h?`
24
- `:"");y.writeFileSync(s.profileFile,S),E(`completion script uninstalled for ${n}`,o,t),pe(`run "source ${s.profileFile}" or restart your shell`,o,t)}else A("completion was not found in profile",o,t)}catch(r){let a=r instanceof Error?r.message:String(r);A(`could not uninstall completion script: ${a}`,o,t)}}var gt=require("readline/promises"),_=require("fs"),yt=require("os"),St=require("path");C();var de=require("yoctocolors"),G=(0,St.join)((0,yt.homedir)(),".shiprc");function ft(e){return e.length<13?e:e.slice(0,9)+"..."+e.slice(-4)}function ht(){try{return(0,_.existsSync)(G)?JSON.parse((0,_.readFileSync)(G,"utf-8")):{}}catch{return{}}}async function bt(e={}){let{noColor:o,json:t}=e,n=d=>o?d:(0,de.dim)(d),i=d=>o?d:(0,de.green)(d);if(t){let d=ht(),h=typeof d.apiKey=="string"?d.apiKey:void 0,S=typeof d.apiUrl=="string"?d.apiUrl:void 0;console.log(JSON.stringify({path:G,exists:(0,_.existsSync)(G),...h?{apiKey:ft(h)}:{},...S&&S!==M?{apiUrl:S}:{}},null,2)+`
25
- `);return}let s=ht(),r=typeof s.apiKey=="string"?s.apiKey:void 0,a=(0,gt.createInterface)({input:process.stdin,output:process.stdout});console.log("");let l=r?` API Key (${n(ft(r))}): `:" API Key: ",c;try{c=(await a.question(l)).trim()}finally{a.close()}c&&(te(c),s.apiKey=c),(0,_.writeFileSync)(G,JSON.stringify(s,null,2)+`
24
+ `:"");y.writeFileSync(s.profileFile,S),E(`completion script uninstalled for ${n}`,o,t),pe(`run "source ${s.profileFile}" or restart your shell`,o,t)}else A("completion was not found in profile",o,t)}catch(r){let a=r instanceof Error?r.message:String(r);A(`could not uninstall completion script: ${a}`,o,t)}}var gt=require("readline/promises"),_=require("fs"),yt=require("os"),St=require("path");C();var de=require("yoctocolors"),G=(0,St.join)((0,yt.homedir)(),".shiprc");function ft(e){return e.length<13?e:e.slice(0,9)+"..."+e.slice(-4)}function ht(){try{return(0,_.existsSync)(G)?JSON.parse((0,_.readFileSync)(G,"utf-8")):{}}catch{return{}}}async function bt(e={}){let{noColor:o,json:t}=e,n=d=>o?d:(0,de.dim)(d),i=d=>o?d:(0,de.green)(d);if(t){let d=ht(),h=typeof d.apiKey=="string"?d.apiKey:void 0,S=typeof d.apiUrl=="string"?d.apiUrl:void 0;console.log(JSON.stringify({path:G,exists:(0,_.existsSync)(G),...h?{apiKey:ft(h)}:{},...S&&S!==K?{apiUrl:S}:{}},null,2)+`
25
+ `);return}let s=ht(),r=typeof s.apiKey=="string"?s.apiKey:void 0,a=(0,gt.createInterface)({input:process.stdin,output:process.stdout});console.log("");let l=r?` API Key (${n(ft(r))}): `:" API Key: ",p;try{p=(await a.question(l)).trim()}finally{a.close()}p&&(te(p),s.apiKey=p),(0,_.writeFileSync)(G,JSON.stringify(s,null,2)+`
26
26
  `),console.log(`
27
27
  ${i("saved to")} ${n(G)}
28
- `)}C();function Dt(e){return R(e)?e:e instanceof Error?p.business(e.message):p.business(String(e??"Unknown error"))}function Ct(e,o,t){if(e.isAuthError())return t?.apiKey?"authentication failed: invalid API key":t?.deployToken?"authentication failed: invalid or expired deploy token":"authentication required: use --api-key or --deploy-token, or set SHIP_API_KEY";if(e.isNetworkError()){let n=e.details?.url;return n?`network error: could not reach ${n}`:"network error: could not reach the API. check your internet connection"}return e.isFileError()||e.isValidationError()||e.isClientError()||e.status&&e.status>=400&&e.status<500?e.message:"server error: please try again or check https://status.shipstatic.com"}function vt(e,o){return JSON.stringify({error:e,...o?{details:o}:{}},null,2)}var me=require("yoctocolors");function no(){let e=[ue.resolve(__dirname,"../package.json"),ue.resolve(__dirname,"../../package.json")];for(let o of e)try{return JSON.parse((0,U.readFileSync)(o,"utf-8"))}catch{}return{version:"0.0.0"}}var io=no(),f=new wt.Command;f.exitOverride(e=>{(e.code==="commander.help"||e.code==="commander.version"||e.exitCode===0)&&process.exit(e.exitCode||0);let o=L(f),t=e.message||"unknown command error";t=t.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),A(t,o.json,o.noColor),o.json||Y(o.noColor),process.exit(e.exitCode||1)}).configureOutput({writeErr:e=>{e.startsWith("error:")||process.stderr.write(e)},writeOut:e=>process.stdout.write(e)});function Y(e){let o=i=>e?i:(0,me.bold)(i),t=i=>e?i:(0,me.dim)(i),n=`${o("USAGE")}
28
+ `)}C();function Dt(e){return k(e)?e:e instanceof Error?c.business(e.message):c.business(String(e??"Unknown error"))}function Ct(e,o,t){if(e.isAuthError())return t?.apiKey?"authentication failed: invalid API key":t?.deployToken?"authentication failed: invalid or expired deploy token":"authentication required: use --api-key or --deploy-token, or set SHIP_API_KEY";if(e.isNetworkError()){let n=e.details?.url;return n?`network error: could not reach ${n}`:"network error: could not reach the API. check your internet connection"}return e.isFileError()||e.isValidationError()||e.isClientError()||e.status&&e.status>=400&&e.status<500?e.message:"server error: please try again or check https://status.shipstatic.com"}function vt(e,o){return JSON.stringify({error:e,...o?{details:o}:{}},null,2)}var me=require("yoctocolors");function no(){let e=[ue.resolve(__dirname,"../package.json"),ue.resolve(__dirname,"../../package.json")];for(let o of e)try{return JSON.parse((0,U.readFileSync)(o,"utf-8"))}catch{}return{version:"0.0.0"}}var io=no(),f=new wt.Command;f.exitOverride(e=>{(e.code==="commander.help"||e.code==="commander.version"||e.exitCode===0)&&process.exit(e.exitCode||0);let o=L(f),t=e.message||"unknown command error";t=t.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),A(t,o.json,o.noColor),o.json||Y(o.noColor),process.exit(e.exitCode||1)}).configureOutput({writeErr:e=>{e.startsWith("error:")||process.stderr.write(e)},writeOut:e=>process.stdout.write(e)});function Y(e){let o=i=>e?i:(0,me.bold)(i),t=i=>e?i:(0,me.dim)(i),n=`${o("USAGE")}
29
29
  ship <path> \u{1F680} Deploy static sites with simplicity
30
30
 
31
31
  ${o("COMMANDS")}
32
32
  \u{1F4E6} ${o("Deployments")}
33
33
  ship deployments list List all deployments
34
34
  ship deployments upload <path> Upload deployment from directory
35
- ship deployments get <id> Show deployment information
36
- ship deployments set <id> Set deployment labels
37
- ship deployments remove <id> Delete deployment permanently
35
+ ship deployments get <deployment> Show deployment information
36
+ ship deployments set <deployment> Set deployment labels
37
+ ship deployments remove <deployment> Delete deployment permanently
38
38
 
39
39
  \u{1F30E} ${o("Domains")}
40
40
  ship domains list List all domains
@@ -66,10 +66,14 @@ ${o("FLAGS")}
66
66
  --no-spa-detect Disable automatic SPA detection and configuration
67
67
  --no-color Disable colored output
68
68
  --json Output results in JSON format
69
+ -q, --quiet Output only the resource identifier
69
70
  --version Show version information
70
71
 
72
+ ${o("EXAMPLES")}
73
+ ship ./dist -q | ship domains set www.example.com
74
+
71
75
  ${t("Please report any issues to https://github.com/shipstatic/ship/issues")}
72
76
  `;console.log(n)}function X(e,o=[]){return o.concat([e])}function Z(e,o){let t=e?.label?.length?e.label:o?.label;return t?.length?t:void 0}function Q(e){return(...o)=>{let t=L(f),n=o[o.length-1];if(n?.args?.length){let i=n.args.find(s=>!e.includes(s));i&&A(`unknown command '${i}'`,t.json,t.noColor)}Y(t.noColor),process.exit(1)}}function L(e){let o=e.optsWithGlobals();return o.color===!1&&(o.noColor=!0),o}function Et(e,o){let t=L(f),n=Dt(e),i=Ct(n,o,{apiKey:t.apiKey,deployToken:t.deployToken});t.json?console.error(vt(i,n.details)+`
73
- `):(A(i,!1,t.noColor),n.isValidationError()&&i.includes("unknown command")&&Y(t.noColor)),process.exit(1)}function v(e,o){return async function(...t){let n=L(this),i=o?{operation:o.operation,resourceType:o.resourceType,resourceId:o.getResourceId?.(...t)}:{};try{let s=so(),r=await e(s,n,...t);pt(r,i,{json:n.json,noColor:n.noColor})}catch(s){Et(s,i)}}}function so(){let{config:e,apiUrl:o,apiKey:t,deployToken:n}=f.opts();return new le({configFile:e,apiUrl:o,apiKey:t,deployToken:n})}async function Tt(e,o,t,n,i){if(!(0,U.existsSync)(o))throw p.file(`${o} path does not exist`,o);let s=(0,U.statSync)(o);if(!s.isDirectory()&&!s.isFile())throw p.file(`${o} path must be a file or directory`,o);let r={via:process.env.SHIP_VIA||"cli"};t&&(r.labels=t),n?.noPathDetect!==void 0&&(r.pathDetect=!n.noPathDetect),n?.noSpaDetect!==void 0&&(r.spaDetect=!n.noSpaDetect);let a=new AbortController;r.signal=a.signal;let l=null;if(process.stdout.isTTY&&!i.json&&!i.noColor){let{default:d}=await import("yocto-spinner");l=d({text:"uploading\u2026"}).start()}let c=()=>{a.abort(),l&&l.stop(),process.exit(130)};process.on("SIGINT",c);try{return await e.deployments.upload(o,r)}finally{process.removeListener("SIGINT",c),l&&l.stop()}}f.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(io.version,"--version","Show version information").option("--api-key <key>","API key for authenticated deployments").option("--deploy-token <token>","Deploy token for single-use deployments").option("--config <file>","Custom config file path").option("--api-url <url>","API URL (for development)").option("--json","Output results in JSON format").option("--no-color","Disable colored output").option("--help","Display help for command").helpOption(!1);f.hook("preAction",e=>{let o=L(e);o.help&&(Y(o.noColor),process.exit(0))});f.hook("preAction",e=>{let o=L(e);try{o.apiKey&&typeof o.apiKey=="string"&&te(o.apiKey),o.deployToken&&typeof o.deployToken=="string"&&$e(o.deployToken),o.apiUrl&&typeof o.apiUrl=="string"&&Le(o.apiUrl)}catch(t){throw R(t)&&(A(t.message,o.json,o.noColor),process.exit(1)),t}});f.command("ping").description("Check API connectivity").action(v((e,o)=>e.ping()));f.command("whoami").description("Get current account information").action(v((e,o)=>e.whoami(),{operation:"get",resourceType:"Account"}));var ee=f.command("deployments").description("Manage deployments").enablePositionalOptions().action(Q(["list","upload","get","set","remove"]));ee.command("list").description("List all deployments").action(v((e,o)=>e.deployments.list()));ee.command("upload <path>").description("Upload deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",X,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(v((e,o,t,n)=>Tt(e,t,Z(n,f.opts()),n,o),{operation:"upload"}));ee.command("get <deployment>").description("Show deployment information").action(v((e,o,t)=>e.deployments.get(t),{operation:"get",resourceType:"Deployment",getResourceId:e=>e}));ee.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",X,[]).action(v(async(e,o,t,n)=>{let i=Z(n,f.opts())||[];return e.deployments.set(t,{labels:i})},{operation:"set",resourceType:"Deployment",getResourceId:e=>e}));ee.command("remove <deployment>").description("Delete deployment permanently").action(v((e,o,t)=>e.deployments.remove(t),{operation:"remove",resourceType:"Deployment",getResourceId:e=>e}));var V=f.command("domains").description("Manage domains").enablePositionalOptions().action(Q(["list","get","set","validate","verify","remove"]));V.command("list").description("List all domains").action(v((e,o)=>e.domains.list()));V.command("get <name>").description("Show domain information").action(v((e,o,t)=>e.domains.get(t),{operation:"get",resourceType:"Domain",getResourceId:e=>e}));V.command("validate <name>").description("Check if domain name is valid and available").action(v((e,o,t)=>e.domains.validate(t),{operation:"validate",resourceType:"Domain",getResourceId:e=>e}));V.command("verify <name>").description("Trigger DNS verification for external domain").action(v((e,o,t)=>e.domains.verify(t),{operation:"verify",resourceType:"Domain",getResourceId:e=>e}));V.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",X,[]).action(v(async(e,o,t,n,i)=>{let s=Z(i,f.opts()),r={};n&&(r.deployment=n),s&&s.length>0&&(r.labels=s);let a=await e.domains.set(t,r);if(a.isCreate&&t.includes("."))try{let[l,c]=await Promise.all([e.domains.records(t),e.domains.share(t)]);return{...a,_dnsRecords:l.records,_shareHash:c.hash}}catch{}return a},{operation:"set",resourceType:"Domain",getResourceId:e=>e}));V.command("remove <name>").description("Delete domain permanently").action(v((e,o,t)=>e.domains.remove(t),{operation:"remove",resourceType:"Domain",getResourceId:e=>e}));var ke=f.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(Q(["list","create","remove"]));ke.command("list").description("List all tokens").action(v((e,o)=>e.tokens.list()));ke.command("create").description("Create a new deploy token").option("--ttl <seconds>","Time to live in seconds (default: never expires)",parseInt).option("--label <label>","Label to set (can be repeated)",X,[]).action(v((e,o,t)=>{let n={};t?.ttl!==void 0&&(n.ttl=t.ttl);let i=Z(t,f.opts());return i&&i.length>0&&(n.labels=i),e.tokens.create(n)},{operation:"create",resourceType:"Token"}));ke.command("remove <token>").description("Delete token permanently").action(v((e,o,t)=>e.tokens.remove(t),{operation:"remove",resourceType:"Token",getResourceId:e=>e}));var ro=f.command("account").description("Manage account").action(Q(["get"]));ro.command("get").description("Show account information").action(v((e,o)=>e.whoami(),{operation:"get",resourceType:"Account"}));var At=f.command("completion").description("Setup shell completion").action(Q(["install","uninstall"]));At.command("install").description("Install shell completion script").action(()=>{let e=L(f),o=ue.resolve(__dirname,"completions");ut(o,{json:e.json,noColor:e.noColor})});At.command("uninstall").description("Uninstall shell completion script").action(()=>{let e=L(f);mt({json:e.json,noColor:e.noColor})});f.command("config").description("Create or update ~/.shiprc configuration").action(async()=>{let e=L(f);try{await bt({noColor:e.noColor,json:e.json})}catch(o){Et(o)}});f.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",X,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(v(async(e,o,t,n)=>{if(t||(Y(o.noColor),process.exit(0)),!(0,U.existsSync)(t)&&!t.includes("/")&&!t.includes("\\")&&!t.includes(".")&&!t.startsWith("~"))throw p.validation(`unknown command '${t}'`);return Tt(e,t,Z(n,f.opts()),n,o)},{operation:"upload"}));function ao(){let e=process.argv,o=e.includes("--compbash"),t=e.includes("--compzsh"),n=e.includes("--compfish");if(!o&&!t&&!n)return;console.log(["ping","whoami","deployments","domains","tokens","account","config","completion"].join(n?`
77
+ `):(A(i,!1,t.noColor),n.isValidationError()&&i.includes("unknown command")&&Y(t.noColor)),process.exit(1)}function v(e,o){return async function(...t){let n=L(this),i=o?{operation:o.operation,resourceType:o.resourceType,resourceId:o.getResourceId?.(...t)}:{};try{let s=so(),r=await e(s,n,...t);pt(r,i,{json:n.json,quiet:n.quiet,noColor:n.noColor})}catch(s){Et(s,i)}}}function so(){let{config:e,apiUrl:o,apiKey:t,deployToken:n}=f.opts();return new le({configFile:e,apiUrl:o,apiKey:t,deployToken:n})}async function Tt(e,o,t,n,i){if(!(0,U.existsSync)(o))throw c.file(`${o} path does not exist`,o);let s=(0,U.statSync)(o);if(!s.isDirectory()&&!s.isFile())throw c.file(`${o} path must be a file or directory`,o);let r={via:process.env.SHIP_VIA||"cli"};t&&(r.labels=t),n?.noPathDetect!==void 0&&(r.pathDetect=!n.noPathDetect),n?.noSpaDetect!==void 0&&(r.spaDetect=!n.noSpaDetect);let a=new AbortController;r.signal=a.signal;let l=null;if(process.stdout.isTTY&&!i.json&&!i.quiet&&!i.noColor){let{default:d}=await import("yocto-spinner");l=d({text:"uploading\u2026"}).start()}let p=()=>{a.abort(),l&&l.stop(),process.exit(130)};process.on("SIGINT",p);try{return await e.deployments.upload(o,r)}finally{process.removeListener("SIGINT",p),l&&l.stop()}}f.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(io.version,"--version","Show version information").option("--api-key <key>","API key for authenticated deployments").option("--deploy-token <token>","Deploy token for single-use deployments").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").option("--help","Display help for command").helpOption(!1);f.hook("preAction",e=>{let o=L(e);o.help&&(Y(o.noColor),process.exit(0))});f.hook("preAction",e=>{let o=L(e);try{o.apiKey&&typeof o.apiKey=="string"&&te(o.apiKey),o.deployToken&&typeof o.deployToken=="string"&&$e(o.deployToken),o.apiUrl&&typeof o.apiUrl=="string"&&Le(o.apiUrl)}catch(t){throw k(t)&&(A(t.message,o.json,o.noColor),process.exit(1)),t}});f.command("ping").description("Check API connectivity").action(v((e,o)=>e.ping()));f.command("whoami").description("Get current account information").action(v((e,o)=>e.whoami(),{operation:"get",resourceType:"Account"}));var ee=f.command("deployments").description("Manage deployments").enablePositionalOptions().action(Q(["list","upload","get","set","remove"]));ee.command("list").description("List all deployments").action(v((e,o)=>e.deployments.list()));ee.command("upload <path>").description("Upload deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",X,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(v((e,o,t,n)=>Tt(e,t,Z(n,f.opts()),n,o),{operation:"upload"}));ee.command("get <deployment>").description("Show deployment information").action(v((e,o,t)=>e.deployments.get(t),{operation:"get",resourceType:"Deployment",getResourceId:e=>e}));ee.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",X,[]).action(v(async(e,o,t,n)=>{let i=Z(n,f.opts())||[];return e.deployments.set(t,{labels:i})},{operation:"set",resourceType:"Deployment",getResourceId:e=>e}));ee.command("remove <deployment>").description("Delete deployment permanently").action(v((e,o,t)=>e.deployments.remove(t),{operation:"remove",resourceType:"Deployment",getResourceId:e=>e}));var V=f.command("domains").description("Manage domains").enablePositionalOptions().action(Q(["list","get","set","validate","verify","remove"]));V.command("list").description("List all domains").action(v((e,o)=>e.domains.list()));V.command("get <name>").description("Show domain information").action(v((e,o,t)=>e.domains.get(t),{operation:"get",resourceType:"Domain",getResourceId:e=>e}));V.command("validate <name>").description("Check if domain name is valid and available").action(v((e,o,t)=>e.domains.validate(t),{operation:"validate",resourceType:"Domain",getResourceId:e=>e}));V.command("verify <name>").description("Trigger DNS verification for external domain").action(v((e,o,t)=>e.domains.verify(t),{operation:"verify",resourceType:"Domain",getResourceId:e=>e}));V.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",X,[]).action(v(async(e,o,t,n,i)=>{!n&&!process.stdin.isTTY&&(n=await new Promise(l=>{let p="";process.stdin.on("data",d=>p+=d),process.stdin.on("end",()=>l(p.trim()||void 0))}));let s=Z(i,f.opts()),r={};n&&(r.deployment=n),s&&s.length>0&&(r.labels=s);let a=await e.domains.set(t,r);if(a.isCreate&&t.includes("."))try{let[l,p]=await Promise.all([e.domains.records(t),e.domains.share(t)]);return{...a,_dnsRecords:l.records,_shareHash:p.hash}}catch{}return a},{operation:"set",resourceType:"Domain",getResourceId:e=>e}));V.command("remove <name>").description("Delete domain permanently").action(v((e,o,t)=>e.domains.remove(t),{operation:"remove",resourceType:"Domain",getResourceId:e=>e}));var Oe=f.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(Q(["list","create","remove"]));Oe.command("list").description("List all tokens").action(v((e,o)=>e.tokens.list()));Oe.command("create").description("Create a new deploy token").option("--ttl <seconds>","Time to live in seconds (default: never expires)",parseInt).option("--label <label>","Label to set (can be repeated)",X,[]).action(v((e,o,t)=>{let n={};t?.ttl!==void 0&&(n.ttl=t.ttl);let i=Z(t,f.opts());return i&&i.length>0&&(n.labels=i),e.tokens.create(n)},{operation:"create",resourceType:"Token"}));Oe.command("remove <token>").description("Delete token permanently").action(v((e,o,t)=>e.tokens.remove(t),{operation:"remove",resourceType:"Token",getResourceId:e=>e}));var ro=f.command("account").description("Manage account").action(Q(["get"]));ro.command("get").description("Show account information").action(v((e,o)=>e.whoami(),{operation:"get",resourceType:"Account"}));var At=f.command("completion").description("Setup shell completion").action(Q(["install","uninstall"]));At.command("install").description("Install shell completion script").action(()=>{let e=L(f),o=ue.resolve(__dirname,"completions");ut(o,{json:e.json,noColor:e.noColor})});At.command("uninstall").description("Uninstall shell completion script").action(()=>{let e=L(f);mt({json:e.json,noColor:e.noColor})});f.command("config").description("Create or update ~/.shiprc configuration").action(async()=>{let e=L(f);try{await bt({noColor:e.noColor,json:e.json})}catch(o){Et(o)}});f.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",X,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(v(async(e,o,t,n)=>{if(t||(Y(o.noColor),process.exit(0)),!(0,U.existsSync)(t)&&!t.includes("/")&&!t.includes("\\")&&!t.includes(".")&&!t.startsWith("~"))throw c.validation(`unknown command '${t}'`);return Tt(e,t,Z(n,f.opts()),n,o)},{operation:"upload"}));function ao(){let e=process.argv,o=e.includes("--compbash"),t=e.includes("--compzsh"),n=e.includes("--compfish");if(!o&&!t&&!n)return;console.log(["ping","whoami","deployments","domains","tokens","account","config","completion"].join(n?`
74
78
  `:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&ao();if(process.env.NODE_ENV!=="test")try{f.parse(process.argv)}catch(e){if(e instanceof Error&&"code"in e){let o=e.code,t=e.exitCode;o?.startsWith("commander.")&&process.exit(t||1)}throw e}
75
79
  //# sourceMappingURL=cli.cjs.map