@shipstatic/ship 0.6.4 → 0.7.1
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 +160 -52
- package/dist/browser.d.ts +18 -2
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +33 -33
- package/dist/cli.cjs.map +1 -1
- package/dist/completions/ship.bash +3 -3
- package/dist/completions/ship.fish +2 -2
- package/dist/completions/ship.zsh +3 -3
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +18 -2
- package/dist/index.d.ts +18 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -15,33 +15,76 @@ npm install @shipstatic/ship
|
|
|
15
15
|
## CLI Usage
|
|
16
16
|
|
|
17
17
|
```bash
|
|
18
|
-
# Deploy a directory
|
|
18
|
+
# Deploy a directory (shortcut)
|
|
19
19
|
ship ./dist
|
|
20
20
|
|
|
21
21
|
# Deploy with labels
|
|
22
22
|
ship ./dist --label production --label v1.0.0
|
|
23
23
|
|
|
24
|
-
#
|
|
24
|
+
# Disable automatic detection
|
|
25
|
+
ship ./dist --no-path-detect --no-spa-detect
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
### Deployments
|
|
29
|
+
|
|
30
|
+
```bash
|
|
25
31
|
ship deployments list
|
|
32
|
+
ship deployments upload <path> # Upload from file or directory
|
|
33
|
+
ship deployments upload <path> --label production # Upload with labels
|
|
26
34
|
ship deployments get <id>
|
|
27
35
|
ship deployments set <id> --label production # Update labels
|
|
28
36
|
ship deployments remove <id>
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Domains
|
|
29
40
|
|
|
30
|
-
|
|
41
|
+
```bash
|
|
31
42
|
ship domains list
|
|
43
|
+
ship domains set staging # Reserve domain (no deployment yet)
|
|
32
44
|
ship domains set staging <deployment-id> # Link domain to deployment
|
|
33
|
-
ship domains set staging --label production # Update
|
|
45
|
+
ship domains set staging --label production # Update labels only
|
|
34
46
|
ship domains get staging
|
|
35
|
-
ship domains
|
|
47
|
+
ship domains validate www.example.com # Check if domain is valid and available
|
|
48
|
+
ship domains verify www.example.com # Trigger DNS verification
|
|
36
49
|
ship domains remove staging
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Tokens
|
|
37
53
|
|
|
38
|
-
|
|
54
|
+
```bash
|
|
39
55
|
ship tokens list
|
|
40
56
|
ship tokens create --ttl 3600 --label ci
|
|
41
57
|
ship tokens remove <token>
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Account & Setup
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
ship whoami # Get current account (alias for account get)
|
|
64
|
+
ship account get
|
|
65
|
+
ship config # Create or update ~/.shiprc
|
|
66
|
+
ship ping # Check API connectivity
|
|
67
|
+
```
|
|
42
68
|
|
|
43
|
-
|
|
44
|
-
|
|
69
|
+
### Shell Completion
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
ship completion install
|
|
73
|
+
ship completion uninstall
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Global Flags
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
--api-key <key> API key for authenticated deployments
|
|
80
|
+
--deploy-token <token> Deploy token for single-use deployments
|
|
81
|
+
--config <file> Custom config file path
|
|
82
|
+
--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
|
|
85
|
+
--no-color Disable colored output
|
|
86
|
+
--json Output results in JSON format
|
|
87
|
+
--version Show version information
|
|
45
88
|
```
|
|
46
89
|
|
|
47
90
|
## SDK Usage
|
|
@@ -53,19 +96,22 @@ const ship = new Ship({
|
|
|
53
96
|
apiKey: 'ship-your-api-key'
|
|
54
97
|
});
|
|
55
98
|
|
|
56
|
-
// Deploy
|
|
57
|
-
const
|
|
99
|
+
// Deploy (shortcut)
|
|
100
|
+
const deployment = await ship.deploy('./dist');
|
|
101
|
+
console.log(`Deployed: ${deployment.url}`);
|
|
102
|
+
|
|
103
|
+
// Deploy with options
|
|
104
|
+
const deployment = await ship.deployments.upload('./dist', {
|
|
105
|
+
labels: ['production', 'v1.0'],
|
|
58
106
|
onProgress: ({ percent }) => console.log(`${percent}%`)
|
|
59
107
|
});
|
|
60
108
|
|
|
61
|
-
console.log(`Deployed: ${result.url}`);
|
|
62
|
-
|
|
63
109
|
// Manage domains
|
|
64
|
-
await ship.domains.set('staging', { deployment:
|
|
110
|
+
await ship.domains.set('staging', { deployment: deployment.id });
|
|
65
111
|
await ship.domains.list();
|
|
66
112
|
|
|
67
113
|
// Update labels
|
|
68
|
-
await ship.deployments.set(
|
|
114
|
+
await ship.deployments.set(deployment.id, { labels: ['production', 'v1.0'] });
|
|
69
115
|
await ship.domains.set('staging', { labels: ['live'] });
|
|
70
116
|
```
|
|
71
117
|
|
|
@@ -78,7 +124,12 @@ const ship = new Ship({ apiKey: 'ship-your-api-key' });
|
|
|
78
124
|
|
|
79
125
|
// From file input
|
|
80
126
|
const files = Array.from(fileInput.files);
|
|
81
|
-
const
|
|
127
|
+
const deployment = await ship.deploy(files);
|
|
128
|
+
|
|
129
|
+
// From StaticFile array
|
|
130
|
+
const deployment = await ship.deploy([
|
|
131
|
+
{ path: 'index.html', content: new Blob(['<html>…</html>']) }
|
|
132
|
+
]);
|
|
82
133
|
```
|
|
83
134
|
|
|
84
135
|
## Authentication
|
|
@@ -93,6 +144,10 @@ const ship = new Ship({
|
|
|
93
144
|
const ship = new Ship({
|
|
94
145
|
deployToken: 'token-...' // 70 chars: token- + 64 hex
|
|
95
146
|
});
|
|
147
|
+
|
|
148
|
+
// Set credentials after construction
|
|
149
|
+
ship.setApiKey('ship-...');
|
|
150
|
+
ship.setDeployToken('token-...');
|
|
96
151
|
```
|
|
97
152
|
|
|
98
153
|
## Configuration
|
|
@@ -108,7 +163,7 @@ SHIP_API_URL=https://api.shipstatic.com
|
|
|
108
163
|
SHIP_API_KEY=ship-your-api-key
|
|
109
164
|
```
|
|
110
165
|
|
|
111
|
-
**Config files** (Node.js):
|
|
166
|
+
**Config files** (Node.js, in order of precedence):
|
|
112
167
|
```json
|
|
113
168
|
// .shiprc or package.json "ship" key
|
|
114
169
|
{ "apiUrl": "...", "apiKey": "..." }
|
|
@@ -116,61 +171,114 @@ SHIP_API_KEY=ship-your-api-key
|
|
|
116
171
|
|
|
117
172
|
## API Reference
|
|
118
173
|
|
|
119
|
-
###
|
|
174
|
+
### Top-level Methods
|
|
175
|
+
|
|
176
|
+
```typescript
|
|
177
|
+
ship.deploy(input, options?) // Deploy (shortcut for deployments.upload)
|
|
178
|
+
ship.whoami() // Get current account (shortcut for account.get)
|
|
179
|
+
ship.ping() // Check API connectivity (returns boolean)
|
|
180
|
+
ship.getConfig() // Get platform config and plan limits
|
|
181
|
+
ship.on(event, handler) // Add event listener
|
|
182
|
+
ship.off(event, handler) // Remove event listener
|
|
183
|
+
ship.setApiKey(key) // Set API key after construction
|
|
184
|
+
ship.setDeployToken(token) // Set deploy token after construction
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### Deployments
|
|
120
188
|
|
|
121
189
|
```typescript
|
|
122
|
-
//
|
|
123
|
-
ship.deployments.
|
|
124
|
-
ship.deployments.
|
|
125
|
-
ship.deployments.
|
|
126
|
-
ship.deployments.
|
|
127
|
-
|
|
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
|
|
195
|
+
```
|
|
128
196
|
|
|
129
|
-
|
|
130
|
-
ship.domains.set(name, { deployment?, labels? }) // Create/update domain (see below)
|
|
131
|
-
ship.domains.get(name) // Get domain details
|
|
132
|
-
ship.domains.list() // List all domains
|
|
133
|
-
ship.domains.remove(name) // Delete domain
|
|
134
|
-
ship.domains.verify(name) // Trigger DNS verification
|
|
197
|
+
### Domains
|
|
135
198
|
|
|
136
|
-
|
|
137
|
-
ship.
|
|
138
|
-
ship.
|
|
139
|
-
ship.
|
|
199
|
+
```typescript
|
|
200
|
+
ship.domains.set(name, options?) // Create/update domain (see below)
|
|
201
|
+
ship.domains.get(name) // Get domain details
|
|
202
|
+
ship.domains.list() // List all domains
|
|
203
|
+
ship.domains.remove(name) // Delete domain
|
|
204
|
+
ship.domains.validate(name) // Pre-flight: check if domain is valid and available
|
|
205
|
+
ship.domains.verify(name) // Trigger async DNS verification
|
|
206
|
+
ship.domains.dns(name) // Get required DNS records
|
|
207
|
+
ship.domains.records(name) // Get current live DNS records
|
|
208
|
+
ship.domains.share(name) // Get shareable domain hash
|
|
209
|
+
```
|
|
140
210
|
|
|
141
|
-
|
|
142
|
-
ship.whoami() // Get current account
|
|
211
|
+
### Tokens
|
|
143
212
|
|
|
144
|
-
|
|
145
|
-
ship.
|
|
213
|
+
```typescript
|
|
214
|
+
ship.tokens.create({ ttl?, labels? }) // Create deploy token
|
|
215
|
+
ship.tokens.list() // List all tokens
|
|
216
|
+
ship.tokens.remove(token) // Revoke token
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
### Account
|
|
220
|
+
|
|
221
|
+
```typescript
|
|
222
|
+
ship.account.get() // Get current account
|
|
146
223
|
```
|
|
147
224
|
|
|
148
225
|
### domains.set() Behavior
|
|
149
226
|
|
|
227
|
+
`domains.set()` is a single upsert endpoint. Omitted fields are preserved on update and defaulted on create:
|
|
228
|
+
|
|
150
229
|
```typescript
|
|
230
|
+
// Reserve domain (no deployment yet)
|
|
231
|
+
ship.domains.set('staging');
|
|
232
|
+
|
|
151
233
|
// Link domain to deployment
|
|
152
234
|
ship.domains.set('staging', { deployment: 'abc123' });
|
|
153
235
|
|
|
154
|
-
//
|
|
155
|
-
ship.domains.set('staging', { deployment: '
|
|
236
|
+
// Switch to a different deployment (atomic)
|
|
237
|
+
ship.domains.set('staging', { deployment: 'xyz789' });
|
|
156
238
|
|
|
157
|
-
// Update labels only (
|
|
239
|
+
// Update labels only (deployment preserved)
|
|
158
240
|
ship.domains.set('staging', { labels: ['prod', 'v2'] });
|
|
241
|
+
|
|
242
|
+
// Update both
|
|
243
|
+
ship.domains.set('staging', { deployment: 'abc123', labels: ['prod'] });
|
|
159
244
|
```
|
|
160
245
|
|
|
161
|
-
**
|
|
246
|
+
**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.
|
|
247
|
+
|
|
248
|
+
**Domain format:** Domain names are FQDNs. The SDK accepts any format (case-insensitive, Unicode) — the API normalizes:
|
|
162
249
|
|
|
163
250
|
```typescript
|
|
164
251
|
ship.domains.set('Example.COM', { deployment: 'abc' }); // → normalized to 'example.com'
|
|
165
252
|
ship.domains.set('münchen.de', { deployment: 'abc' }); // → Unicode supported
|
|
166
253
|
```
|
|
167
254
|
|
|
255
|
+
### Deploy Options
|
|
256
|
+
|
|
257
|
+
```typescript
|
|
258
|
+
ship.deploy('./dist', {
|
|
259
|
+
labels?: string[], // Labels for the deployment
|
|
260
|
+
onProgress?: (info) => void, // Progress callback
|
|
261
|
+
signal?: AbortSignal, // Cancellation
|
|
262
|
+
pathDetect?: boolean, // Auto-optimize paths (default: true)
|
|
263
|
+
spaDetect?: boolean, // Auto-detect SPA (default: true)
|
|
264
|
+
maxConcurrency?: number, // Concurrent uploads (default: 4)
|
|
265
|
+
timeout?: number, // Request timeout (ms)
|
|
266
|
+
subdomain?: string, // Suggested subdomain
|
|
267
|
+
via?: string, // Client identifier (e.g. 'sdk', 'cli')
|
|
268
|
+
apiKey?: string, // Per-request API key override
|
|
269
|
+
deployToken?: string, // Per-request deploy token override
|
|
270
|
+
})
|
|
271
|
+
```
|
|
272
|
+
|
|
168
273
|
### Events
|
|
169
274
|
|
|
170
275
|
```javascript
|
|
171
276
|
ship.on('request', (url, init) => console.log(`→ ${url}`));
|
|
172
277
|
ship.on('response', (response, url) => console.log(`← ${response.status}`));
|
|
173
278
|
ship.on('error', (error, url) => console.error(error));
|
|
279
|
+
|
|
280
|
+
// Remove listeners
|
|
281
|
+
ship.off('request', handler);
|
|
174
282
|
```
|
|
175
283
|
|
|
176
284
|
### Error Handling
|
|
@@ -179,7 +287,7 @@ ship.on('error', (error, url) => console.error(error));
|
|
|
179
287
|
import { isShipError } from '@shipstatic/types';
|
|
180
288
|
|
|
181
289
|
try {
|
|
182
|
-
await ship.
|
|
290
|
+
await ship.deploy('./dist');
|
|
183
291
|
} catch (error) {
|
|
184
292
|
if (isShipError(error)) {
|
|
185
293
|
if (error.isAuthError()) { /* ... */ }
|
|
@@ -189,23 +297,23 @@ try {
|
|
|
189
297
|
}
|
|
190
298
|
```
|
|
191
299
|
|
|
192
|
-
## Bundle Sizes
|
|
193
|
-
|
|
194
|
-
- **Node.js**: 21KB
|
|
195
|
-
- **Browser**: 185KB
|
|
196
|
-
- **CLI**: 38KB
|
|
197
|
-
|
|
198
300
|
## TypeScript
|
|
199
301
|
|
|
200
302
|
Full TypeScript support with exported types:
|
|
201
303
|
|
|
202
304
|
```typescript
|
|
203
305
|
import type {
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
ProgressInfo
|
|
306
|
+
ShipClientOptions,
|
|
307
|
+
DeploymentOptions,
|
|
308
|
+
ShipEvents
|
|
208
309
|
} from '@shipstatic/ship';
|
|
310
|
+
|
|
311
|
+
import type {
|
|
312
|
+
Deployment,
|
|
313
|
+
Domain,
|
|
314
|
+
Account,
|
|
315
|
+
StaticFile
|
|
316
|
+
} from '@shipstatic/types';
|
|
209
317
|
```
|
|
210
318
|
|
|
211
319
|
---
|
package/dist/browser.d.ts
CHANGED
|
@@ -174,7 +174,13 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
174
174
|
private readonly getAuthHeadersCallback;
|
|
175
175
|
private readonly timeout;
|
|
176
176
|
private readonly createDeployBody;
|
|
177
|
+
private globalHeaders;
|
|
177
178
|
constructor(options: ApiHttpOptions);
|
|
179
|
+
/**
|
|
180
|
+
* Set global headers included in every request.
|
|
181
|
+
* Priority: globalHeaders (lowest) < per-request headers < auth headers (highest)
|
|
182
|
+
*/
|
|
183
|
+
setGlobalHeaders(headers: Record<string, string>): void;
|
|
178
184
|
/**
|
|
179
185
|
* Transfer events to another client
|
|
180
186
|
*/
|
|
@@ -268,7 +274,7 @@ interface DeploymentResourceContext extends ResourceContext {
|
|
|
268
274
|
hasAuth?: () => boolean;
|
|
269
275
|
}
|
|
270
276
|
/**
|
|
271
|
-
*
|
|
277
|
+
* Upload deployment resource with all CRUD operations.
|
|
272
278
|
*/
|
|
273
279
|
declare function createDeploymentResource(ctx: DeploymentResourceContext): DeploymentResource;
|
|
274
280
|
/**
|
|
@@ -300,6 +306,7 @@ declare abstract class Ship$1 {
|
|
|
300
306
|
protected initPromise: Promise<void> | null;
|
|
301
307
|
protected _config: ConfigResponse | null;
|
|
302
308
|
private auth;
|
|
309
|
+
private customHeaders;
|
|
303
310
|
protected readonly authHeadersCallback: () => Record<string, string>;
|
|
304
311
|
protected _deployments: DeploymentResource;
|
|
305
312
|
protected _domains: DomainResource;
|
|
@@ -319,7 +326,7 @@ declare abstract class Ship$1 {
|
|
|
319
326
|
*/
|
|
320
327
|
ping(): Promise<boolean>;
|
|
321
328
|
/**
|
|
322
|
-
* Deploy project (convenience shortcut to ship.deployments.
|
|
329
|
+
* Deploy project (convenience shortcut to ship.deployments.upload())
|
|
323
330
|
*/
|
|
324
331
|
deploy(input: DeployInput, options?: DeploymentOptions): Promise<Deployment>;
|
|
325
332
|
/**
|
|
@@ -359,6 +366,15 @@ declare abstract class Ship$1 {
|
|
|
359
366
|
* @param handler - Event handler function
|
|
360
367
|
*/
|
|
361
368
|
off<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void;
|
|
369
|
+
/**
|
|
370
|
+
* Set global headers included in every request.
|
|
371
|
+
* Useful for injecting custom headers (e.g. for admin impersonation).
|
|
372
|
+
*/
|
|
373
|
+
setHeaders(headers: Record<string, string>): void;
|
|
374
|
+
/**
|
|
375
|
+
* Clear all custom global headers.
|
|
376
|
+
*/
|
|
377
|
+
clearHeaders(): void;
|
|
362
378
|
/**
|
|
363
379
|
* Replace HTTP client while preserving event listeners
|
|
364
380
|
* Used during initialization to maintain user event subscriptions
|
package/dist/browser.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Me=Object.create;var _=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,Ve=Object.prototype.hasOwnProperty;var He=(i,e,t)=>e in i?_(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var R=(i,e)=>()=>(i&&(e=i(i=0)),e);var fe=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),qe=(i,e)=>{for(var t in e)_(i,t,{get:e[t],enumerable:!0})},Ge=(i,e,t,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let u of ze(e))!Ve.call(i,u)&&u!==t&&_(i,u,{get:()=>e[u],enumerable:!(a=ke(e,u))||a.enumerable});return i};var G=(i,e,t)=>(t=i!=null?Me(Ke(i)):{},Ge(e||!i||!i.__esModule?_(t,"default",{value:i,enumerable:!0}):t,i));var $=(i,e,t)=>He(i,typeof e!="symbol"?e+"":e,t);function J(i){return i!==null&&typeof i=="object"&&"name"in i&&i.name==="ShipError"&&"status"in i}function N(i){let e=i.lastIndexOf(".");if(e===-1||e===i.length-1)return!1;let t=i.slice(e+1).toLowerCase();return je.has(t)}function ut(i){if(!i.startsWith(T))throw d.validation(`API key must start with "${T}"`);if(i.length!==he)throw d.validation(`API key must be ${he} characters total (${T} + ${Y} hex chars)`);let e=i.slice(T.length);if(!/^[a-f0-9]{64}$/i.test(e))throw d.validation(`API key must contain ${Y} hexadecimal characters after "${T}" prefix`)}function ct(i){if(!i.startsWith(I))throw d.validation(`Deploy token must start with "${I}"`);if(i.length!==de)throw d.validation(`Deploy token must be ${de} characters total (${I} + ${W} hex chars)`);let e=i.slice(I.length);if(!/^[a-f0-9]{64}$/i.test(e))throw d.validation(`Deploy token must contain ${W} hexadecimal characters after "${I}" prefix`)}function ft(i){try{let e=new URL(i);if(!["http:","https:"].includes(e.protocol))throw d.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw d.validation("API URL must not contain a path");if(e.search||e.hash)throw d.validation("API URL must not contain query parameters or fragments")}catch(e){throw J(e)?e:d.validation("API URL must be a valid URL")}}function ht(i){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(i)}function me(i,e){return i.endsWith(`.${e}`)}function dt(i,e){return!me(i,e)}function mt(i,e){return me(i,e)?i.slice(0,-(e.length+1)):null}function yt(i,e){return`https://${i}.${e||"shipstatic.com"}`}function gt(i){return`https://${i}`}function St(i){return!i||i.length===0?null:JSON.stringify(i)}function vt(i){if(!i)return[];try{let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch{return[]}}var ot,st,at,A,j,d,je,T,Y,he,pt,I,W,de,lt,X,L,v,Dt,At,x=R(()=>{"use strict";ot={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},st={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},at={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"};(function(i){i.Validation="validation_failed",i.NotFound="not_found",i.RateLimit="rate_limit_exceeded",i.Authentication="authentication_failed",i.Business="business_logic_error",i.Api="internal_server_error",i.Network="network_error",i.Cancelled="operation_cancelled",i.File="file_error",i.Config="config_error"})(A||(A={}));j={client:new Set([A.Business,A.Config,A.File,A.Validation]),network:new Set([A.Network]),auth:new Set([A.Authentication])},d=class i extends Error{constructor(t,a,u,c){super(a);$(this,"type");$(this,"status");$(this,"details");this.type=t,this.status=u,this.details=c,this.name="ShipError"}toResponse(){let t=this.type===A.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:t}}static fromResponse(t){return new i(t.error,t.message,t.status,t.details)}static validation(t,a){return new i(A.Validation,t,400,a)}static notFound(t,a){let u=a?`${t} ${a} not found`:`${t} not found`;return new i(A.NotFound,u,404)}static rateLimit(t="Too many requests"){return new i(A.RateLimit,t,429)}static authentication(t="Authentication required",a){return new i(A.Authentication,t,401,a)}static business(t,a=400){return new i(A.Business,t,a)}static network(t,a){return new i(A.Network,t,void 0,{cause:a})}static cancelled(t){return new i(A.Cancelled,t)}static file(t,a){return new i(A.File,t,void 0,{filePath:a})}static config(t,a){return new i(A.Config,t,void 0,a)}static api(t,a=500){return new i(A.Api,t,a)}static database(t,a=500){return new i(A.Api,t,a)}static storage(t,a=500){return new i(A.Api,t,a)}get filePath(){return this.details?.filePath}isClientError(){return j.client.has(this.type)}isNetworkError(){return j.network.has(this.type)}isAuthError(){return j.auth.has(this.type)}isValidationError(){return this.type===A.Validation}isFileError(){return this.type===A.File}isConfigError(){return this.type===A.Config}isType(t){return this.type===t}};je=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"]);T="ship-",Y=64,he=T.length+Y,pt=4,I="token-",W=64,de=I.length+W,lt={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},X="ship.json";L="https://api.shipstatic.com",v={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};Dt={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},At=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function Z(i){Q=i}function F(){if(Q===null)throw d.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return Q}var Q,P=R(()=>{"use strict";x();Q=null});function Ot(i){ee=i}function We(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function M(){return ee||We()}var ee,k=R(()=>{"use strict";ee=null});var Se=fe((De,Ae)=>{"use strict";(function(i){if(typeof De=="object")Ae.exports=i();else if(typeof define=="function"&&define.amd)define(i);else{var e;try{e=window}catch{e=self}e.SparkMD5=i()}})(function(i){"use strict";var e=function(l,p){return l+p&4294967295},t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function a(l,p,r,n,s,o){return p=e(e(p,l),e(n,o)),e(p<<s|p>>>32-s,r)}function u(l,p){var r=l[0],n=l[1],s=l[2],o=l[3];r+=(n&s|~n&o)+p[0]-680876936|0,r=(r<<7|r>>>25)+n|0,o+=(r&n|~r&s)+p[1]-389564586|0,o=(o<<12|o>>>20)+r|0,s+=(o&r|~o&n)+p[2]+606105819|0,s=(s<<17|s>>>15)+o|0,n+=(s&o|~s&r)+p[3]-1044525330|0,n=(n<<22|n>>>10)+s|0,r+=(n&s|~n&o)+p[4]-176418897|0,r=(r<<7|r>>>25)+n|0,o+=(r&n|~r&s)+p[5]+1200080426|0,o=(o<<12|o>>>20)+r|0,s+=(o&r|~o&n)+p[6]-1473231341|0,s=(s<<17|s>>>15)+o|0,n+=(s&o|~s&r)+p[7]-45705983|0,n=(n<<22|n>>>10)+s|0,r+=(n&s|~n&o)+p[8]+1770035416|0,r=(r<<7|r>>>25)+n|0,o+=(r&n|~r&s)+p[9]-1958414417|0,o=(o<<12|o>>>20)+r|0,s+=(o&r|~o&n)+p[10]-42063|0,s=(s<<17|s>>>15)+o|0,n+=(s&o|~s&r)+p[11]-1990404162|0,n=(n<<22|n>>>10)+s|0,r+=(n&s|~n&o)+p[12]+1804603682|0,r=(r<<7|r>>>25)+n|0,o+=(r&n|~r&s)+p[13]-40341101|0,o=(o<<12|o>>>20)+r|0,s+=(o&r|~o&n)+p[14]-1502002290|0,s=(s<<17|s>>>15)+o|0,n+=(s&o|~s&r)+p[15]+1236535329|0,n=(n<<22|n>>>10)+s|0,r+=(n&o|s&~o)+p[1]-165796510|0,r=(r<<5|r>>>27)+n|0,o+=(r&s|n&~s)+p[6]-1069501632|0,o=(o<<9|o>>>23)+r|0,s+=(o&n|r&~n)+p[11]+643717713|0,s=(s<<14|s>>>18)+o|0,n+=(s&r|o&~r)+p[0]-373897302|0,n=(n<<20|n>>>12)+s|0,r+=(n&o|s&~o)+p[5]-701558691|0,r=(r<<5|r>>>27)+n|0,o+=(r&s|n&~s)+p[10]+38016083|0,o=(o<<9|o>>>23)+r|0,s+=(o&n|r&~n)+p[15]-660478335|0,s=(s<<14|s>>>18)+o|0,n+=(s&r|o&~r)+p[4]-405537848|0,n=(n<<20|n>>>12)+s|0,r+=(n&o|s&~o)+p[9]+568446438|0,r=(r<<5|r>>>27)+n|0,o+=(r&s|n&~s)+p[14]-1019803690|0,o=(o<<9|o>>>23)+r|0,s+=(o&n|r&~n)+p[3]-187363961|0,s=(s<<14|s>>>18)+o|0,n+=(s&r|o&~r)+p[8]+1163531501|0,n=(n<<20|n>>>12)+s|0,r+=(n&o|s&~o)+p[13]-1444681467|0,r=(r<<5|r>>>27)+n|0,o+=(r&s|n&~s)+p[2]-51403784|0,o=(o<<9|o>>>23)+r|0,s+=(o&n|r&~n)+p[7]+1735328473|0,s=(s<<14|s>>>18)+o|0,n+=(s&r|o&~r)+p[12]-1926607734|0,n=(n<<20|n>>>12)+s|0,r+=(n^s^o)+p[5]-378558|0,r=(r<<4|r>>>28)+n|0,o+=(r^n^s)+p[8]-2022574463|0,o=(o<<11|o>>>21)+r|0,s+=(o^r^n)+p[11]+1839030562|0,s=(s<<16|s>>>16)+o|0,n+=(s^o^r)+p[14]-35309556|0,n=(n<<23|n>>>9)+s|0,r+=(n^s^o)+p[1]-1530992060|0,r=(r<<4|r>>>28)+n|0,o+=(r^n^s)+p[4]+1272893353|0,o=(o<<11|o>>>21)+r|0,s+=(o^r^n)+p[7]-155497632|0,s=(s<<16|s>>>16)+o|0,n+=(s^o^r)+p[10]-1094730640|0,n=(n<<23|n>>>9)+s|0,r+=(n^s^o)+p[13]+681279174|0,r=(r<<4|r>>>28)+n|0,o+=(r^n^s)+p[0]-358537222|0,o=(o<<11|o>>>21)+r|0,s+=(o^r^n)+p[3]-722521979|0,s=(s<<16|s>>>16)+o|0,n+=(s^o^r)+p[6]+76029189|0,n=(n<<23|n>>>9)+s|0,r+=(n^s^o)+p[9]-640364487|0,r=(r<<4|r>>>28)+n|0,o+=(r^n^s)+p[12]-421815835|0,o=(o<<11|o>>>21)+r|0,s+=(o^r^n)+p[15]+530742520|0,s=(s<<16|s>>>16)+o|0,n+=(s^o^r)+p[2]-995338651|0,n=(n<<23|n>>>9)+s|0,r+=(s^(n|~o))+p[0]-198630844|0,r=(r<<6|r>>>26)+n|0,o+=(n^(r|~s))+p[7]+1126891415|0,o=(o<<10|o>>>22)+r|0,s+=(r^(o|~n))+p[14]-1416354905|0,s=(s<<15|s>>>17)+o|0,n+=(o^(s|~r))+p[5]-57434055|0,n=(n<<21|n>>>11)+s|0,r+=(s^(n|~o))+p[12]+1700485571|0,r=(r<<6|r>>>26)+n|0,o+=(n^(r|~s))+p[3]-1894986606|0,o=(o<<10|o>>>22)+r|0,s+=(r^(o|~n))+p[10]-1051523|0,s=(s<<15|s>>>17)+o|0,n+=(o^(s|~r))+p[1]-2054922799|0,n=(n<<21|n>>>11)+s|0,r+=(s^(n|~o))+p[8]+1873313359|0,r=(r<<6|r>>>26)+n|0,o+=(n^(r|~s))+p[15]-30611744|0,o=(o<<10|o>>>22)+r|0,s+=(r^(o|~n))+p[6]-1560198380|0,s=(s<<15|s>>>17)+o|0,n+=(o^(s|~r))+p[13]+1309151649|0,n=(n<<21|n>>>11)+s|0,r+=(s^(n|~o))+p[4]-145523070|0,r=(r<<6|r>>>26)+n|0,o+=(n^(r|~s))+p[11]-1120210379|0,o=(o<<10|o>>>22)+r|0,s+=(r^(o|~n))+p[2]+718787259|0,s=(s<<15|s>>>17)+o|0,n+=(o^(s|~r))+p[9]-343485551|0,n=(n<<21|n>>>11)+s|0,l[0]=r+l[0]|0,l[1]=n+l[1]|0,l[2]=s+l[2]|0,l[3]=o+l[3]|0}function c(l){var p=[],r;for(r=0;r<64;r+=4)p[r>>2]=l.charCodeAt(r)+(l.charCodeAt(r+1)<<8)+(l.charCodeAt(r+2)<<16)+(l.charCodeAt(r+3)<<24);return p}function h(l){var p=[],r;for(r=0;r<64;r+=4)p[r>>2]=l[r]+(l[r+1]<<8)+(l[r+2]<<16)+(l[r+3]<<24);return p}function g(l){var p=l.length,r=[1732584193,-271733879,-1732584194,271733878],n,s,o,E,C,b;for(n=64;n<=p;n+=64)u(r,c(l.substring(n-64,n)));for(l=l.substring(n-64),s=l.length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0;n<s;n+=1)o[n>>2]|=l.charCodeAt(n)<<(n%4<<3);if(o[n>>2]|=128<<(n%4<<3),n>55)for(u(r,o),n=0;n<16;n+=1)o[n]=0;return E=p*8,E=E.toString(16).match(/(.*?)(.{0,8})$/),C=parseInt(E[2],16),b=parseInt(E[1],16)||0,o[14]=C,o[15]=b,u(r,o),r}function f(l){var p=l.length,r=[1732584193,-271733879,-1732584194,271733878],n,s,o,E,C,b;for(n=64;n<=p;n+=64)u(r,h(l.subarray(n-64,n)));for(l=n-64<p?l.subarray(n-64):new Uint8Array(0),s=l.length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0;n<s;n+=1)o[n>>2]|=l[n]<<(n%4<<3);if(o[n>>2]|=128<<(n%4<<3),n>55)for(u(r,o),n=0;n<16;n+=1)o[n]=0;return E=p*8,E=E.toString(16).match(/(.*?)(.{0,8})$/),C=parseInt(E[2],16),b=parseInt(E[1],16)||0,o[14]=C,o[15]=b,u(r,o),r}function y(l){var p="",r;for(r=0;r<4;r+=1)p+=t[l>>r*8+4&15]+t[l>>r*8&15];return p}function m(l){var p;for(p=0;p<l.length;p+=1)l[p]=y(l[p]);return l.join("")}m(g("hello"))!=="5d41402abc4b2a76b9719d911017c592"&&(e=function(l,p){var r=(l&65535)+(p&65535),n=(l>>16)+(p>>16)+(r>>16);return n<<16|r&65535}),typeof ArrayBuffer<"u"&&!ArrayBuffer.prototype.slice&&(function(){function l(p,r){return p=p|0||0,p<0?Math.max(p+r,0):Math.min(p,r)}ArrayBuffer.prototype.slice=function(p,r){var n=this.byteLength,s=l(p,n),o=n,E,C,b,ce;return r!==i&&(o=l(r,n)),s>o?new ArrayBuffer(0):(E=o-s,C=new ArrayBuffer(E),b=new Uint8Array(C),ce=new Uint8Array(this,s,E),b.set(ce),C)}})();function w(l){return/[\u0080-\uFFFF]/.test(l)&&(l=unescape(encodeURIComponent(l))),l}function q(l,p){var r=l.length,n=new ArrayBuffer(r),s=new Uint8Array(n),o;for(o=0;o<r;o+=1)s[o]=l.charCodeAt(o);return p?s:n}function Be(l){return String.fromCharCode.apply(null,new Uint8Array(l))}function Ue(l,p,r){var n=new Uint8Array(l.byteLength+p.byteLength);return n.set(new Uint8Array(l)),n.set(new Uint8Array(p),l.byteLength),r?n:n.buffer}function O(l){var p=[],r=l.length,n;for(n=0;n<r-1;n+=2)p.push(parseInt(l.substr(n,2),16));return String.fromCharCode.apply(String,p)}function D(){this.reset()}return D.prototype.append=function(l){return this.appendBinary(w(l)),this},D.prototype.appendBinary=function(l){this._buff+=l,this._length+=l.length;var p=this._buff.length,r;for(r=64;r<=p;r+=64)u(this._hash,c(this._buff.substring(r-64,r)));return this._buff=this._buff.substring(r-64),this},D.prototype.end=function(l){var p=this._buff,r=p.length,n,s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],o;for(n=0;n<r;n+=1)s[n>>2]|=p.charCodeAt(n)<<(n%4<<3);return this._finish(s,r),o=m(this._hash),l&&(o=O(o)),this.reset(),o},D.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},D.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},D.prototype.setState=function(l){return this._buff=l.buff,this._length=l.length,this._hash=l.hash,this},D.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},D.prototype._finish=function(l,p){var r=p,n,s,o;if(l[r>>2]|=128<<(r%4<<3),r>55)for(u(this._hash,l),r=0;r<16;r+=1)l[r]=0;n=this._length*8,n=n.toString(16).match(/(.*?)(.{0,8})$/),s=parseInt(n[2],16),o=parseInt(n[1],16)||0,l[14]=s,l[15]=o,u(this._hash,l)},D.hash=function(l,p){return D.hashBinary(w(l),p)},D.hashBinary=function(l,p){var r=g(l),n=m(r);return p?O(n):n},D.ArrayBuffer=function(){this.reset()},D.ArrayBuffer.prototype.append=function(l){var p=Ue(this._buff.buffer,l,!0),r=p.length,n;for(this._length+=l.byteLength,n=64;n<=r;n+=64)u(this._hash,h(p.subarray(n-64,n)));return this._buff=n-64<r?new Uint8Array(p.buffer.slice(n-64)):new Uint8Array(0),this},D.ArrayBuffer.prototype.end=function(l){var p=this._buff,r=p.length,n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],s,o;for(s=0;s<r;s+=1)n[s>>2]|=p[s]<<(s%4<<3);return this._finish(n,r),o=m(this._hash),l&&(o=O(o)),this.reset(),o},D.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},D.ArrayBuffer.prototype.getState=function(){var l=D.prototype.getState.call(this);return l.buff=Be(l.buff),l},D.ArrayBuffer.prototype.setState=function(l){return l.buff=q(l.buff,!0),D.prototype.setState.call(this,l)},D.ArrayBuffer.prototype.destroy=D.prototype.destroy,D.ArrayBuffer.prototype._finish=D.prototype._finish,D.ArrayBuffer.hash=function(l,p){var r=f(new Uint8Array(l)),n=m(r);return p?O(n):n},D})});var te=fe(($t,ve)=>{"use strict";ve.exports={}});async function Je(i){let e=(await Promise.resolve().then(()=>G(Se(),1))).default;return new Promise((t,a)=>{let c=Math.ceil(i.size/2097152),h=0,g=new e.ArrayBuffer,f=new FileReader,y=()=>{let m=h*2097152,w=Math.min(m+2097152,i.size);f.readAsArrayBuffer(i.slice(m,w))};f.onload=m=>{let w=m.target?.result;if(!w){a(d.business("Failed to read file chunk"));return}g.append(w),h++,h<c?y():t({md5:g.end()})},f.onerror=()=>{a(d.business("Failed to calculate MD5: FileReader error"))},y()})}async function Xe(i){let e=await Promise.resolve().then(()=>G(te(),1));if(Buffer.isBuffer(i)){let a=e.createHash("md5");return a.update(i),{md5:a.digest("hex")}}let t=await Promise.resolve().then(()=>G(te(),1));return new Promise((a,u)=>{let c=e.createHash("md5"),h=t.createReadStream(i);h.on("error",g=>u(d.business(`Failed to read file for MD5: ${g.message}`))),h.on("data",g=>c.update(g)),h.on("end",()=>a({md5:c.digest("hex")}))})}async function z(i){let e=M();if(e==="browser"){if(!(i instanceof Blob))throw d.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Je(i)}if(e==="node"){if(!(Buffer.isBuffer(i)||typeof i=="string"))throw d.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Xe(i)}throw d.business("Unknown or unsupported execution environment for MD5 calculation.")}var K=R(()=>{"use strict";k();x()});function Te(i){return et.test(i)}var Ze,et,Ie=R(()=>{"use strict";Ze=["^npm-debug\\.log$","^\\..*\\.swp$","^\\.DS_Store$","^\\.AppleDouble$","^\\.LSOverride$","^Icon\\r$","^\\._.*","^\\.Spotlight-V100(?:$|\\/)","\\.Trashes","^__MACOSX$","~$","^Thumbs\\.db$","^ehthumbs\\.db$","^[Dd]esktop\\.ini$","@eaDir$"],et=new RegExp(Ze.join("|"))});function Fe(i){return!i||i.length===0?[]:i.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let a=t[t.length-1];if(Te(a))return!1;for(let c of t)if(c!==".well-known"&&(c.startsWith(".")||c.length>255))return!1;let u=t.slice(0,-1);for(let c of u)if(tt.some(h=>c.toLowerCase()===h.toLowerCase()))return!1;return!0})}var tt,ne=R(()=>{"use strict";Ie();tt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function H(i){return i.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Pe=R(()=>{"use strict"});function Oe(i,e={}){if(e.flatten===!1)return i.map(a=>({path:H(a),name:re(a)}));let t=nt(i);return i.map(a=>{let u=H(a);if(t){let c=t.endsWith("/")?t:`${t}/`;u.startsWith(c)&&(u=u.substring(c.length))}return u||(u=re(a)),{path:u,name:re(a)}})}function nt(i){if(!i.length)return"";let t=i.map(c=>H(c)).map(c=>c.split("/")),a=[],u=Math.min(...t.map(c=>c.length));for(let c=0;c<u-1;c++){let h=t[0][c];if(t.every(g=>g[c]===h))a.push(h);else break}return a.join("/")}function re(i){return i.split(/[/\\]/).pop()||i}var ie=R(()=>{"use strict";Pe()});function oe(i,e=1){if(i===0)return"0 Bytes";let t=1024,a=["Bytes","KB","MB","GB"],u=Math.floor(Math.log(i)/Math.log(t));return parseFloat((i/Math.pow(t,u)).toFixed(e))+" "+a[u]}function se(i){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(i))return{valid:!1,reason:"File name contains unsafe characters"};if(i.startsWith(" ")||i.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(i.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,a=i.split("/").pop()||i;return t.test(a)?{valid:!1,reason:"File name uses a reserved system name"}:i.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function pn(i,e){let t=[],a=[],u=[];if(i.length===0){let f={file:"(no files)",message:"At least one file must be provided"};return t.push(f),{files:[],validFiles:[],errors:t,warnings:[],canDeploy:!1}}if(i.length>e.maxFilesCount){let f={file:`(${i.length} files)`,message:`File count (${i.length}) exceeds limit of ${e.maxFilesCount}`};return t.push(f),{files:i.map(y=>({...y,status:v.VALIDATION_FAILED,statusMessage:f.message})),validFiles:[],errors:t,warnings:[],canDeploy:!1}}let c=0;for(let f of i){let y=v.READY,m="Ready for upload",w=f.name?se(f.name):{valid:!1,reason:"File name cannot be empty"};if(f.status===v.PROCESSING_ERROR)y=v.VALIDATION_FAILED,m=f.statusMessage||"File failed during processing",t.push({file:f.name,message:m});else if(f.size===0){y=v.EXCLUDED,m="File is empty (0 bytes) and cannot be deployed due to storage limitations",a.push({file:f.name,message:m}),u.push({...f,status:y,statusMessage:m});continue}else f.size<0?(y=v.VALIDATION_FAILED,m="File size must be positive",t.push({file:f.name,message:m})):!f.name||f.name.trim().length===0?(y=v.VALIDATION_FAILED,m="File name cannot be empty",t.push({file:f.name||"(empty)",message:m})):f.name.includes("\0")?(y=v.VALIDATION_FAILED,m="File name contains invalid characters (null byte)",t.push({file:f.name,message:m})):w.valid?N(f.name)?(y=v.VALIDATION_FAILED,m=`File extension not allowed: "${f.name}"`,t.push({file:f.name,message:m})):f.size>e.maxFileSize?(y=v.VALIDATION_FAILED,m=`File size (${oe(f.size)}) exceeds limit of ${oe(e.maxFileSize)}`,t.push({file:f.name,message:m})):(c+=f.size,c>e.maxTotalSize&&(y=v.VALIDATION_FAILED,m=`Total size would exceed limit of ${oe(e.maxTotalSize)}`,t.push({file:f.name,message:m}))):(y=v.VALIDATION_FAILED,m=w.reason||"Invalid file name",t.push({file:f.name,message:m}));u.push({...f,status:y,statusMessage:m})}t.length>0&&(u=u.map(f=>f.status===v.EXCLUDED?f:{...f,status:v.VALIDATION_FAILED,statusMessage:f.status===v.VALIDATION_FAILED?f.statusMessage:"Deployment failed due to validation errors in bundle"}));let h=t.length===0?u.filter(f=>f.status===v.READY):[],g=t.length===0;return{files:u,validFiles:h,errors:t,warnings:a,canDeploy:g}}function rt(i){return i.filter(e=>e.status===v.READY)}function ln(i){return rt(i).length>0}var ae=R(()=>{"use strict";x()});function _e(i,e){if(i.includes("\0")||i.includes("/../")||i.startsWith("../")||i.endsWith("/.."))throw d.business(`Security error: Unsafe file path "${i}" for file: ${e}`)}function $e(i,e){let t=se(i);if(!t.valid)throw d.business(t.reason||"Invalid file name");if(N(i))throw d.business(`File extension not allowed: "${e}"`)}var pe=R(()=>{"use strict";x();ae()});var Le={};qe(Le,{processFilesForBrowser:()=>Ne});async function Ne(i,e={}){if(M()!=="browser")throw d.business("processFilesForBrowser can only be called in a browser environment.");let t=i.map(y=>y.webkitRelativePath||y.name),a=new Set(Fe(t)),u=[];for(let y=0;y<i.length;y++)a.has(t[y])&&u.push({file:i[y],rawPath:t[y]});if(u.length===0)return[];let c=Oe(u.map(y=>y.rawPath),{flatten:e.pathDetect!==!1}),h=F(),g=[],f=0;for(let y=0;y<u.length;y++){let{file:m}=u[y],w=c[y].path;if(_e(w,m.name),m.size===0)continue;if($e(w,m.name),m.size>h.maxFileSize)throw d.business(`File ${m.name} is too large. Maximum allowed size is ${h.maxFileSize/(1024*1024)}MB.`);if(f+=m.size,f>h.maxTotalSize)throw d.business(`Total deploy size is too large. Maximum allowed is ${h.maxTotalSize/(1024*1024)}MB.`);let{md5:q}=await z(m);g.push({path:w,content:m,size:m.size,md5:q})}if(g.length>h.maxFilesCount)throw d.business(`Too many files to deploy. Maximum allowed is ${h.maxFilesCount} files.`);return g}var le=R(()=>{"use strict";K();x();k();ne();ie();pe();P()});x();var B=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let a=this.handlers.get(e);a&&(a.delete(t),a.size===0&&this.handlers.delete(e))}emit(e,...t){let a=this.handlers.get(e);if(!a)return;let u=Array.from(a);for(let c of u)try{c(...t)}catch(h){a.delete(c),e!=="error"&&setTimeout(()=>{h instanceof Error?this.emit("error",h,String(e)):this.emit("error",new Error(String(h)),String(e))},0)}}transfer(e){this.handlers.forEach((t,a)=>{t.forEach(u=>{e.on(a,u)})})}clear(){this.handlers.clear()}};var S={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Ye=3e4,U=class extends B{constructor(e){super(),this.apiUrl=e.apiUrl||L,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Ye,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,t,a){let u=this.mergeHeaders(t.headers),{signal:c,cleanup:h}=this.createTimeoutSignal(t.signal),g={...t,headers:u,credentials:u.Authorization?void 0:"include",signal:c};this.emit("request",e,g);try{let f=await fetch(e,g);return h(),f.ok||await this.handleResponseError(f,a),this.emit("response",this.safeClone(f),e),{data:await this.parseResponse(this.safeClone(f)),status:f.status}}catch(f){h();let y=f instanceof Error?f:new Error(String(f));this.emit("error",y,e),this.handleFetchError(f,a)}}async request(e,t,a){let{data:u}=await this.executeRequest(e,t,a);return u}async requestWithStatus(e,t,a){return this.executeRequest(e,t,a)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let t=new AbortController,a=setTimeout(()=>t.abort(),this.timeout);if(e){let u=()=>t.abort();e.addEventListener("abort",u),e.aborted&&t.abort()}return{signal:t.signal,cleanup:()=>clearTimeout(a)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,t){let a={};try{if(e.headers.get("content-type")?.includes("application/json")){let h=await e.json();if(h&&typeof h=="object"){let g=h;typeof g.message=="string"&&(a.message=g.message),typeof g.error=="string"&&(a.error=g.error)}}else a={message:await e.text()}}catch{a={message:"Failed to parse error response"}}let u=a.message||a.error||`${t} failed`;throw e.status===401?d.authentication(u):d.api(u,e.status)}handleFetchError(e,t){throw J(e)?e:e instanceof Error&&e.name==="AbortError"?d.cancelled(`${t} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?d.network(`${t} failed: ${e.message}`,e):e instanceof Error?d.business(`${t} failed: ${e.message}`):d.business(`${t} failed: Unknown error`)}async deploy(e,t={}){if(!e.length)throw d.business("No files to deploy");for(let h of e)if(!h.md5)throw d.file(`MD5 checksum missing for file: ${h.path}`,h.path);let{body:a,headers:u}=await this.createDeployBody(e,t.labels,t.via),c={};return t.deployToken?c.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(c.Authorization=`Bearer ${t.apiKey}`),t.caller&&(c["X-Caller"]=t.caller),this.request(`${t.apiUrl||this.apiUrl}${S.DEPLOYMENTS}`,{method:"POST",body:a,headers:{...u,...c},signal:t.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,t){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:t})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,t,a){let u={};t&&(u.deployment=t),a!==void 0&&(u.labels=a);let{data:c,status:h}=await this.requestWithStatus(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)},"Set domain");return{...c,isCreate:h===201}}async listDomains(){return this.request(`${this.apiUrl}${S.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${S.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,t){let a={};return e!==void 0&&(a.ttl=e),t!==void 0&&(a.labels=t),this.request(`${this.apiUrl}${S.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${S.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${S.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${S.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${S.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${S.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e){let t=e.find(h=>h.path==="index.html"||h.path==="/index.html");if(!t||t.size>100*1024)return!1;let a;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))a=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)a=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)a=await t.content.text();else return!1;let u={files:e.map(h=>h.path),index:a};return(await this.request(`${this.apiUrl}${S.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)},"SPA check")).isSPA}};x();P();x();x();function ye(i={},e={}){let t={apiUrl:i.apiUrl||e.apiUrl||L,apiKey:i.apiKey!==void 0?i.apiKey:e.apiKey,deployToken:i.deployToken!==void 0?i.deployToken:e.deployToken},a={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(a.apiKey=t.apiKey),t.deployToken!==void 0&&(a.deployToken=t.deployToken),a}function ge(i,e){let t={...i};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.caller===void 0&&e.caller!==void 0&&(t.caller=e.caller),t}x();K();async function Qe(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:a}=await z(t);return{path:X,content:t,size:e.length,md5:a}}async function Ee(i,e,t){if(t.spaDetect===!1||i.some(a=>a.path===X))return i;try{if(await e.checkSPA(i)){let u=await Qe();return[...i,u]}}catch{}return i}function we(i){let{getApi:e,ensureInit:t,processInput:a,clientDefaults:u,hasAuth:c}=i;return{create:async(h,g={})=>{await t();let f=u?ge(g,u):g;if(c&&!c()&&!f.deployToken&&!f.apiKey)throw d.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!a)throw d.config("processInput function is not provided.");let y=e(),m=await a(h,f);return m=await Ee(m,y,f),y.deploy(m,f)},list:async()=>(await t(),e().listDeployments()),get:async h=>(await t(),e().getDeployment(h)),set:async(h,g)=>(await t(),e().updateDeploymentLabels(h,g.labels)),remove:async h=>{await t(),await e().removeDeployment(h)}}}function xe(i){let{getApi:e,ensureInit:t}=i;return{set:async(a,u={})=>(await t(),e().setDomain(a,u.deployment,u.labels)),list:async()=>(await t(),e().listDomains()),get:async a=>(await t(),e().getDomain(a)),remove:async a=>{await t(),await e().removeDomain(a)},verify:async a=>(await t(),e().verifyDomain(a)),validate:async a=>(await t(),e().validateDomain(a)),dns:async a=>(await t(),e().getDomainDns(a)),records:async a=>(await t(),e().getDomainRecords(a)),share:async a=>(await t(),e().getDomainShare(a))}}function Re(i){let{getApi:e,ensureInit:t}=i;return{get:async()=>(await t(),e().getAccount())}}function Ce(i){let{getApi:e,ensureInit:t}=i;return{create:async(a={})=>(await t(),e().createToken(a.ttl,a.labels)),list:async()=>(await t(),e().listTokens()),remove:async a=>{await t(),await e().removeToken(a)}}}var V=class{constructor(e={}){this.initPromise=null;this._config=null;this.auth=null;this.clientOptions=e,e.deployToken?this.auth={type:"token",value:e.deployToken}:e.apiKey&&(this.auth={type:"apiKey",value:e.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(e);this.http=new U({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let a={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=we({...a,processInput:(u,c)=>this.processInput(u,c),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=xe(a),this._account=Re(a),this._tokens=Ce(a)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=F(),this._config)}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}setDeployToken(e){if(!e||typeof e!="string")throw d.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw d.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};P();x();x();async function be(i,e,t){let a=new FormData,u=[];for(let c of i){if(!(c.content instanceof File||c.content instanceof Blob))throw d.file(`Unsupported file.content type for browser: ${c.path}`,c.path);if(!c.md5)throw d.file(`File missing md5 checksum: ${c.path}`,c.path);let h=new File([c.content],c.path,{type:"application/octet-stream"});a.append("files[]",h),u.push(c.md5)}return a.append("checksums",JSON.stringify(u)),e&&e.length>0&&a.append("labels",JSON.stringify(e)),t&&a.append("via",t),{body:a,headers:{}}}K();function Qt(i,e,t,a=!0){let u=i===1?e:t;return a?`${i} ${u}`:u}ne();ie();k();ae();pe();x();P();le();var ue=class extends V{constructor(e={}){super(e)}resolveInitialConfig(e){return ye(e,{})}async loadFullConfig(){try{let e=await this.http.getConfig();Z(e)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.isFileArray(e))throw d.business("Invalid input type for browser environment. Expected File[].");if(e.length===0)throw d.business("No files to deploy.");let{processFilesForBrowser:a}=await Promise.resolve().then(()=>(le(),Le));return a(e,t)}isFileArray(e){return Array.isArray(e)&&e.every(t=>t instanceof File)}getDeployBodyCreator(){return be}},kn=ue;export{Y as API_KEY_HEX_LENGTH,pt as API_KEY_HINT_LENGTH,T as API_KEY_PREFIX,he as API_KEY_TOTAL_LENGTH,at as AccountPlan,U as ApiHttp,lt as AuthMethod,je as BLOCKED_EXTENSIONS,L as DEFAULT_API,X as DEPLOYMENT_CONFIG_FILENAME,W as DEPLOY_TOKEN_HEX_LENGTH,I as DEPLOY_TOKEN_PREFIX,de as DEPLOY_TOKEN_TOTAL_LENGTH,ot as DeploymentStatus,st as DomainStatus,A as ErrorType,v as FILE_VALIDATION_STATUS,v as FileValidationStatus,tt as JUNK_DIRECTORIES,Dt as LABEL_CONSTRAINTS,At as LABEL_PATTERN,ue as Ship,d as ShipError,Ot as __setTestEnvironment,ln as allValidFilesReady,z as calculateMD5,Re as createAccountResource,we as createDeploymentResource,xe as createDomainResource,Ce as createTokenResource,kn as default,vt as deserializeLabels,mt as extractSubdomain,Fe as filterJunk,oe as formatFileSize,yt as generateDeploymentUrl,gt as generateDomainUrl,F as getCurrentConfig,M as getENV,rt as getValidFiles,N as isBlockedExtension,dt as isCustomDomain,ht as isDeployment,me as isPlatformDomain,J as isShipError,ge as mergeDeployOptions,Oe as optimizeDeployPaths,Qt as pluralize,Ne as processFilesForBrowser,ye as resolveConfig,St as serializeLabels,Z as setPlatformConfig,ut as validateApiKey,ft as validateApiUrl,$e as validateDeployFile,_e as validateDeployPath,ct as validateDeployToken,se as validateFileName,pn as validateFiles};
|
|
1
|
+
var Me=Object.create;var _=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var He=Object.getPrototypeOf,Ke=Object.prototype.hasOwnProperty;var Ve=(i,r,e)=>r in i?_(i,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[r]=e;var R=(i,r)=>()=>(i&&(r=i(i=0)),r);var fe=(i,r)=>()=>(r||i((r={exports:{}}).exports,r),r.exports),Ge=(i,r)=>{for(var e in r)_(i,e,{get:r[e],enumerable:!0})},qe=(i,r,e,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let u of ze(r))!Ke.call(i,u)&&u!==e&&_(i,u,{get:()=>r[u],enumerable:!(a=ke(r,u))||a.enumerable});return i};var q=(i,r,e)=>(e=i!=null?Me(He(i)):{},qe(r||!i||!i.__esModule?_(e,"default",{value:i,enumerable:!0}):e,i));var $=(i,r,e)=>Ve(i,typeof r!="symbol"?r+"":r,e);function J(i){return i!==null&&typeof i=="object"&&"name"in i&&i.name==="ShipError"&&"status"in i}function N(i){let r=i.lastIndexOf(".");if(r===-1||r===i.length-1)return!1;let e=i.slice(r+1).toLowerCase();return je.has(e)}function ut(i){if(!i.startsWith(T))throw h.validation(`API key must start with "${T}"`);if(i.length!==he)throw h.validation(`API key must be ${he} characters total (${T} + ${Y} hex chars)`);let r=i.slice(T.length);if(!/^[a-f0-9]{64}$/i.test(r))throw h.validation(`API key must contain ${Y} hexadecimal characters after "${T}" prefix`)}function ct(i){if(!i.startsWith(I))throw h.validation(`Deploy token must start with "${I}"`);if(i.length!==de)throw h.validation(`Deploy token must be ${de} characters total (${I} + ${W} hex chars)`);let r=i.slice(I.length);if(!/^[a-f0-9]{64}$/i.test(r))throw h.validation(`Deploy token must contain ${W} hexadecimal characters after "${I}" prefix`)}function ft(i){try{let r=new URL(i);if(!["http:","https:"].includes(r.protocol))throw h.validation("API URL must use http:// or https:// protocol");if(r.pathname!=="/"&&r.pathname!=="")throw h.validation("API URL must not contain a path");if(r.search||r.hash)throw h.validation("API URL must not contain query parameters or fragments")}catch(r){throw J(r)?r:h.validation("API URL must be a valid URL")}}function ht(i){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(i)}function me(i,r){return i.endsWith(`.${r}`)}function dt(i,r){return!me(i,r)}function mt(i,r){return me(i,r)?i.slice(0,-(r.length+1)):null}function yt(i,r){return`https://${i}.${r||"shipstatic.com"}`}function gt(i){return`https://${i}`}function St(i){return!i||i.length===0?null:JSON.stringify(i)}function vt(i){if(!i)return[];try{let r=JSON.parse(i);return Array.isArray(r)?r:[]}catch{return[]}}var ot,st,at,A,j,h,je,T,Y,he,lt,I,W,de,pt,X,L,v,Dt,At,b=R(()=>{"use strict";ot={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},st={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},at={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"};(function(i){i.Validation="validation_failed",i.NotFound="not_found",i.RateLimit="rate_limit_exceeded",i.Authentication="authentication_failed",i.Business="business_logic_error",i.Api="internal_server_error",i.Network="network_error",i.Cancelled="operation_cancelled",i.File="file_error",i.Config="config_error"})(A||(A={}));j={client:new Set([A.Business,A.Config,A.File,A.Validation]),network:new Set([A.Network]),auth:new Set([A.Authentication])},h=class i extends Error{constructor(e,a,u,c){super(a);$(this,"type");$(this,"status");$(this,"details");this.type=e,this.status=u,this.details=c,this.name="ShipError"}toResponse(){let e=this.type===A.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static fromResponse(e){return new i(e.error,e.message,e.status,e.details)}static validation(e,a){return new i(A.Validation,e,400,a)}static notFound(e,a){let u=a?`${e} ${a} not found`:`${e} not found`;return new i(A.NotFound,u,404)}static rateLimit(e="Too many requests"){return new i(A.RateLimit,e,429)}static authentication(e="Authentication required",a){return new i(A.Authentication,e,401,a)}static business(e,a=400){return new i(A.Business,e,a)}static network(e,a){return new i(A.Network,e,void 0,{cause:a})}static cancelled(e){return new i(A.Cancelled,e)}static file(e,a){return new i(A.File,e,void 0,{filePath:a})}static config(e,a){return new i(A.Config,e,void 0,a)}static api(e,a=500){return new i(A.Api,e,a)}static database(e,a=500){return new i(A.Api,e,a)}static storage(e,a=500){return new i(A.Api,e,a)}get filePath(){return this.details?.filePath}isClientError(){return j.client.has(this.type)}isNetworkError(){return j.network.has(this.type)}isAuthError(){return j.auth.has(this.type)}isValidationError(){return this.type===A.Validation}isFileError(){return this.type===A.File}isConfigError(){return this.type===A.Config}isType(e){return this.type===e}};je=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"]);T="ship-",Y=64,he=T.length+Y,lt=4,I="token-",W=64,de=I.length+W,pt={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},X="ship.json";L="https://api.shipstatic.com",v={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};Dt={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},At=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function Z(i){Q=i}function F(){if(Q===null)throw h.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return Q}var Q,P=R(()=>{"use strict";b();Q=null});function Ot(i){ee=i}function We(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function M(){return ee||We()}var ee,k=R(()=>{"use strict";ee=null});var Se=fe((De,Ae)=>{"use strict";(function(i){if(typeof De=="object")Ae.exports=i();else if(typeof define=="function"&&define.amd)define(i);else{var r;try{r=window}catch{r=self}r.SparkMD5=i()}})(function(i){"use strict";var r=function(p,l){return p+l&4294967295},e=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function a(p,l,n,t,s,o){return l=r(r(l,p),r(t,o)),r(l<<s|l>>>32-s,n)}function u(p,l){var n=p[0],t=p[1],s=p[2],o=p[3];n+=(t&s|~t&o)+l[0]-680876936|0,n=(n<<7|n>>>25)+t|0,o+=(n&t|~n&s)+l[1]-389564586|0,o=(o<<12|o>>>20)+n|0,s+=(o&n|~o&t)+l[2]+606105819|0,s=(s<<17|s>>>15)+o|0,t+=(s&o|~s&n)+l[3]-1044525330|0,t=(t<<22|t>>>10)+s|0,n+=(t&s|~t&o)+l[4]-176418897|0,n=(n<<7|n>>>25)+t|0,o+=(n&t|~n&s)+l[5]+1200080426|0,o=(o<<12|o>>>20)+n|0,s+=(o&n|~o&t)+l[6]-1473231341|0,s=(s<<17|s>>>15)+o|0,t+=(s&o|~s&n)+l[7]-45705983|0,t=(t<<22|t>>>10)+s|0,n+=(t&s|~t&o)+l[8]+1770035416|0,n=(n<<7|n>>>25)+t|0,o+=(n&t|~n&s)+l[9]-1958414417|0,o=(o<<12|o>>>20)+n|0,s+=(o&n|~o&t)+l[10]-42063|0,s=(s<<17|s>>>15)+o|0,t+=(s&o|~s&n)+l[11]-1990404162|0,t=(t<<22|t>>>10)+s|0,n+=(t&s|~t&o)+l[12]+1804603682|0,n=(n<<7|n>>>25)+t|0,o+=(n&t|~n&s)+l[13]-40341101|0,o=(o<<12|o>>>20)+n|0,s+=(o&n|~o&t)+l[14]-1502002290|0,s=(s<<17|s>>>15)+o|0,t+=(s&o|~s&n)+l[15]+1236535329|0,t=(t<<22|t>>>10)+s|0,n+=(t&o|s&~o)+l[1]-165796510|0,n=(n<<5|n>>>27)+t|0,o+=(n&s|t&~s)+l[6]-1069501632|0,o=(o<<9|o>>>23)+n|0,s+=(o&t|n&~t)+l[11]+643717713|0,s=(s<<14|s>>>18)+o|0,t+=(s&n|o&~n)+l[0]-373897302|0,t=(t<<20|t>>>12)+s|0,n+=(t&o|s&~o)+l[5]-701558691|0,n=(n<<5|n>>>27)+t|0,o+=(n&s|t&~s)+l[10]+38016083|0,o=(o<<9|o>>>23)+n|0,s+=(o&t|n&~t)+l[15]-660478335|0,s=(s<<14|s>>>18)+o|0,t+=(s&n|o&~n)+l[4]-405537848|0,t=(t<<20|t>>>12)+s|0,n+=(t&o|s&~o)+l[9]+568446438|0,n=(n<<5|n>>>27)+t|0,o+=(n&s|t&~s)+l[14]-1019803690|0,o=(o<<9|o>>>23)+n|0,s+=(o&t|n&~t)+l[3]-187363961|0,s=(s<<14|s>>>18)+o|0,t+=(s&n|o&~n)+l[8]+1163531501|0,t=(t<<20|t>>>12)+s|0,n+=(t&o|s&~o)+l[13]-1444681467|0,n=(n<<5|n>>>27)+t|0,o+=(n&s|t&~s)+l[2]-51403784|0,o=(o<<9|o>>>23)+n|0,s+=(o&t|n&~t)+l[7]+1735328473|0,s=(s<<14|s>>>18)+o|0,t+=(s&n|o&~n)+l[12]-1926607734|0,t=(t<<20|t>>>12)+s|0,n+=(t^s^o)+l[5]-378558|0,n=(n<<4|n>>>28)+t|0,o+=(n^t^s)+l[8]-2022574463|0,o=(o<<11|o>>>21)+n|0,s+=(o^n^t)+l[11]+1839030562|0,s=(s<<16|s>>>16)+o|0,t+=(s^o^n)+l[14]-35309556|0,t=(t<<23|t>>>9)+s|0,n+=(t^s^o)+l[1]-1530992060|0,n=(n<<4|n>>>28)+t|0,o+=(n^t^s)+l[4]+1272893353|0,o=(o<<11|o>>>21)+n|0,s+=(o^n^t)+l[7]-155497632|0,s=(s<<16|s>>>16)+o|0,t+=(s^o^n)+l[10]-1094730640|0,t=(t<<23|t>>>9)+s|0,n+=(t^s^o)+l[13]+681279174|0,n=(n<<4|n>>>28)+t|0,o+=(n^t^s)+l[0]-358537222|0,o=(o<<11|o>>>21)+n|0,s+=(o^n^t)+l[3]-722521979|0,s=(s<<16|s>>>16)+o|0,t+=(s^o^n)+l[6]+76029189|0,t=(t<<23|t>>>9)+s|0,n+=(t^s^o)+l[9]-640364487|0,n=(n<<4|n>>>28)+t|0,o+=(n^t^s)+l[12]-421815835|0,o=(o<<11|o>>>21)+n|0,s+=(o^n^t)+l[15]+530742520|0,s=(s<<16|s>>>16)+o|0,t+=(s^o^n)+l[2]-995338651|0,t=(t<<23|t>>>9)+s|0,n+=(s^(t|~o))+l[0]-198630844|0,n=(n<<6|n>>>26)+t|0,o+=(t^(n|~s))+l[7]+1126891415|0,o=(o<<10|o>>>22)+n|0,s+=(n^(o|~t))+l[14]-1416354905|0,s=(s<<15|s>>>17)+o|0,t+=(o^(s|~n))+l[5]-57434055|0,t=(t<<21|t>>>11)+s|0,n+=(s^(t|~o))+l[12]+1700485571|0,n=(n<<6|n>>>26)+t|0,o+=(t^(n|~s))+l[3]-1894986606|0,o=(o<<10|o>>>22)+n|0,s+=(n^(o|~t))+l[10]-1051523|0,s=(s<<15|s>>>17)+o|0,t+=(o^(s|~n))+l[1]-2054922799|0,t=(t<<21|t>>>11)+s|0,n+=(s^(t|~o))+l[8]+1873313359|0,n=(n<<6|n>>>26)+t|0,o+=(t^(n|~s))+l[15]-30611744|0,o=(o<<10|o>>>22)+n|0,s+=(n^(o|~t))+l[6]-1560198380|0,s=(s<<15|s>>>17)+o|0,t+=(o^(s|~n))+l[13]+1309151649|0,t=(t<<21|t>>>11)+s|0,n+=(s^(t|~o))+l[4]-145523070|0,n=(n<<6|n>>>26)+t|0,o+=(t^(n|~s))+l[11]-1120210379|0,o=(o<<10|o>>>22)+n|0,s+=(n^(o|~t))+l[2]+718787259|0,s=(s<<15|s>>>17)+o|0,t+=(o^(s|~n))+l[9]-343485551|0,t=(t<<21|t>>>11)+s|0,p[0]=n+p[0]|0,p[1]=t+p[1]|0,p[2]=s+p[2]|0,p[3]=o+p[3]|0}function c(p){var l=[],n;for(n=0;n<64;n+=4)l[n>>2]=p.charCodeAt(n)+(p.charCodeAt(n+1)<<8)+(p.charCodeAt(n+2)<<16)+(p.charCodeAt(n+3)<<24);return l}function d(p){var l=[],n;for(n=0;n<64;n+=4)l[n>>2]=p[n]+(p[n+1]<<8)+(p[n+2]<<16)+(p[n+3]<<24);return l}function g(p){var l=p.length,n=[1732584193,-271733879,-1732584194,271733878],t,s,o,E,x,C;for(t=64;t<=l;t+=64)u(n,c(p.substring(t-64,t)));for(p=p.substring(t-64),s=p.length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t<s;t+=1)o[t>>2]|=p.charCodeAt(t)<<(t%4<<3);if(o[t>>2]|=128<<(t%4<<3),t>55)for(u(n,o),t=0;t<16;t+=1)o[t]=0;return E=l*8,E=E.toString(16).match(/(.*?)(.{0,8})$/),x=parseInt(E[2],16),C=parseInt(E[1],16)||0,o[14]=x,o[15]=C,u(n,o),n}function f(p){var l=p.length,n=[1732584193,-271733879,-1732584194,271733878],t,s,o,E,x,C;for(t=64;t<=l;t+=64)u(n,d(p.subarray(t-64,t)));for(p=t-64<l?p.subarray(t-64):new Uint8Array(0),s=p.length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t<s;t+=1)o[t>>2]|=p[t]<<(t%4<<3);if(o[t>>2]|=128<<(t%4<<3),t>55)for(u(n,o),t=0;t<16;t+=1)o[t]=0;return E=l*8,E=E.toString(16).match(/(.*?)(.{0,8})$/),x=parseInt(E[2],16),C=parseInt(E[1],16)||0,o[14]=x,o[15]=C,u(n,o),n}function m(p){var l="",n;for(n=0;n<4;n+=1)l+=e[p>>n*8+4&15]+e[p>>n*8&15];return l}function y(p){var l;for(l=0;l<p.length;l+=1)p[l]=m(p[l]);return p.join("")}y(g("hello"))!=="5d41402abc4b2a76b9719d911017c592"&&(r=function(p,l){var n=(p&65535)+(l&65535),t=(p>>16)+(l>>16)+(n>>16);return t<<16|n&65535}),typeof ArrayBuffer<"u"&&!ArrayBuffer.prototype.slice&&(function(){function p(l,n){return l=l|0||0,l<0?Math.max(l+n,0):Math.min(l,n)}ArrayBuffer.prototype.slice=function(l,n){var t=this.byteLength,s=p(l,t),o=t,E,x,C,ce;return n!==i&&(o=p(n,t)),s>o?new ArrayBuffer(0):(E=o-s,x=new ArrayBuffer(E),C=new Uint8Array(x),ce=new Uint8Array(this,s,E),C.set(ce),x)}})();function w(p){return/[\u0080-\uFFFF]/.test(p)&&(p=unescape(encodeURIComponent(p))),p}function G(p,l){var n=p.length,t=new ArrayBuffer(n),s=new Uint8Array(t),o;for(o=0;o<n;o+=1)s[o]=p.charCodeAt(o);return l?s:t}function Be(p){return String.fromCharCode.apply(null,new Uint8Array(p))}function Ue(p,l,n){var t=new Uint8Array(p.byteLength+l.byteLength);return t.set(new Uint8Array(p)),t.set(new Uint8Array(l),p.byteLength),n?t:t.buffer}function O(p){var l=[],n=p.length,t;for(t=0;t<n-1;t+=2)l.push(parseInt(p.substr(t,2),16));return String.fromCharCode.apply(String,l)}function D(){this.reset()}return D.prototype.append=function(p){return this.appendBinary(w(p)),this},D.prototype.appendBinary=function(p){this._buff+=p,this._length+=p.length;var l=this._buff.length,n;for(n=64;n<=l;n+=64)u(this._hash,c(this._buff.substring(n-64,n)));return this._buff=this._buff.substring(n-64),this},D.prototype.end=function(p){var l=this._buff,n=l.length,t,s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],o;for(t=0;t<n;t+=1)s[t>>2]|=l.charCodeAt(t)<<(t%4<<3);return this._finish(s,n),o=y(this._hash),p&&(o=O(o)),this.reset(),o},D.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},D.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},D.prototype.setState=function(p){return this._buff=p.buff,this._length=p.length,this._hash=p.hash,this},D.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},D.prototype._finish=function(p,l){var n=l,t,s,o;if(p[n>>2]|=128<<(n%4<<3),n>55)for(u(this._hash,p),n=0;n<16;n+=1)p[n]=0;t=this._length*8,t=t.toString(16).match(/(.*?)(.{0,8})$/),s=parseInt(t[2],16),o=parseInt(t[1],16)||0,p[14]=s,p[15]=o,u(this._hash,p)},D.hash=function(p,l){return D.hashBinary(w(p),l)},D.hashBinary=function(p,l){var n=g(p),t=y(n);return l?O(t):t},D.ArrayBuffer=function(){this.reset()},D.ArrayBuffer.prototype.append=function(p){var l=Ue(this._buff.buffer,p,!0),n=l.length,t;for(this._length+=p.byteLength,t=64;t<=n;t+=64)u(this._hash,d(l.subarray(t-64,t)));return this._buff=t-64<n?new Uint8Array(l.buffer.slice(t-64)):new Uint8Array(0),this},D.ArrayBuffer.prototype.end=function(p){var l=this._buff,n=l.length,t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],s,o;for(s=0;s<n;s+=1)t[s>>2]|=l[s]<<(s%4<<3);return this._finish(t,n),o=y(this._hash),p&&(o=O(o)),this.reset(),o},D.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},D.ArrayBuffer.prototype.getState=function(){var p=D.prototype.getState.call(this);return p.buff=Be(p.buff),p},D.ArrayBuffer.prototype.setState=function(p){return p.buff=G(p.buff,!0),D.prototype.setState.call(this,p)},D.ArrayBuffer.prototype.destroy=D.prototype.destroy,D.ArrayBuffer.prototype._finish=D.prototype._finish,D.ArrayBuffer.hash=function(p,l){var n=f(new Uint8Array(p)),t=y(n);return l?O(t):t},D})});var te=fe(($t,ve)=>{"use strict";ve.exports={}});async function Je(i){let r=(await Promise.resolve().then(()=>q(Se(),1))).default;return new Promise((e,a)=>{let c=Math.ceil(i.size/2097152),d=0,g=new r.ArrayBuffer,f=new FileReader,m=()=>{let y=d*2097152,w=Math.min(y+2097152,i.size);f.readAsArrayBuffer(i.slice(y,w))};f.onload=y=>{let w=y.target?.result;if(!w){a(h.business("Failed to read file chunk"));return}g.append(w),d++,d<c?m():e({md5:g.end()})},f.onerror=()=>{a(h.business("Failed to calculate MD5: FileReader error"))},m()})}async function Xe(i){let r=await Promise.resolve().then(()=>q(te(),1));if(Buffer.isBuffer(i)){let a=r.createHash("md5");return a.update(i),{md5:a.digest("hex")}}let e=await Promise.resolve().then(()=>q(te(),1));return new Promise((a,u)=>{let c=r.createHash("md5"),d=e.createReadStream(i);d.on("error",g=>u(h.business(`Failed to read file for MD5: ${g.message}`))),d.on("data",g=>c.update(g)),d.on("end",()=>a({md5:c.digest("hex")}))})}async function z(i){let r=M();if(r==="browser"){if(!(i instanceof Blob))throw h.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Je(i)}if(r==="node"){if(!(Buffer.isBuffer(i)||typeof i=="string"))throw h.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Xe(i)}throw h.business("Unknown or unsupported execution environment for MD5 calculation.")}var H=R(()=>{"use strict";k();b()});function Te(i){return et.test(i)}var Ze,et,Ie=R(()=>{"use strict";Ze=["^npm-debug\\.log$","^\\..*\\.swp$","^\\.DS_Store$","^\\.AppleDouble$","^\\.LSOverride$","^Icon\\r$","^\\._.*","^\\.Spotlight-V100(?:$|\\/)","\\.Trashes","^__MACOSX$","~$","^Thumbs\\.db$","^ehthumbs\\.db$","^[Dd]esktop\\.ini$","@eaDir$"],et=new RegExp(Ze.join("|"))});function Fe(i){return!i||i.length===0?[]:i.filter(r=>{if(!r)return!1;let e=r.replace(/\\/g,"/").split("/").filter(Boolean);if(e.length===0)return!0;let a=e[e.length-1];if(Te(a))return!1;for(let c of e)if(c!==".well-known"&&(c.startsWith(".")||c.length>255))return!1;let u=e.slice(0,-1);for(let c of u)if(tt.some(d=>c.toLowerCase()===d.toLowerCase()))return!1;return!0})}var tt,ne=R(()=>{"use strict";Ie();tt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function V(i){return i.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Pe=R(()=>{"use strict"});function Oe(i,r={}){if(r.flatten===!1)return i.map(a=>({path:V(a),name:re(a)}));let e=nt(i);return i.map(a=>{let u=V(a);if(e){let c=e.endsWith("/")?e:`${e}/`;u.startsWith(c)&&(u=u.substring(c.length))}return u||(u=re(a)),{path:u,name:re(a)}})}function nt(i){if(!i.length)return"";let e=i.map(c=>V(c)).map(c=>c.split("/")),a=[],u=Math.min(...e.map(c=>c.length));for(let c=0;c<u-1;c++){let d=e[0][c];if(e.every(g=>g[c]===d))a.push(d);else break}return a.join("/")}function re(i){return i.split(/[/\\]/).pop()||i}var ie=R(()=>{"use strict";Pe()});function oe(i,r=1){if(i===0)return"0 Bytes";let e=1024,a=["Bytes","KB","MB","GB"],u=Math.floor(Math.log(i)/Math.log(e));return parseFloat((i/Math.pow(e,u)).toFixed(r))+" "+a[u]}function se(i){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(i))return{valid:!1,reason:"File name contains unsafe characters"};if(i.startsWith(" ")||i.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(i.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let e=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,a=i.split("/").pop()||i;return e.test(a)?{valid:!1,reason:"File name uses a reserved system name"}:i.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function ln(i,r){let e=[],a=[],u=[];if(i.length===0){let f={file:"(no files)",message:"At least one file must be provided"};return e.push(f),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}if(i.length>r.maxFilesCount){let f={file:`(${i.length} files)`,message:`File count (${i.length}) exceeds limit of ${r.maxFilesCount}`};return e.push(f),{files:i.map(m=>({...m,status:v.VALIDATION_FAILED,statusMessage:f.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let c=0;for(let f of i){let m=v.READY,y="Ready for upload",w=f.name?se(f.name):{valid:!1,reason:"File name cannot be empty"};if(f.status===v.PROCESSING_ERROR)m=v.VALIDATION_FAILED,y=f.statusMessage||"File failed during processing",e.push({file:f.name,message:y});else if(f.size===0){m=v.EXCLUDED,y="File is empty (0 bytes) and cannot be deployed due to storage limitations",a.push({file:f.name,message:y}),u.push({...f,status:m,statusMessage:y});continue}else f.size<0?(m=v.VALIDATION_FAILED,y="File size must be positive",e.push({file:f.name,message:y})):!f.name||f.name.trim().length===0?(m=v.VALIDATION_FAILED,y="File name cannot be empty",e.push({file:f.name||"(empty)",message:y})):f.name.includes("\0")?(m=v.VALIDATION_FAILED,y="File name contains invalid characters (null byte)",e.push({file:f.name,message:y})):w.valid?N(f.name)?(m=v.VALIDATION_FAILED,y=`File extension not allowed: "${f.name}"`,e.push({file:f.name,message:y})):f.size>r.maxFileSize?(m=v.VALIDATION_FAILED,y=`File size (${oe(f.size)}) exceeds limit of ${oe(r.maxFileSize)}`,e.push({file:f.name,message:y})):(c+=f.size,c>r.maxTotalSize&&(m=v.VALIDATION_FAILED,y=`Total size would exceed limit of ${oe(r.maxTotalSize)}`,e.push({file:f.name,message:y}))):(m=v.VALIDATION_FAILED,y=w.reason||"Invalid file name",e.push({file:f.name,message:y}));u.push({...f,status:m,statusMessage:y})}e.length>0&&(u=u.map(f=>f.status===v.EXCLUDED?f:{...f,status:v.VALIDATION_FAILED,statusMessage:f.status===v.VALIDATION_FAILED?f.statusMessage:"Deployment failed due to validation errors in bundle"}));let d=e.length===0?u.filter(f=>f.status===v.READY):[],g=e.length===0;return{files:u,validFiles:d,errors:e,warnings:a,canDeploy:g}}function rt(i){return i.filter(r=>r.status===v.READY)}function pn(i){return rt(i).length>0}var ae=R(()=>{"use strict";b()});function _e(i,r){if(i.includes("\0")||i.includes("/../")||i.startsWith("../")||i.endsWith("/.."))throw h.business(`Security error: Unsafe file path "${i}" for file: ${r}`)}function $e(i,r){let e=se(i);if(!e.valid)throw h.business(e.reason||"Invalid file name");if(N(i))throw h.business(`File extension not allowed: "${r}"`)}var le=R(()=>{"use strict";b();ae()});var Le={};Ge(Le,{processFilesForBrowser:()=>Ne});async function Ne(i,r={}){if(M()!=="browser")throw h.business("processFilesForBrowser can only be called in a browser environment.");let e=i.map(m=>m.webkitRelativePath||m.name),a=new Set(Fe(e)),u=[];for(let m=0;m<i.length;m++)a.has(e[m])&&u.push({file:i[m],rawPath:e[m]});if(u.length===0)return[];let c=Oe(u.map(m=>m.rawPath),{flatten:r.pathDetect!==!1}),d=F(),g=[],f=0;for(let m=0;m<u.length;m++){let{file:y}=u[m],w=c[m].path;if(_e(w,y.name),y.size===0)continue;if($e(w,y.name),y.size>d.maxFileSize)throw h.business(`File ${y.name} is too large. Maximum allowed size is ${d.maxFileSize/(1024*1024)}MB.`);if(f+=y.size,f>d.maxTotalSize)throw h.business(`Total deploy size is too large. Maximum allowed is ${d.maxTotalSize/(1024*1024)}MB.`);let{md5:G}=await z(y);g.push({path:w,content:y,size:y.size,md5:G})}if(g.length>d.maxFilesCount)throw h.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return g}var pe=R(()=>{"use strict";H();b();k();ne();ie();le();P()});b();var B=class{constructor(){this.handlers=new Map}on(r,e){this.handlers.has(r)||this.handlers.set(r,new Set),this.handlers.get(r).add(e)}off(r,e){let a=this.handlers.get(r);a&&(a.delete(e),a.size===0&&this.handlers.delete(r))}emit(r,...e){let a=this.handlers.get(r);if(!a)return;let u=Array.from(a);for(let c of u)try{c(...e)}catch(d){a.delete(c),r!=="error"&&setTimeout(()=>{d instanceof Error?this.emit("error",d,String(r)):this.emit("error",new Error(String(d)),String(r))},0)}}transfer(r){this.handlers.forEach((e,a)=>{e.forEach(u=>{r.on(a,u)})})}clear(){this.handlers.clear()}};var S={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Ye=3e4,U=class extends B{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||L,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Ye,this.createDeployBody=e.createDeployBody}setGlobalHeaders(e){this.globalHeaders=e}transferEventsTo(e){this.transfer(e)}async executeRequest(e,a,u){let c=this.mergeHeaders(a.headers),{signal:d,cleanup:g}=this.createTimeoutSignal(a.signal),f={...a,headers:c,credentials:c.Authorization?void 0:"include",signal:d};this.emit("request",e,f);try{let m=await fetch(e,f);return g(),m.ok||await this.handleResponseError(m,u),this.emit("response",this.safeClone(m),e),{data:await this.parseResponse(this.safeClone(m)),status:m.status}}catch(m){g();let y=m instanceof Error?m:new Error(String(m));this.emit("error",y,e),this.handleFetchError(m,u)}}async request(e,a,u){let{data:c}=await this.executeRequest(e,a,u);return c}async requestWithStatus(e,a,u){return this.executeRequest(e,a,u)}mergeHeaders(e={}){return{...this.globalHeaders,...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let a=new AbortController,u=setTimeout(()=>a.abort(),this.timeout);if(e){let c=()=>a.abort();e.addEventListener("abort",c),e.aborted&&a.abort()}return{signal:a.signal,cleanup:()=>clearTimeout(u)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,a){let u={};try{if(e.headers.get("content-type")?.includes("application/json")){let g=await e.json();if(g&&typeof g=="object"){let f=g;typeof f.message=="string"&&(u.message=f.message),typeof f.error=="string"&&(u.error=f.error)}}else u={message:await e.text()}}catch{u={message:"Failed to parse error response"}}let c=u.message||u.error||`${a} failed`;throw e.status===401?h.authentication(c):h.api(c,e.status)}handleFetchError(e,a){throw J(e)?e:e instanceof Error&&e.name==="AbortError"?h.cancelled(`${a} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?h.network(`${a} failed: ${e.message}`,e):e instanceof Error?h.business(`${a} failed: ${e.message}`):h.business(`${a} failed: Unknown error`)}async deploy(e,a={}){if(!e.length)throw h.business("No files to deploy");for(let g of e)if(!g.md5)throw h.file(`MD5 checksum missing for file: ${g.path}`,g.path);let{body:u,headers:c}=await this.createDeployBody(e,a.labels,a.via),d={};return a.deployToken?d.Authorization=`Bearer ${a.deployToken}`:a.apiKey&&(d.Authorization=`Bearer ${a.apiKey}`),a.caller&&(d["X-Caller"]=a.caller),this.request(`${a.apiUrl||this.apiUrl}${S.DEPLOYMENTS}`,{method:"POST",body:u,headers:{...c,...d},signal:a.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,a){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:a})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,a,u){let c={};a&&(c.deployment=a),u!==void 0&&(c.labels=u);let{data:d,status:g}=await this.requestWithStatus(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)},"Set domain");return{...d,isCreate:g===201}}async listDomains(){return this.request(`${this.apiUrl}${S.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${S.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,a){let u={};return e!==void 0&&(u.ttl=e),a!==void 0&&(u.labels=a),this.request(`${this.apiUrl}${S.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${S.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${S.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${S.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${S.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${S.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e){let a=e.find(g=>g.path==="index.html"||g.path==="/index.html");if(!a||a.size>100*1024)return!1;let u;if(typeof Buffer<"u"&&Buffer.isBuffer(a.content))u=a.content.toString("utf-8");else if(typeof Blob<"u"&&a.content instanceof Blob)u=await a.content.text();else if(typeof File<"u"&&a.content instanceof File)u=await a.content.text();else return!1;let c={files:e.map(g=>g.path),index:u};return(await this.request(`${this.apiUrl}${S.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)},"SPA check")).isSPA}};b();P();b();b();function ye(i={},r={}){let e={apiUrl:i.apiUrl||r.apiUrl||L,apiKey:i.apiKey!==void 0?i.apiKey:r.apiKey,deployToken:i.deployToken!==void 0?i.deployToken:r.deployToken},a={apiUrl:e.apiUrl};return e.apiKey!==void 0&&(a.apiKey=e.apiKey),e.deployToken!==void 0&&(a.deployToken=e.deployToken),a}function ge(i,r){let e={...i};return e.apiUrl===void 0&&r.apiUrl!==void 0&&(e.apiUrl=r.apiUrl),e.apiKey===void 0&&r.apiKey!==void 0&&(e.apiKey=r.apiKey),e.deployToken===void 0&&r.deployToken!==void 0&&(e.deployToken=r.deployToken),e.timeout===void 0&&r.timeout!==void 0&&(e.timeout=r.timeout),e.maxConcurrency===void 0&&r.maxConcurrency!==void 0&&(e.maxConcurrency=r.maxConcurrency),e.onProgress===void 0&&r.onProgress!==void 0&&(e.onProgress=r.onProgress),e.caller===void 0&&r.caller!==void 0&&(e.caller=r.caller),e}b();H();async function Qe(){let r=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),e;typeof Buffer<"u"?e=Buffer.from(r,"utf-8"):e=new Blob([r],{type:"application/json"});let{md5:a}=await z(e);return{path:X,content:e,size:r.length,md5:a}}async function Ee(i,r,e){if(e.spaDetect===!1||i.some(a=>a.path===X))return i;try{if(await r.checkSPA(i)){let u=await Qe();return[...i,u]}}catch{}return i}function we(i){let{getApi:r,ensureInit:e,processInput:a,clientDefaults:u,hasAuth:c}=i;return{upload:async(d,g={})=>{await e();let f=u?ge(g,u):g;if(c&&!c()&&!f.deployToken&&!f.apiKey)throw h.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!a)throw h.config("processInput function is not provided.");let m=r(),y=await a(d,f);return y=await Ee(y,m,f),m.deploy(y,f)},list:async()=>(await e(),r().listDeployments()),get:async d=>(await e(),r().getDeployment(d)),set:async(d,g)=>(await e(),r().updateDeploymentLabels(d,g.labels)),remove:async d=>{await e(),await r().removeDeployment(d)}}}function be(i){let{getApi:r,ensureInit:e}=i;return{set:async(a,u={})=>(await e(),r().setDomain(a,u.deployment,u.labels)),list:async()=>(await e(),r().listDomains()),get:async a=>(await e(),r().getDomain(a)),remove:async a=>{await e(),await r().removeDomain(a)},verify:async a=>(await e(),r().verifyDomain(a)),validate:async a=>(await e(),r().validateDomain(a)),dns:async a=>(await e(),r().getDomainDns(a)),records:async a=>(await e(),r().getDomainRecords(a)),share:async a=>(await e(),r().getDomainShare(a))}}function Re(i){let{getApi:r,ensureInit:e}=i;return{get:async()=>(await e(),r().getAccount())}}function xe(i){let{getApi:r,ensureInit:e}=i;return{create:async(a={})=>(await e(),r().createToken(a.ttl,a.labels)),list:async()=>(await e(),r().listTokens()),remove:async a=>{await e(),await r().removeToken(a)}}}var K=class{constructor(r={}){this.initPromise=null;this._config=null;this.auth=null;this.customHeaders={};this.clientOptions=r,r.deployToken?this.auth={type:"token",value:r.deployToken}:r.apiKey&&(this.auth={type:"apiKey",value:r.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let e=this.resolveInitialConfig(r);this.http=new U({...r,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let a={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=we({...a,processInput:(u,c)=>this.processInput(u,c),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=be(a),this._account=Re(a),this._tokens=xe(a)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(r,e){return this.deployments.upload(r,e)}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=F(),this._config)}on(r,e){this.http.on(r,e)}off(r,e){this.http.off(r,e)}setHeaders(r){this.customHeaders=r,this.http.setGlobalHeaders(r)}clearHeaders(){this.customHeaders={},this.http.setGlobalHeaders({})}replaceHttpClient(r){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(r)}catch(e){console.warn("Event transfer failed during client replacement:",e)}this.http=r,Object.keys(this.customHeaders).length>0&&this.http.setGlobalHeaders(this.customHeaders)}setDeployToken(r){if(!r||typeof r!="string")throw h.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:r}}setApiKey(r){if(!r||typeof r!="string")throw h.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:r}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};P();b();b();async function Ce(i,r,e){let a=new FormData,u=[];for(let c of i){if(!(c.content instanceof File||c.content instanceof Blob))throw h.file(`Unsupported file.content type for browser: ${c.path}`,c.path);if(!c.md5)throw h.file(`File missing md5 checksum: ${c.path}`,c.path);let d=new File([c.content],c.path,{type:"application/octet-stream"});a.append("files[]",d),u.push(c.md5)}return a.append("checksums",JSON.stringify(u)),r&&r.length>0&&a.append("labels",JSON.stringify(r)),e&&a.append("via",e),{body:a,headers:{}}}H();function Qt(i,r,e,a=!0){let u=i===1?r:e;return a?`${i} ${u}`:u}ne();ie();k();ae();le();b();P();pe();var ue=class extends K{constructor(r={}){super(r)}resolveInitialConfig(r){return ye(r,{})}async loadFullConfig(){try{let r=await this.http.getConfig();Z(r)}catch(r){throw this.initPromise=null,r}}async processInput(r,e){if(!this.isFileArray(r))throw h.business("Invalid input type for browser environment. Expected File[].");if(r.length===0)throw h.business("No files to deploy.");let{processFilesForBrowser:a}=await Promise.resolve().then(()=>(pe(),Le));return a(r,e)}isFileArray(r){return Array.isArray(r)&&r.every(e=>e instanceof File)}getDeployBodyCreator(){return Ce}},kn=ue;export{Y as API_KEY_HEX_LENGTH,lt as API_KEY_HINT_LENGTH,T as API_KEY_PREFIX,he as API_KEY_TOTAL_LENGTH,at as AccountPlan,U as ApiHttp,pt as AuthMethod,je as BLOCKED_EXTENSIONS,L as DEFAULT_API,X as DEPLOYMENT_CONFIG_FILENAME,W as DEPLOY_TOKEN_HEX_LENGTH,I as DEPLOY_TOKEN_PREFIX,de as DEPLOY_TOKEN_TOTAL_LENGTH,ot as DeploymentStatus,st as DomainStatus,A as ErrorType,v as FILE_VALIDATION_STATUS,v as FileValidationStatus,tt as JUNK_DIRECTORIES,Dt as LABEL_CONSTRAINTS,At as LABEL_PATTERN,ue as Ship,h as ShipError,Ot as __setTestEnvironment,pn as allValidFilesReady,z as calculateMD5,Re as createAccountResource,we as createDeploymentResource,be as createDomainResource,xe as createTokenResource,kn as default,vt as deserializeLabels,mt as extractSubdomain,Fe as filterJunk,oe as formatFileSize,yt as generateDeploymentUrl,gt as generateDomainUrl,F as getCurrentConfig,M as getENV,rt as getValidFiles,N as isBlockedExtension,dt as isCustomDomain,ht as isDeployment,me as isPlatformDomain,J as isShipError,ge as mergeDeployOptions,Oe as optimizeDeployPaths,Qt as pluralize,Ne as processFilesForBrowser,ye as resolveConfig,St as serializeLabels,Z as setPlatformConfig,ut as validateApiKey,ft as validateApiUrl,$e as validateDeployFile,_e as validateDeployPath,ct as validateDeployToken,se as validateFileName,ln as validateFiles};
|
|
2
2
|
//# sourceMappingURL=browser.js.map
|