@shipstatic/ship 0.3.12 → 0.3.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.d.ts +64 -49
- package/dist/browser.js +3 -3
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +23 -22
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +64 -49
- package/dist/index.d.ts +64 -49
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +5 -4
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as _shipstatic_types from '@shipstatic/types';
|
|
2
|
-
import { PingResponse, ConfigResponse, StaticFile, Deployment, DeploymentListResponse, Domain, DomainListResponse, Account, TokenCreateResponse, TokenListResponse, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource,
|
|
2
|
+
import { ProgressInfo, PingResponse, ConfigResponse, StaticFile, Deployment, DeploymentListResponse, Domain, DomainListResponse, DomainDnsResponse, DomainRecordsResponse, Account, TokenCreateResponse, TokenListResponse, PlatformConfig, ResolvedConfig, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource, ValidatableFile, FileValidationResult, ShipError } from '@shipstatic/types';
|
|
3
3
|
export * from '@shipstatic/types';
|
|
4
|
-
export { Account, AccountResource, DEFAULT_API, DeployInput, Deployment, DeploymentResource, Domain, DomainResource, FileValidationStatus as FILE_VALIDATION_STATUS, PingResponse,
|
|
4
|
+
export { Account, AccountResource, DEFAULT_API, DeployInput, Deployment, DeploymentResource, Domain, DomainResource, ErrorType, FileValidationStatus as FILE_VALIDATION_STATUS, PingResponse, ResolvedConfig, ShipError, StaticFile, TokenResource } from '@shipstatic/types';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* @file SDK-specific type definitions
|
|
@@ -43,20 +43,6 @@ interface DeploymentOptions {
|
|
|
43
43
|
* Derived from DeploymentOptions but excludes client-side only options.
|
|
44
44
|
*/
|
|
45
45
|
type ApiDeployOptions = Omit<DeploymentOptions, 'pathDetect'>;
|
|
46
|
-
/**
|
|
47
|
-
* Progress information for deploy operations.
|
|
48
|
-
* Provides consistent percentage-based progress with byte-level details.
|
|
49
|
-
*/
|
|
50
|
-
interface ProgressInfo {
|
|
51
|
-
/** Progress percentage (0-100). */
|
|
52
|
-
percent: number;
|
|
53
|
-
/** Number of bytes loaded so far. */
|
|
54
|
-
loaded: number;
|
|
55
|
-
/** Total number of bytes to be loaded. May be 0 if unknown initially. */
|
|
56
|
-
total: number;
|
|
57
|
-
/** Current file being processed (optional). */
|
|
58
|
-
file?: string;
|
|
59
|
-
}
|
|
60
46
|
/**
|
|
61
47
|
* Options for configuring a `Ship` instance.
|
|
62
48
|
* Sets default API host, authentication credentials, progress callbacks, concurrency, and timeouts for the client.
|
|
@@ -163,6 +149,7 @@ declare class SimpleEvents {
|
|
|
163
149
|
declare class ApiHttp extends SimpleEvents {
|
|
164
150
|
private readonly apiUrl;
|
|
165
151
|
private readonly getAuthHeadersCallback;
|
|
152
|
+
private readonly timeout;
|
|
166
153
|
constructor(options: ShipClientOptions & {
|
|
167
154
|
getAuthHeaders: () => Record<string, string>;
|
|
168
155
|
});
|
|
@@ -171,9 +158,18 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
171
158
|
*/
|
|
172
159
|
transferEventsTo(target: ApiHttp): void;
|
|
173
160
|
/**
|
|
174
|
-
* Make authenticated HTTP request with events
|
|
161
|
+
* Make authenticated HTTP request with events and timeout
|
|
175
162
|
*/
|
|
176
163
|
private request;
|
|
164
|
+
/**
|
|
165
|
+
* Combine multiple AbortSignals into one
|
|
166
|
+
*/
|
|
167
|
+
private combineSignals;
|
|
168
|
+
/**
|
|
169
|
+
* Make request and return both data and HTTP status code
|
|
170
|
+
* Used when the caller needs to inspect the status (e.g., 201 vs 200)
|
|
171
|
+
*/
|
|
172
|
+
private requestWithStatus;
|
|
177
173
|
/**
|
|
178
174
|
* Generate auth headers from Ship instance callback
|
|
179
175
|
*/
|
|
@@ -208,14 +204,8 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
208
204
|
confirmDomain(name: string): Promise<{
|
|
209
205
|
message: string;
|
|
210
206
|
}>;
|
|
211
|
-
getDomainDns(name: string): Promise<
|
|
212
|
-
|
|
213
|
-
dns: any;
|
|
214
|
-
}>;
|
|
215
|
-
getDomainRecords(name: string): Promise<{
|
|
216
|
-
domain: string;
|
|
217
|
-
records: any[];
|
|
218
|
-
}>;
|
|
207
|
+
getDomainDns(name: string): Promise<DomainDnsResponse>;
|
|
208
|
+
getDomainRecords(name: string): Promise<DomainRecordsResponse>;
|
|
219
209
|
getDomainShare(name: string): Promise<{
|
|
220
210
|
domain: string;
|
|
221
211
|
hash: string;
|
|
@@ -232,6 +222,31 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
232
222
|
private getBrowserContentType;
|
|
233
223
|
}
|
|
234
224
|
|
|
225
|
+
/**
|
|
226
|
+
* @file Shared configuration logic for both environments.
|
|
227
|
+
*
|
|
228
|
+
* CONFIGURATION PRECEDENCE (highest to lowest):
|
|
229
|
+
* 1. Constructor options / CLI flags (passed directly to Ship())
|
|
230
|
+
* 2. Environment variables (SHIP_API_KEY, SHIP_DEPLOY_TOKEN, SHIP_API_URL)
|
|
231
|
+
* 3. Config file (.shiprc or package.json "ship" key)
|
|
232
|
+
* 4. Default values (DEFAULT_API)
|
|
233
|
+
*
|
|
234
|
+
* This means CLI flags always win, followed by env vars, then config files.
|
|
235
|
+
*/
|
|
236
|
+
|
|
237
|
+
type Config = PlatformConfig;
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Universal configuration resolver for all environments.
|
|
241
|
+
* This is the single source of truth for config resolution.
|
|
242
|
+
*/
|
|
243
|
+
declare function resolveConfig(userOptions?: ShipClientOptions, loadedConfig?: Partial<ShipClientOptions>): ResolvedConfig;
|
|
244
|
+
/**
|
|
245
|
+
* Merge deployment options with client defaults.
|
|
246
|
+
* This is shared logic used by both environments.
|
|
247
|
+
*/
|
|
248
|
+
declare function mergeDeployOptions(options: DeploymentOptions, clientDefaults: ShipClientOptions): DeploymentOptions;
|
|
249
|
+
|
|
235
250
|
/**
|
|
236
251
|
* @file Ship SDK resource implementations for deployments, domains, and accounts.
|
|
237
252
|
*/
|
|
@@ -253,13 +268,13 @@ declare abstract class Ship$1 {
|
|
|
253
268
|
protected initPromise: Promise<void> | null;
|
|
254
269
|
protected _config: ConfigResponse | null;
|
|
255
270
|
private auth;
|
|
256
|
-
|
|
271
|
+
protected readonly authHeadersCallback: () => Record<string, string>;
|
|
257
272
|
protected _deployments: DeploymentResource;
|
|
258
273
|
protected _domains: DomainResource;
|
|
259
274
|
protected _account: AccountResource;
|
|
260
275
|
protected _tokens: TokenResource;
|
|
261
276
|
constructor(options?: ShipClientOptions);
|
|
262
|
-
protected abstract resolveInitialConfig(options: ShipClientOptions):
|
|
277
|
+
protected abstract resolveInitialConfig(options: ShipClientOptions): ResolvedConfig;
|
|
263
278
|
protected abstract loadFullConfig(): Promise<void>;
|
|
264
279
|
protected abstract processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
|
|
265
280
|
/**
|
|
@@ -343,26 +358,6 @@ declare abstract class Ship$1 {
|
|
|
343
358
|
private hasAuth;
|
|
344
359
|
}
|
|
345
360
|
|
|
346
|
-
/**
|
|
347
|
-
* @file Shared configuration logic for both environments.
|
|
348
|
-
*/
|
|
349
|
-
|
|
350
|
-
type Config = PlatformConfig;
|
|
351
|
-
/**
|
|
352
|
-
* Universal configuration resolver for all environments.
|
|
353
|
-
* This is the single source of truth for config resolution.
|
|
354
|
-
*/
|
|
355
|
-
declare function resolveConfig(userOptions?: ShipClientOptions, loadedConfig?: Partial<ShipClientOptions>): {
|
|
356
|
-
apiUrl: string;
|
|
357
|
-
apiKey?: string;
|
|
358
|
-
deployToken?: string;
|
|
359
|
-
};
|
|
360
|
-
/**
|
|
361
|
-
* Merge deployment options with client defaults.
|
|
362
|
-
* This is shared logic used by both environments.
|
|
363
|
-
*/
|
|
364
|
-
declare function mergeDeployOptions(options: DeploymentOptions, clientDefaults: ShipClientOptions): DeploymentOptions;
|
|
365
|
-
|
|
366
361
|
interface MD5Result {
|
|
367
362
|
md5: string;
|
|
368
363
|
}
|
|
@@ -540,6 +535,26 @@ declare function getValidFiles<T extends ValidatableFile>(files: T[]): T[];
|
|
|
540
535
|
*/
|
|
541
536
|
declare function allValidFilesReady<T extends ValidatableFile>(files: T[]): boolean;
|
|
542
537
|
|
|
538
|
+
/**
|
|
539
|
+
* @file Error utilities for consistent error handling across SDK consumers.
|
|
540
|
+
*/
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Ensure any error is wrapped as a ShipError.
|
|
544
|
+
* Useful for catch blocks where the error type is unknown.
|
|
545
|
+
*
|
|
546
|
+
* @example
|
|
547
|
+
* ```ts
|
|
548
|
+
* try {
|
|
549
|
+
* await someOperation();
|
|
550
|
+
* } catch (err) {
|
|
551
|
+
* const shipError = ensureShipError(err);
|
|
552
|
+
* // Now you can safely use shipError.message, shipError.type, etc.
|
|
553
|
+
* }
|
|
554
|
+
* ```
|
|
555
|
+
*/
|
|
556
|
+
declare function ensureShipError(err: unknown): ShipError;
|
|
557
|
+
|
|
543
558
|
/**
|
|
544
559
|
* @file Manages loading and validation of client configuration.
|
|
545
560
|
* This module uses `cosmiconfig` to find and load configuration from various
|
|
@@ -609,9 +624,9 @@ declare function processFilesForNode(paths: string[], options?: DeploymentOption
|
|
|
609
624
|
declare class Ship extends Ship$1 {
|
|
610
625
|
#private;
|
|
611
626
|
constructor(options?: ShipClientOptions);
|
|
612
|
-
protected resolveInitialConfig(options: ShipClientOptions):
|
|
627
|
+
protected resolveInitialConfig(options: ShipClientOptions): ResolvedConfig;
|
|
613
628
|
protected loadFullConfig(): Promise<void>;
|
|
614
629
|
protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
|
|
615
630
|
}
|
|
616
631
|
|
|
617
|
-
export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result,
|
|
632
|
+
export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, ensureShipError, filterJunk, formatFileSize, getCurrentConfig, getENV, getValidFiles, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig, setConfig as setPlatformConfig, validateFiles };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as _shipstatic_types from '@shipstatic/types';
|
|
2
|
-
import { PingResponse, ConfigResponse, StaticFile, Deployment, DeploymentListResponse, Domain, DomainListResponse, Account, TokenCreateResponse, TokenListResponse, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource,
|
|
2
|
+
import { ProgressInfo, PingResponse, ConfigResponse, StaticFile, Deployment, DeploymentListResponse, Domain, DomainListResponse, DomainDnsResponse, DomainRecordsResponse, Account, TokenCreateResponse, TokenListResponse, PlatformConfig, ResolvedConfig, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource, ValidatableFile, FileValidationResult, ShipError } from '@shipstatic/types';
|
|
3
3
|
export * from '@shipstatic/types';
|
|
4
|
-
export { Account, AccountResource, DEFAULT_API, DeployInput, Deployment, DeploymentResource, Domain, DomainResource, FileValidationStatus as FILE_VALIDATION_STATUS, PingResponse,
|
|
4
|
+
export { Account, AccountResource, DEFAULT_API, DeployInput, Deployment, DeploymentResource, Domain, DomainResource, ErrorType, FileValidationStatus as FILE_VALIDATION_STATUS, PingResponse, ResolvedConfig, ShipError, StaticFile, TokenResource } from '@shipstatic/types';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* @file SDK-specific type definitions
|
|
@@ -43,20 +43,6 @@ interface DeploymentOptions {
|
|
|
43
43
|
* Derived from DeploymentOptions but excludes client-side only options.
|
|
44
44
|
*/
|
|
45
45
|
type ApiDeployOptions = Omit<DeploymentOptions, 'pathDetect'>;
|
|
46
|
-
/**
|
|
47
|
-
* Progress information for deploy operations.
|
|
48
|
-
* Provides consistent percentage-based progress with byte-level details.
|
|
49
|
-
*/
|
|
50
|
-
interface ProgressInfo {
|
|
51
|
-
/** Progress percentage (0-100). */
|
|
52
|
-
percent: number;
|
|
53
|
-
/** Number of bytes loaded so far. */
|
|
54
|
-
loaded: number;
|
|
55
|
-
/** Total number of bytes to be loaded. May be 0 if unknown initially. */
|
|
56
|
-
total: number;
|
|
57
|
-
/** Current file being processed (optional). */
|
|
58
|
-
file?: string;
|
|
59
|
-
}
|
|
60
46
|
/**
|
|
61
47
|
* Options for configuring a `Ship` instance.
|
|
62
48
|
* Sets default API host, authentication credentials, progress callbacks, concurrency, and timeouts for the client.
|
|
@@ -163,6 +149,7 @@ declare class SimpleEvents {
|
|
|
163
149
|
declare class ApiHttp extends SimpleEvents {
|
|
164
150
|
private readonly apiUrl;
|
|
165
151
|
private readonly getAuthHeadersCallback;
|
|
152
|
+
private readonly timeout;
|
|
166
153
|
constructor(options: ShipClientOptions & {
|
|
167
154
|
getAuthHeaders: () => Record<string, string>;
|
|
168
155
|
});
|
|
@@ -171,9 +158,18 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
171
158
|
*/
|
|
172
159
|
transferEventsTo(target: ApiHttp): void;
|
|
173
160
|
/**
|
|
174
|
-
* Make authenticated HTTP request with events
|
|
161
|
+
* Make authenticated HTTP request with events and timeout
|
|
175
162
|
*/
|
|
176
163
|
private request;
|
|
164
|
+
/**
|
|
165
|
+
* Combine multiple AbortSignals into one
|
|
166
|
+
*/
|
|
167
|
+
private combineSignals;
|
|
168
|
+
/**
|
|
169
|
+
* Make request and return both data and HTTP status code
|
|
170
|
+
* Used when the caller needs to inspect the status (e.g., 201 vs 200)
|
|
171
|
+
*/
|
|
172
|
+
private requestWithStatus;
|
|
177
173
|
/**
|
|
178
174
|
* Generate auth headers from Ship instance callback
|
|
179
175
|
*/
|
|
@@ -208,14 +204,8 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
208
204
|
confirmDomain(name: string): Promise<{
|
|
209
205
|
message: string;
|
|
210
206
|
}>;
|
|
211
|
-
getDomainDns(name: string): Promise<
|
|
212
|
-
|
|
213
|
-
dns: any;
|
|
214
|
-
}>;
|
|
215
|
-
getDomainRecords(name: string): Promise<{
|
|
216
|
-
domain: string;
|
|
217
|
-
records: any[];
|
|
218
|
-
}>;
|
|
207
|
+
getDomainDns(name: string): Promise<DomainDnsResponse>;
|
|
208
|
+
getDomainRecords(name: string): Promise<DomainRecordsResponse>;
|
|
219
209
|
getDomainShare(name: string): Promise<{
|
|
220
210
|
domain: string;
|
|
221
211
|
hash: string;
|
|
@@ -232,6 +222,31 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
232
222
|
private getBrowserContentType;
|
|
233
223
|
}
|
|
234
224
|
|
|
225
|
+
/**
|
|
226
|
+
* @file Shared configuration logic for both environments.
|
|
227
|
+
*
|
|
228
|
+
* CONFIGURATION PRECEDENCE (highest to lowest):
|
|
229
|
+
* 1. Constructor options / CLI flags (passed directly to Ship())
|
|
230
|
+
* 2. Environment variables (SHIP_API_KEY, SHIP_DEPLOY_TOKEN, SHIP_API_URL)
|
|
231
|
+
* 3. Config file (.shiprc or package.json "ship" key)
|
|
232
|
+
* 4. Default values (DEFAULT_API)
|
|
233
|
+
*
|
|
234
|
+
* This means CLI flags always win, followed by env vars, then config files.
|
|
235
|
+
*/
|
|
236
|
+
|
|
237
|
+
type Config = PlatformConfig;
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Universal configuration resolver for all environments.
|
|
241
|
+
* This is the single source of truth for config resolution.
|
|
242
|
+
*/
|
|
243
|
+
declare function resolveConfig(userOptions?: ShipClientOptions, loadedConfig?: Partial<ShipClientOptions>): ResolvedConfig;
|
|
244
|
+
/**
|
|
245
|
+
* Merge deployment options with client defaults.
|
|
246
|
+
* This is shared logic used by both environments.
|
|
247
|
+
*/
|
|
248
|
+
declare function mergeDeployOptions(options: DeploymentOptions, clientDefaults: ShipClientOptions): DeploymentOptions;
|
|
249
|
+
|
|
235
250
|
/**
|
|
236
251
|
* @file Ship SDK resource implementations for deployments, domains, and accounts.
|
|
237
252
|
*/
|
|
@@ -253,13 +268,13 @@ declare abstract class Ship$1 {
|
|
|
253
268
|
protected initPromise: Promise<void> | null;
|
|
254
269
|
protected _config: ConfigResponse | null;
|
|
255
270
|
private auth;
|
|
256
|
-
|
|
271
|
+
protected readonly authHeadersCallback: () => Record<string, string>;
|
|
257
272
|
protected _deployments: DeploymentResource;
|
|
258
273
|
protected _domains: DomainResource;
|
|
259
274
|
protected _account: AccountResource;
|
|
260
275
|
protected _tokens: TokenResource;
|
|
261
276
|
constructor(options?: ShipClientOptions);
|
|
262
|
-
protected abstract resolveInitialConfig(options: ShipClientOptions):
|
|
277
|
+
protected abstract resolveInitialConfig(options: ShipClientOptions): ResolvedConfig;
|
|
263
278
|
protected abstract loadFullConfig(): Promise<void>;
|
|
264
279
|
protected abstract processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
|
|
265
280
|
/**
|
|
@@ -343,26 +358,6 @@ declare abstract class Ship$1 {
|
|
|
343
358
|
private hasAuth;
|
|
344
359
|
}
|
|
345
360
|
|
|
346
|
-
/**
|
|
347
|
-
* @file Shared configuration logic for both environments.
|
|
348
|
-
*/
|
|
349
|
-
|
|
350
|
-
type Config = PlatformConfig;
|
|
351
|
-
/**
|
|
352
|
-
* Universal configuration resolver for all environments.
|
|
353
|
-
* This is the single source of truth for config resolution.
|
|
354
|
-
*/
|
|
355
|
-
declare function resolveConfig(userOptions?: ShipClientOptions, loadedConfig?: Partial<ShipClientOptions>): {
|
|
356
|
-
apiUrl: string;
|
|
357
|
-
apiKey?: string;
|
|
358
|
-
deployToken?: string;
|
|
359
|
-
};
|
|
360
|
-
/**
|
|
361
|
-
* Merge deployment options with client defaults.
|
|
362
|
-
* This is shared logic used by both environments.
|
|
363
|
-
*/
|
|
364
|
-
declare function mergeDeployOptions(options: DeploymentOptions, clientDefaults: ShipClientOptions): DeploymentOptions;
|
|
365
|
-
|
|
366
361
|
interface MD5Result {
|
|
367
362
|
md5: string;
|
|
368
363
|
}
|
|
@@ -540,6 +535,26 @@ declare function getValidFiles<T extends ValidatableFile>(files: T[]): T[];
|
|
|
540
535
|
*/
|
|
541
536
|
declare function allValidFilesReady<T extends ValidatableFile>(files: T[]): boolean;
|
|
542
537
|
|
|
538
|
+
/**
|
|
539
|
+
* @file Error utilities for consistent error handling across SDK consumers.
|
|
540
|
+
*/
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Ensure any error is wrapped as a ShipError.
|
|
544
|
+
* Useful for catch blocks where the error type is unknown.
|
|
545
|
+
*
|
|
546
|
+
* @example
|
|
547
|
+
* ```ts
|
|
548
|
+
* try {
|
|
549
|
+
* await someOperation();
|
|
550
|
+
* } catch (err) {
|
|
551
|
+
* const shipError = ensureShipError(err);
|
|
552
|
+
* // Now you can safely use shipError.message, shipError.type, etc.
|
|
553
|
+
* }
|
|
554
|
+
* ```
|
|
555
|
+
*/
|
|
556
|
+
declare function ensureShipError(err: unknown): ShipError;
|
|
557
|
+
|
|
543
558
|
/**
|
|
544
559
|
* @file Manages loading and validation of client configuration.
|
|
545
560
|
* This module uses `cosmiconfig` to find and load configuration from various
|
|
@@ -609,9 +624,9 @@ declare function processFilesForNode(paths: string[], options?: DeploymentOption
|
|
|
609
624
|
declare class Ship extends Ship$1 {
|
|
610
625
|
#private;
|
|
611
626
|
constructor(options?: ShipClientOptions);
|
|
612
|
-
protected resolveInitialConfig(options: ShipClientOptions):
|
|
627
|
+
protected resolveInitialConfig(options: ShipClientOptions): ResolvedConfig;
|
|
613
628
|
protected loadFullConfig(): Promise<void>;
|
|
614
629
|
protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
|
|
615
630
|
}
|
|
616
631
|
|
|
617
|
-
export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result,
|
|
632
|
+
export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, ensureShipError, filterJunk, formatFileSize, getCurrentConfig, getENV, getValidFiles, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig, setConfig as setPlatformConfig, validateFiles };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Ae=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var Qe=Object.prototype.hasOwnProperty;var x=(n,e)=>()=>(n&&(e=n(n=0)),e);var M=(n,e)=>{for(var t in e)Ae(n,t,{get:e[t],enumerable:!0})},Re=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ze(e))!Qe.call(n,s)&&s!==t&&Ae(n,s,{get:()=>e[s],enumerable:!(i=Xe(e,s))||i.enumerable});return n},p=(n,e,t)=>(Re(n,e,"default"),t&&Re(t,e,"default"));var $e={};M($e,{__setTestEnvironment:()=>q,getENV:()=>y});function q(n){fe=n}function et(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function y(){return fe||et()}var fe,F=x(()=>{"use strict";fe=null});import{ShipError as st}from"@shipstatic/types";function z(n){ue=n}function A(){if(ue===null)throw st.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ue}var ue,I=x(()=>{"use strict";ue=null});var Oe={};M(Oe,{loadConfig:()=>U});import{z as H}from"zod";import{ShipError as he}from"@shipstatic/types";function ke(n){try{return rt.parse(n)}catch(e){if(e instanceof H.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw he.config(`Configuration validation failed${i}: ${t.message}`)}throw he.config("Configuration validation failed")}}async function at(n){try{if(y()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(de,{searchPlaces:[`.${de}rc`,"package.json",`${t.homedir()}/.${de}rc`],stopDir:t.homedir()}),s;if(n?s=i.load(n):s=i.search(),s&&s.config)return ke(s.config)}catch(e){if(e instanceof he)throw e}return{}}async function U(n){if(y()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await at(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return ke(i)}var de,rt,ie=x(()=>{"use strict";F();de="ship",rt=H.object({apiUrl:H.string().url().optional(),apiKey:H.string().optional(),deployToken:H.string().optional()}).strict()});import{ShipError as _}from"@shipstatic/types";async function ct(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let o=Math.ceil(n.size/2097152),r=0,a=new e.ArrayBuffer,f=new FileReader,g=()=>{let w=r*2097152,l=Math.min(w+2097152,n.size);f.readAsArrayBuffer(n.slice(w,l))};f.onload=w=>{let l=w.target?.result;if(!l){i(_.business("Failed to read file chunk"));return}a.append(l),r++,r<o?g():t({md5:a.end()})},f.onerror=()=>{i(_.business("Failed to calculate MD5: FileReader error"))},g()})}async function ft(n){let e=await import("crypto");if(Buffer.isBuffer(n)){let i=e.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let t=await import("fs");return new Promise((i,s)=>{let o=e.createHash("md5"),r=t.createReadStream(n);r.on("error",a=>s(_.business(`Failed to read file for MD5: ${a.message}`))),r.on("data",a=>o.update(a)),r.on("end",()=>i({md5:o.digest("hex")}))})}async function b(n){let e=y();if(e==="browser"){if(!(n instanceof Blob))throw _.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return ct(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw _.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return ft(n)}throw _.business("Unknown or unsupported execution environment for MD5 calculation.")}var j=x(()=>{"use strict";F()});import{isJunk as ut}from"junk";function k(n){return!n||n.length===0?[]:n.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let i=t[t.length-1];if(ut(i))return!1;let s=t.slice(0,-1);for(let o of s)if(oe.some(r=>o.toLowerCase()===r.toLowerCase()))return!1;return!0})}var oe,se=x(()=>{"use strict";oe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ue(n){if(!n||n.length===0)return"";let e=n.filter(o=>o&&typeof o=="string").map(o=>o.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(o=>o.split("/").filter(Boolean)),i=[],s=Math.min(...t.map(o=>o.length));for(let o=0;o<s;o++){let r=t[0][o];if(t.every(a=>a[o]===r))i.push(r);else break}return i.join("/")}function re(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ve=x(()=>{"use strict"});function O(n,e={}){if(e.flatten===!1)return n.map(i=>({path:re(i),name:we(i)}));let t=dt(n);return n.map(i=>{let s=re(i);if(t){let o=t.endsWith("/")?t:`${t}/`;s.startsWith(o)&&(s=s.substring(o.length))}return s||(s=we(i)),{path:s,name:we(i)}})}function dt(n){if(!n.length)return"";let t=n.map(o=>re(o)).map(o=>o.split("/")),i=[],s=Math.min(...t.map(o=>o.length));for(let o=0;o<s-1;o++){let r=t[0][o];if(t.every(a=>a[o]===r))i.push(r);else break}return i.join("/")}function we(n){return n.split(/[/\\]/).pop()||n}var ae=x(()=>{"use strict";ve()});import{ShipError as N}from"@shipstatic/types";import*as $ from"fs";import*as D from"path";function _e(n){let e=[];try{let t=$.readdirSync(n);for(let i of t){let s=D.join(n,i),o=$.statSync(s);if(o.isDirectory()){let r=_e(s);e.push(...r)}else o.isFile()&&e.push(s)}}catch(t){console.error(`Error reading directory ${n}:`,t)}return e}async function X(n,e={}){if(y()!=="node")throw N.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(m=>{let u=D.resolve(m);try{return $.statSync(u).isDirectory()?_e(u):[u]}catch{throw N.file(`Path does not exist: ${m}`,m)}}),i=[...new Set(t)],s=k(i);if(s.length===0)return[];let o=n.map(m=>D.resolve(m)),r=Ue(o.map(m=>{try{return $.statSync(m).isDirectory()?m:D.dirname(m)}catch{return D.dirname(m)}})),a=s.map(m=>{if(r&&r.length>0){let u=D.relative(r,m);if(u&&typeof u=="string"&&!u.startsWith(".."))return u.replace(/\\/g,"/")}return D.basename(m)}),f=O(a,{flatten:e.pathDetect!==!1}),g=[],w=0,l=A();for(let m=0;m<s.length;m++){let u=s[m],P=f[m].path;try{let T=$.statSync(u);if(T.size===0){console.warn(`Skipping empty file: ${u}`);continue}if(T.size>l.maxFileSize)throw N.business(`File ${u} is too large. Maximum allowed size is ${l.maxFileSize/(1024*1024)}MB.`);if(w+=T.size,w>l.maxTotalSize)throw N.business(`Total deploy size is too large. Maximum allowed is ${l.maxTotalSize/(1024*1024)}MB.`);let pe=$.readFileSync(u),{md5:Ye}=await b(pe);if(P.includes("\0")||P.includes("/../")||P.startsWith("../")||P.endsWith("/.."))throw N.business(`Security error: Unsafe file path "${P}" for file: ${u}`);g.push({path:P,content:pe,size:pe.length,md5:Ye})}catch(T){if(T instanceof N&&T.isClientError&&T.isClientError())throw T;console.error(`Could not process file ${u}:`,T)}}if(g.length>l.maxFilesCount)throw N.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return g}var Ce=x(()=>{"use strict";F();j();se();I();ae();ve()});import{ShipError as Le}from"@shipstatic/types";async function Ke(n,e={}){let{getENV:t}=await Promise.resolve().then(()=>(F(),$e));if(t()!=="browser")throw Le.business("processFilesForBrowser can only be called in a browser environment.");let i=n,s=i.map(l=>l.webkitRelativePath||l.name),o=O(s,{flatten:e.pathDetect!==!1}),r=[];for(let l=0;l<i.length;l++){let m=i[l],u=o[l].path;if(u.includes("..")||u.includes("\0"))throw Le.business(`Security error: Unsafe file path "${u}" for file: ${m.name}`);r.push({file:m,relativePath:u})}let a=r.map(l=>l.relativePath),f=k(a),g=new Set(f),w=[];for(let l of r){if(!g.has(l.relativePath))continue;let{md5:m}=await b(l.file);w.push({content:l.file,path:l.relativePath,size:l.file.size,md5:m})}return w}var qe=x(()=>{"use strict";j();se();ae()});var We={};M(We,{convertBrowserInput:()=>Ge,convertDeployInput:()=>wt,convertNodeInput:()=>Pe});import{ShipError as C}from"@shipstatic/types";function He(n,e={}){let t=A();if(!e.skipEmptyCheck&&n.length===0)throw C.business("No files to deploy.");if(n.length>t.maxFilesCount)throw C.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let i=0;for(let s of n){if(s.size>t.maxFileSize)throw C.business(`File ${s.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(i+=s.size,i>t.maxTotalSize)throw C.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Ve(n,e){if(e==="node"){if(!Array.isArray(n))throw C.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(n.length===0)throw C.business("No files to deploy.");if(!n.every(t=>typeof t=="string"))throw C.business("Invalid input type for Node.js environment. Expected string[] file paths.")}}function je(n){let e=n.map(t=>({name:t.path,size:t.size}));return He(e,{skipEmptyCheck:!0}),n.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),n}async function Pe(n,e={}){Ve(n,"node");let t=await X(n,e);return je(t)}async function Ge(n,e={}){Ve(n,"browser");let t;if(Array.isArray(n)){if(n.length>0&&typeof n[0]=="string")throw C.business("Invalid input type for browser environment. Expected File[].");t=n}else throw C.business("Invalid input type for browser environment. Expected File[].");t=t.filter(s=>s.size===0?(console.warn(`Skipping empty file: ${s.name}`),!1):!0),He(t);let i=await Ke(t,e);return je(i)}async function wt(n,e={},t){let i=y();if(i!=="node"&&i!=="browser")throw C.business("Unsupported execution environment.");let s;if(i==="node")if(typeof n=="string")s=await Pe([n],e);else if(Array.isArray(n)&&n.every(o=>typeof o=="string"))s=await Pe(n,e);else throw C.business("Invalid input type for Node.js environment. Expected string[] file paths.");else s=await Ge(n,e);return s}var Je=x(()=>{"use strict";F();Ce();qe();I()});var Q={};M(Q,{ApiHttp:()=>R,DEFAULT_API:()=>ye,FILE_VALIDATION_STATUS:()=>d,JUNK_DIRECTORIES:()=>oe,Ship:()=>Z,ShipError:()=>Se,ShipErrorType:()=>Ee,__setTestEnvironment:()=>q,allValidFilesReady:()=>Fe,calculateMD5:()=>b,createAccountResource:()=>J,createDeploymentResource:()=>G,createDomainResource:()=>W,createTokenResource:()=>Y,default:()=>Te,filterJunk:()=>k,formatFileSize:()=>K,getCurrentConfig:()=>A,getENV:()=>y,getValidFiles:()=>le,loadConfig:()=>U,mergeDeployOptions:()=>V,optimizeDeployPaths:()=>O,pluralize:()=>ge,processFilesForNode:()=>X,resolveConfig:()=>B,setConfig:()=>z,setPlatformConfig:()=>z,validateFiles:()=>De});var h={};M(h,{ApiHttp:()=>R,DEFAULT_API:()=>ye,FILE_VALIDATION_STATUS:()=>d,JUNK_DIRECTORIES:()=>oe,Ship:()=>Z,ShipError:()=>Se,ShipErrorType:()=>Ee,__setTestEnvironment:()=>q,allValidFilesReady:()=>Fe,calculateMD5:()=>b,createAccountResource:()=>J,createDeploymentResource:()=>G,createDomainResource:()=>W,createTokenResource:()=>Y,default:()=>Te,filterJunk:()=>k,formatFileSize:()=>K,getCurrentConfig:()=>A,getENV:()=>y,getValidFiles:()=>le,loadConfig:()=>U,mergeDeployOptions:()=>V,optimizeDeployPaths:()=>O,pluralize:()=>ge,processFilesForNode:()=>X,resolveConfig:()=>B,setConfig:()=>z,setPlatformConfig:()=>z,validateFiles:()=>De});import be from"mime-db";var ce={};for(let n in be){let e=be[n];e&&e.extensions&&e.extensions.forEach(t=>{ce[t]||(ce[t]=n)})}function ee(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return ce[e]||"application/octet-stream"}import{ShipError as S,DEFAULT_API as tt}from"@shipstatic/types";var te=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 i=this.handlers.get(e);i&&(i.delete(t),i.size===0&&this.handlers.delete(e))}emit(e,...t){let i=this.handlers.get(e);if(!i)return;let s=Array.from(i);for(let o of s)try{o(...t)}catch(r){i.delete(o),e!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(e)):this.emit("error",new Error(String(r)),String(e))},0)}}transfer(e){this.handlers.forEach((t,i)=>{t.forEach(s=>{e.on(i,s)})})}clear(){this.handlers.clear()}};F();var ne="/deployments",Ie="/ping",E="/domains",nt="/config",it="/account",me="/tokens",ot="/spa-check",R=class extends te{constructor(e){super(),this.apiUrl=e.apiUrl||tt,this.getAuthHeadersCallback=e.getAuthHeaders}transferEventsTo(e){this.transfer(e)}async request(e,t={},i){let s=this.getAuthHeaders(t.headers),o={...t,headers:s,credentials:s.Authorization?void 0:"include"};this.emit("request",e,o);try{let r=await fetch(e,o);r.ok||await this.handleResponseError(r,i);let a=this.safeClone(r),f=this.safeClone(r);return this.emit("response",a,e),await this.parseResponse(f)}catch(r){throw this.emit("error",r,e),this.handleFetchError(r,i),r}}getAuthHeaders(e={}){let t=this.getAuthHeadersCallback();return{...e,...t}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return await e.json()}async handleResponseError(e,t){let i={};try{e.headers.get("content-type")?.includes("application/json")?i=await e.json():i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let s=i.message||i.error||`${t} failed due to API error`;throw e.status===401?S.authentication(s):S.api(s,e.status,i.code,i)}handleFetchError(e,t){throw e.name==="AbortError"?S.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?S.network(`${t} failed due to network error: ${e.message}`,e):e instanceof S?e:S.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${Ie}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${Ie}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${nt}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:i,requestHeaders:s}=await this.prepareRequestPayload(e,t.tags),o={};t.deployToken?o={Authorization:`Bearer ${t.deployToken}`}:t.apiKey&&(o={Authorization:`Bearer ${t.apiKey}`});let r={method:"POST",body:i,headers:{...s,...o},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${ne}`,r,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${ne}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${ne}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${ne}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,t,i){let s={};t&&(s.deployment=t),i&&i.length>0&&(s.tags=i);let o={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},r=this.getAuthHeaders(o.headers),a={...o,headers:r,credentials:r.Authorization?void 0:"include"};this.emit("request",`${this.apiUrl}${E}/${encodeURIComponent(e)}`,a);try{let f=await fetch(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,a);f.ok||await this.handleResponseError(f,"Set Domain");let g=this.safeClone(f),w=this.safeClone(f);return this.emit("response",g,`${this.apiUrl}${E}/${encodeURIComponent(e)}`),{...await this.parseResponse(w),isCreate:f.status===201}}catch(f){throw this.emit("error",f,`${this.apiUrl}${E}/${encodeURIComponent(e)}`),this.handleFetchError(f,"Set Domain"),f}}async getDomain(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${E}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async confirmDomain(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${it}`,{method:"GET"},"Get Account")}async createToken(e,t){let i={};return e!==void 0&&(i.ttl=e),t&&t.length>0&&(i.tags=t),await this.request(`${this.apiUrl}${me}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${me}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${me}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}async checkSPA(e){let t=e.find(r=>r.path==="index.html"||r.path==="/index.html");if(!t||t.size>100*1024)return!1;let i;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))i=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)i=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)i=await t.content.text();else return!1;let s={files:e.map(r=>r.path),index:i};return(await this.request(`${this.apiUrl}${ot}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw S.business("No files to deploy.");for(let t of e)if(!t.md5)throw S.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async prepareRequestPayload(e,t){if(y()==="browser")return{requestBody:this.createBrowserBody(e,t),requestHeaders:{}};if(y()==="node"){let{body:i,headers:s}=await this.createNodeBody(e,t);return{requestBody:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),requestHeaders:s}}else throw S.business("Unknown or unsupported execution environment")}createBrowserBody(e,t){let i=new FormData,s=[];for(let o of e){if(!(o.content instanceof File||o.content instanceof Blob))throw S.file(`Unsupported file.content type for browser FormData: ${o.path}`,o.path);let r=this.getBrowserContentType(o.content instanceof File?o.content:o.path),a=new File([o.content],o.path,{type:r});i.append("files[]",a),s.push(o.md5)}return i.append("checksums",JSON.stringify(s)),t&&t.length>0&&i.append("tags",JSON.stringify(t)),i}async createNodeBody(e,t){let{FormData:i,File:s}=await import("formdata-node"),{FormDataEncoder:o}=await import("form-data-encoder"),r=new i,a=[];for(let l of e){let m=ee(l.path),u;if(Buffer.isBuffer(l.content))u=new s([l.content],l.path,{type:m});else if(typeof Blob<"u"&&l.content instanceof Blob)u=new s([l.content],l.path,{type:m});else throw S.file(`Unsupported file.content type for Node.js FormData: ${l.path}`,l.path);let P=l.path.startsWith("/")?l.path:"/"+l.path;r.append("files[]",u,P),a.push(l.md5)}r.append("checksums",JSON.stringify(a)),t&&t.length>0&&r.append("tags",JSON.stringify(t));let f=new o(r),g=[];for await(let l of f.encode())g.push(Buffer.from(l));let w=Buffer.concat(g);return{body:w,headers:{"Content-Type":f.contentType,"Content-Length":Buffer.byteLength(w).toString()}}}getBrowserContentType(e){return typeof e=="string"?ee(e):e.type||ee(e.name)}};I();import{ShipError as ze}from"@shipstatic/types";F();import{DEFAULT_API as lt}from"@shipstatic/types";async function pt(n){let e=y();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(ie(),Oe));return t(n)}else return{}}function B(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||lt,apiKey:n.apiKey!==void 0?n.apiKey:e.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:e.deployToken},i={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(i.apiKey=t.apiKey),t.deployToken!==void 0&&(i.deployToken=t.deployToken),i}function V(n,e){let t={...n};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}j();import{DEPLOYMENT_CONFIG_FILENAME as Ne}from"@shipstatic/types";async function mt(){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:i}=await b(t);return{path:Ne,content:t,size:e.length,md5:i}}async function Me(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===Ne))return n;try{if(await e.checkSPA(n)){let s=await mt();return[...n,s]}}catch{}return n}function G(n,e,t,i,s){return{create:async(o,r={})=>{if(s&&!s()&&!r.deployToken&&!r.apiKey)throw new Error("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");t&&await t();let a=e?V(r,e):r,f=n();if(!i)throw new Error("processInput function is not provided.");let g=await i(o,a);return g=await Me(g,f,a),await f.deploy(g,a)},list:async()=>(t&&await t(),n().listDeployments()),remove:async o=>{t&&await t(),await n().removeDeployment(o)},get:async o=>(t&&await t(),n().getDeployment(o))}}function W(n,e){return{set:async(t,i,s)=>(e&&await e(),n().setDomain(t,i,s)),get:async t=>(e&&await e(),n().getDomain(t)),list:async()=>(e&&await e(),n().listDomains()),remove:async t=>{e&&await e(),await n().removeDomain(t)},confirm:async t=>(e&&await e(),n().confirmDomain(t)),dns:async t=>(e&&await e(),n().getDomainDns(t)),records:async t=>(e&&await e(),n().getDomainRecords(t)),share:async t=>(e&&await e(),n().getDomainShare(t))}}function J(n,e){return{get:async()=>(e&&await e(),n().getAccount())}}function Y(n,e){return{create:async(t,i)=>(e&&await e(),n().createToken(t,i)),list:async()=>(e&&await e(),n().listTokens()),remove:async t=>{e&&await e(),await n().removeToken(t)}}}var L=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 R({...e,...t,getAuthHeaders:this.authHeadersCallback});let i=()=>this.ensureInitialized(),s=()=>this.http;this._deployments=G(s,this.clientOptions,i,(o,r)=>this.processInput(o,r),()=>this.hasAuth()),this._domains=W(s,i),this._account=J(s,i),this._tokens=Y(s,i)}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=A(),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 ze.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 ze.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){if(!this.auth)return{};switch(this.auth.type){case"token":return{Authorization:`Bearer ${this.auth.value}`};case"apiKey":return{Authorization:`Bearer ${this.auth.value}`};default:return{}}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};F();ie();import{ShipError as xe}from"@shipstatic/types";I();var c={};M(c,{ApiHttp:()=>R,DEFAULT_API:()=>ye,FILE_VALIDATION_STATUS:()=>d,JUNK_DIRECTORIES:()=>oe,Ship:()=>L,ShipError:()=>Se,ShipErrorType:()=>Ee,__setTestEnvironment:()=>q,allValidFilesReady:()=>Fe,calculateMD5:()=>b,createAccountResource:()=>J,createDeploymentResource:()=>G,createDomainResource:()=>W,createTokenResource:()=>Y,filterJunk:()=>k,formatFileSize:()=>K,getENV:()=>y,getValidFiles:()=>le,loadConfig:()=>pt,mergeDeployOptions:()=>V,optimizeDeployPaths:()=>O,pluralize:()=>ge,resolveConfig:()=>B,validateFiles:()=>De});var v={};p(v,Xt);import*as Xt from"@shipstatic/types";p(c,v);import{DEFAULT_API as ye}from"@shipstatic/types";j();function ge(n,e,t,i=!0){let s=n===1?e:t;return i?`${n} ${s}`:s}se();ae();F();import{FileValidationStatus as d}from"@shipstatic/types";import Be from"mime-db";var ht=new Set(Object.keys(Be)),yt=new Map(Object.entries(Be).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)]));function K(n,e=1){if(n===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,s)).toFixed(e))+" "+i[s]}function gt(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(".")===!1&&(n.startsWith(" ")||n.endsWith(" ")||n.endsWith(".")))return{valid:!1,reason:"File name cannot start/end with spaces or end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,i=n.split("/").pop()||n;return t.test(i)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function vt(n,e){if(n.startsWith("."))return!0;let t=n.toLowerCase().split(".");if(t.length>1&&t[t.length-1]){let i=t[t.length-1],s=yt.get(e);if(s&&!s.has(i))return!1}return!0}function De(n,e){let t=[],i=[];if(n.length===0){let o="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:o,errors:[o],isClientError:!0}}}if(n.length>e.maxFilesCount){let o=`Number of files (${n.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:n.map(r=>({...r,status:d.VALIDATION_FAILED,statusMessage:o})),validFiles:[],error:{error:"File Count Exceeded",details:o,errors:[o],isClientError:!0}}}let s=0;for(let o of n){let r=d.READY,a="Ready for upload",f=o.name?gt(o.name):{valid:!1,reason:"File name cannot be empty"};o.status===d.PROCESSING_ERROR?(r=d.PROCESSING_ERROR,a=o.statusMessage||"A file failed during processing.",t.push(`${o.name}: ${a}`)):!o.name||o.name.trim().length===0?(r=d.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${o.name||"(empty)"}: ${a}`)):o.name.includes("\0")?(r=d.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push(`${o.name}: ${a}`)):f.valid?o.size<=0?(r=d.EMPTY_FILE,a=o.size===0?"File is empty (0 bytes)":"File size must be positive",t.push(`${o.name}: ${a}`)):!o.type||o.type.trim().length===0?(r=d.VALIDATION_FAILED,a="File MIME type is required",t.push(`${o.name}: ${a}`)):e.allowedMimeTypes.some(g=>o.type.startsWith(g))?ht.has(o.type)?vt(o.name,o.type)?o.size>e.maxFileSize?(r=d.VALIDATION_FAILED,a=`File size (${K(o.size)}) exceeds limit of ${K(e.maxFileSize)}`,t.push(`${o.name}: ${a}`)):(s+=o.size,s>e.maxTotalSize&&(r=d.VALIDATION_FAILED,a=`Total size would exceed limit of ${K(e.maxTotalSize)}`,t.push(`${o.name}: ${a}`))):(r=d.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${o.name}: ${a}`)):(r=d.VALIDATION_FAILED,a=`Invalid MIME type "${o.type}"`,t.push(`${o.name}: ${a}`)):(r=d.VALIDATION_FAILED,a=`File type "${o.type}" is not allowed`,t.push(`${o.name}: ${a}`)):(r=d.VALIDATION_FAILED,a=f.reason||"Invalid file name",t.push(`${o.name}: ${a}`)),i.push({...o,status:r,statusMessage:a})}if(t.length>0){let o=i.find(a=>a.status!==d.READY&&a.status!==d.PENDING),r="Validation Failed";return o?.status===d.PROCESSING_ERROR?r="Processing Error":o?.status===d.EMPTY_FILE?r="Empty File":o?.statusMessage?.includes("File name cannot be empty")||o?.statusMessage?.includes("Invalid file name")||o?.statusMessage?.includes("File name contains")||o?.statusMessage?.includes("File name uses")||o?.statusMessage?.includes("File name cannot start")||o?.statusMessage?.includes("traversal")?r="Invalid File Name":o?.statusMessage?.includes("File size must be positive")?r="Invalid File Size":o?.statusMessage?.includes("MIME type is required")?r="Missing MIME Type":o?.statusMessage?.includes("Invalid MIME type")?r="Invalid MIME Type":o?.statusMessage?.includes("not allowed")?r="Invalid File Type":o?.statusMessage?.includes("extension does not match")?r="Extension Mismatch":o?.statusMessage?.includes("Total size")?r="Total Size Exceeded":o?.statusMessage?.includes("exceeds limit")&&(r="File Too Large"),{files:i.map(a=>({...a,status:d.VALIDATION_FAILED})),validFiles:[],error:{error:r,details:t.length===1?t[0]:`${t.length} file(s) failed validation`,errors:t,isClientError:!0}}}return{files:i,validFiles:i,error:null}}function le(n){return n.filter(e=>e.status===d.READY)}function Fe(n){return le(n).length>0}import{ShipError as Se,ShipErrorType as Ee}from"@shipstatic/types";p(h,c);ie();I();I();Ce();F();var Z=class extends L{constructor(e={}){if(y()!=="node")throw xe.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return B(e,{})}async loadFullConfig(){try{let e=await U(this.clientOptions.configFile),t=B(this.clientOptions,e),i=new R({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback});this.replaceHttpClient(i);let s=await this.http.getConfig();z(s)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#e(e))throw xe.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw xe.business("No files to deploy.");let{convertDeployInput:i}=await Promise.resolve().then(()=>(Je(),We));return i(e,t,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},Te=Z;p(Q,h);export{R as ApiHttp,ye as DEFAULT_API,d as FILE_VALIDATION_STATUS,oe as JUNK_DIRECTORIES,Z as Ship,Se as ShipError,Ee as ShipErrorType,q as __setTestEnvironment,Fe as allValidFilesReady,b as calculateMD5,J as createAccountResource,G as createDeploymentResource,W as createDomainResource,Y as createTokenResource,Te as default,k as filterJunk,K as formatFileSize,A as getCurrentConfig,y as getENV,le as getValidFiles,U as loadConfig,V as mergeDeployOptions,O as optimizeDeployPaths,ge as pluralize,X as processFilesForNode,B as resolveConfig,z as setConfig,z as setPlatformConfig,De as validateFiles};
|
|
1
|
+
var ke=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var P=(n,e)=>()=>(n&&(e=n(n=0)),e);var N=(n,e)=>{for(var t in e)ke(n,t,{get:e[t],enumerable:!0})},Ae=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of et(e))!tt.call(n,s)&&s!==t&&ke(n,s,{get:()=>e[s],enumerable:!(i=Ze(e,s))||i.enumerable});return n},p=(n,e,t)=>(Ae(n,e,"default"),t&&Ae(t,e,"default"));var $e={};N($e,{__setTestEnvironment:()=>H,getENV:()=>g});function H(n){fe=n}function nt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function g(){return fe||nt()}var fe,F=P(()=>{"use strict";fe=null});import{ShipError as lt}from"@shipstatic/types";function z(n){ue=n}function b(){if(ue===null)throw lt.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ue}var ue,$=P(()=>{"use strict";ue=null});var Ne={};N(Ne,{loadConfig:()=>L});import{z as j}from"zod";import{ShipError as he}from"@shipstatic/types";function Me(n){try{return pt.parse(n)}catch(e){if(e instanceof j.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw he.config(`Configuration validation failed${i}: ${t.message}`)}throw he.config("Configuration validation failed")}}async function ct(n){try{if(g()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(de,{searchPlaces:[`.${de}rc`,"package.json",`${t.homedir()}/.${de}rc`],stopDir:t.homedir()}),s;if(n?s=i.load(n):s=i.search(),s&&s.config)return Me(s.config)}catch(e){if(e instanceof he)throw e}return{}}async function L(n){if(g()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await ct(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Me(i)}var de,pt,oe=P(()=>{"use strict";F();de="ship",pt=j.object({apiUrl:j.string().url().optional(),apiKey:j.string().optional(),deployToken:j.string().optional()}).strict()});import{ShipError as B}from"@shipstatic/types";async function ut(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let o=Math.ceil(n.size/2097152),r=0,a=new e.ArrayBuffer,d=new FileReader,c=()=>{let w=r*2097152,l=Math.min(w+2097152,n.size);d.readAsArrayBuffer(n.slice(w,l))};d.onload=w=>{let l=w.target?.result;if(!l){i(B.business("Failed to read file chunk"));return}a.append(l),r++,r<o?c():t({md5:a.end()})},d.onerror=()=>{i(B.business("Failed to calculate MD5: FileReader error"))},c()})}async function dt(n){let e=await import("crypto");if(Buffer.isBuffer(n)){let i=e.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let t=await import("fs");return new Promise((i,s)=>{let o=e.createHash("md5"),r=t.createReadStream(n);r.on("error",a=>s(B.business(`Failed to read file for MD5: ${a.message}`))),r.on("data",a=>o.update(a)),r.on("end",()=>i({md5:o.digest("hex")}))})}async function A(n){let e=g();if(e==="browser"){if(!(n instanceof Blob))throw B.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return ut(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw B.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return dt(n)}throw B.business("Unknown or unsupported execution environment for MD5 calculation.")}var G=P(()=>{"use strict";F()});import{isJunk as yt}from"junk";function O(n){return!n||n.length===0?[]:n.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let i=t[t.length-1];if(yt(i))return!1;let s=t.slice(0,-1);for(let o of s)if(se.some(r=>o.toLowerCase()===r.toLowerCase()))return!1;return!0})}var se,re=P(()=>{"use strict";se=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Be(n){if(!n||n.length===0)return"";let e=n.filter(o=>o&&typeof o=="string").map(o=>o.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(o=>o.split("/").filter(Boolean)),i=[],s=Math.min(...t.map(o=>o.length));for(let o=0;o<s;o++){let r=t[0][o];if(t.every(a=>a[o]===r))i.push(r);else break}return i.join("/")}function ae(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ve=P(()=>{"use strict"});function M(n,e={}){if(e.flatten===!1)return n.map(i=>({path:ae(i),name:we(i)}));let t=gt(n);return n.map(i=>{let s=ae(i);if(t){let o=t.endsWith("/")?t:`${t}/`;s.startsWith(o)&&(s=s.substring(o.length))}return s||(s=we(i)),{path:s,name:we(i)}})}function gt(n){if(!n.length)return"";let t=n.map(o=>ae(o)).map(o=>o.split("/")),i=[],s=Math.min(...t.map(o=>o.length));for(let o=0;o<s-1;o++){let r=t[0][o];if(t.every(a=>a[o]===r))i.push(r);else break}return i.join("/")}function we(n){return n.split(/[/\\]/).pop()||n}var le=P(()=>{"use strict";ve()});import{ShipError as I}from"@shipstatic/types";import*as E from"fs";import*as S from"path";function Ke(n,e=new Set){let t=[],i=E.realpathSync(n);if(e.has(i))return t;e.add(i);let s=E.readdirSync(n);for(let o of s){let r=S.join(n,o),a=E.statSync(r);if(a.isDirectory()){let d=Ke(r,e);t.push(...d)}else a.isFile()&&t.push(r)}return t}async function Q(n,e={}){if(g()!=="node")throw I.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(m=>{let u=S.resolve(m);try{return E.statSync(u).isDirectory()?Ke(u):[u]}catch{throw I.file(`Path does not exist: ${m}`,m)}}),i=[...new Set(t)],s=O(i);if(s.length===0)return[];let o=n.map(m=>S.resolve(m)),r=Be(o.map(m=>{try{return E.statSync(m).isDirectory()?m:S.dirname(m)}catch{return S.dirname(m)}})),a=s.map(m=>{if(r&&r.length>0){let u=S.relative(r,m);if(u&&typeof u=="string"&&!u.startsWith(".."))return u.replace(/\\/g,"/")}return S.basename(m)}),d=M(a,{flatten:e.pathDetect!==!1}),c=[],w=0,l=b();for(let m=0;m<s.length;m++){let u=s[m],T=d[m].path;try{let x=E.statSync(u);if(x.size===0){console.warn(`Skipping empty file: ${u}`);continue}if(x.size>l.maxFileSize)throw I.business(`File ${u} is too large. Maximum allowed size is ${l.maxFileSize/(1024*1024)}MB.`);if(w+=x.size,w>l.maxTotalSize)throw I.business(`Total deploy size is too large. Maximum allowed is ${l.maxTotalSize/(1024*1024)}MB.`);let q=E.readFileSync(u),{md5:Qe}=await A(q);if(T.includes("\0")||T.includes("/../")||T.startsWith("../")||T.endsWith("/.."))throw I.business(`Security error: Unsafe file path "${T}" for file: ${u}`);c.push({path:T,content:q,size:q.length,md5:Qe})}catch(x){if(x instanceof I)throw x;let q=x instanceof Error?x.message:String(x);throw I.file(`Failed to read file "${u}": ${q}`,u)}}if(c.length>l.maxFilesCount)throw I.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return c}var Pe=P(()=>{"use strict";F();G();re();$();le();ve()});import{ShipError as qe}from"@shipstatic/types";async function He(n,e={}){let{getENV:t}=await Promise.resolve().then(()=>(F(),$e));if(t()!=="browser")throw qe.business("processFilesForBrowser can only be called in a browser environment.");let i=n,s=i.map(l=>l.webkitRelativePath||l.name),o=M(s,{flatten:e.pathDetect!==!1}),r=[];for(let l=0;l<i.length;l++){let m=i[l],u=o[l].path;if(u.includes("..")||u.includes("\0"))throw qe.business(`Security error: Unsafe file path "${u}" for file: ${m.name}`);r.push({file:m,relativePath:u})}let a=r.map(l=>l.relativePath),d=O(a),c=new Set(d),w=[];for(let l of r){if(!c.has(l.relativePath))continue;let{md5:m}=await A(l.file);w.push({content:l.file,path:l.relativePath,size:l.file.size,md5:m})}return w}var je=P(()=>{"use strict";G();re();le()});var Ye={};N(Ye,{convertBrowserInput:()=>Je,convertDeployInput:()=>Ft,convertNodeInput:()=>xe});import{ShipError as C}from"@shipstatic/types";function Ve(n,e={}){let t=b();if(!e.skipEmptyCheck&&n.length===0)throw C.business("No files to deploy.");if(n.length>t.maxFilesCount)throw C.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let i=0;for(let s of n){if(s.size>t.maxFileSize)throw C.business(`File ${s.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(i+=s.size,i>t.maxTotalSize)throw C.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Ge(n,e){if(e==="node"){if(!Array.isArray(n))throw C.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(n.length===0)throw C.business("No files to deploy.");if(!n.every(t=>typeof t=="string"))throw C.business("Invalid input type for Node.js environment. Expected string[] file paths.")}}function We(n){let e=n.map(t=>({name:t.path,size:t.size}));return Ve(e,{skipEmptyCheck:!0}),n.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),n}async function xe(n,e={}){Ge(n,"node");let t=await Q(n,e);return We(t)}async function Je(n,e={}){Ge(n,"browser");let t;if(Array.isArray(n)){if(n.length>0&&typeof n[0]=="string")throw C.business("Invalid input type for browser environment. Expected File[].");t=n}else throw C.business("Invalid input type for browser environment. Expected File[].");t=t.filter(s=>s.size===0?(console.warn(`Skipping empty file: ${s.name}`),!1):!0),Ve(t);let i=await He(t,e);return We(i)}async function Ft(n,e={},t){let i=g();if(i!=="node"&&i!=="browser")throw C.business("Unsupported execution environment.");let s;if(i==="node")if(typeof n=="string")s=await xe([n],e);else if(Array.isArray(n)&&n.every(o=>typeof o=="string"))s=await xe(n,e);else throw C.business("Invalid input type for Node.js environment. Expected string[] file paths.");else s=await Je(n,e);return s}var Xe=P(()=>{"use strict";F();Pe();je();$()});var ee={};N(ee,{ApiHttp:()=>R,DEFAULT_API:()=>ye,ErrorType:()=>Te,FILE_VALIDATION_STATUS:()=>h,JUNK_DIRECTORIES:()=>se,Ship:()=>Z,ShipError:()=>Ce,__setTestEnvironment:()=>H,allValidFilesReady:()=>Se,calculateMD5:()=>A,createAccountResource:()=>Y,createDeploymentResource:()=>W,createDomainResource:()=>J,createTokenResource:()=>X,default:()=>be,ensureShipError:()=>Ee,filterJunk:()=>O,formatFileSize:()=>K,getCurrentConfig:()=>b,getENV:()=>g,getValidFiles:()=>pe,loadConfig:()=>L,mergeDeployOptions:()=>V,optimizeDeployPaths:()=>M,pluralize:()=>ge,processFilesForNode:()=>Q,resolveConfig:()=>_,setConfig:()=>z,setPlatformConfig:()=>z,validateFiles:()=>De});var y={};N(y,{ApiHttp:()=>R,DEFAULT_API:()=>ye,ErrorType:()=>Te,FILE_VALIDATION_STATUS:()=>h,JUNK_DIRECTORIES:()=>se,Ship:()=>Z,ShipError:()=>Ce,__setTestEnvironment:()=>H,allValidFilesReady:()=>Se,calculateMD5:()=>A,createAccountResource:()=>Y,createDeploymentResource:()=>W,createDomainResource:()=>J,createTokenResource:()=>X,default:()=>be,ensureShipError:()=>Ee,filterJunk:()=>O,formatFileSize:()=>K,getCurrentConfig:()=>b,getENV:()=>g,getValidFiles:()=>pe,loadConfig:()=>L,mergeDeployOptions:()=>V,optimizeDeployPaths:()=>M,pluralize:()=>ge,processFilesForNode:()=>Q,resolveConfig:()=>_,setConfig:()=>z,setPlatformConfig:()=>z,validateFiles:()=>De});import Ie from"mime-db";var ce={};for(let n in Ie){let e=Ie[n];e&&e.extensions&&e.extensions.forEach(t=>{ce[t]||(ce[t]=n)})}function te(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return ce[e]||"application/octet-stream"}import{ShipError as D,DEFAULT_API as it}from"@shipstatic/types";var ne=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 i=this.handlers.get(e);i&&(i.delete(t),i.size===0&&this.handlers.delete(e))}emit(e,...t){let i=this.handlers.get(e);if(!i)return;let s=Array.from(i);for(let o of s)try{o(...t)}catch(r){i.delete(o),e!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(e)):this.emit("error",new Error(String(r)),String(e))},0)}}transfer(e){this.handlers.forEach((t,i)=>{t.forEach(s=>{e.on(i,s)})})}clear(){this.handlers.clear()}};F();var ie="/deployments",Oe="/ping",k="/domains",ot="/config",st="/account",me="/tokens",rt="/spa-check",at=3e4,R=class extends ne{constructor(e){super(),this.apiUrl=e.apiUrl||it,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??at}transferEventsTo(e){this.transfer(e)}async request(e,t={},i){let s=this.getAuthHeaders(t.headers),o=new AbortController,r=setTimeout(()=>o.abort(),this.timeout),a=t.signal?this.combineSignals(t.signal,o.signal):o.signal,d={...t,headers:s,credentials:s.Authorization?void 0:"include",signal:a};this.emit("request",e,d);try{let c=await fetch(e,d);clearTimeout(r),c.ok||await this.handleResponseError(c,i);let w=this.safeClone(c),l=this.safeClone(c);return this.emit("response",w,e),await this.parseResponse(l)}catch(c){throw clearTimeout(r),this.emit("error",c,e),this.handleFetchError(c,i),c}}combineSignals(e,t){let i=new AbortController,s=()=>i.abort();return e.addEventListener("abort",s),t.addEventListener("abort",s),(e.aborted||t.aborted)&&i.abort(),i.signal}async requestWithStatus(e,t={},i){let s=this.getAuthHeaders(t.headers),o=new AbortController,r=setTimeout(()=>o.abort(),this.timeout),a=t.signal?this.combineSignals(t.signal,o.signal):o.signal,d={...t,headers:s,credentials:s.Authorization?void 0:"include",signal:a};this.emit("request",e,d);try{let c=await fetch(e,d);clearTimeout(r),c.ok||await this.handleResponseError(c,i);let w=this.safeClone(c),l=this.safeClone(c);return this.emit("response",w,e),{data:await this.parseResponse(l),status:c.status}}catch(c){throw clearTimeout(r),this.emit("error",c,e),this.handleFetchError(c,i),c}}getAuthHeaders(e={}){let t=this.getAuthHeadersCallback();return{...e,...t}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return await e.json()}async handleResponseError(e,t){let i={};try{e.headers.get("content-type")?.includes("application/json")?i=await e.json():i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let s=i.message||i.error||`${t} failed due to API error`;throw e.status===401?D.authentication(s):D.api(s,e.status,i.code,i)}handleFetchError(e,t){throw e.name==="AbortError"?D.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?D.network(`${t} failed due to network error: ${e.message}`,e):e instanceof D?e:D.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${Oe}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${Oe}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${ot}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:i,requestHeaders:s}=await this.prepareRequestPayload(e,t.tags),o={};t.deployToken?o={Authorization:`Bearer ${t.deployToken}`}:t.apiKey&&(o={Authorization:`Bearer ${t.apiKey}`});let r={method:"POST",body:i,headers:{...s,...o},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${ie}`,r,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${ie}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${ie}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${ie}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,t,i){let s={};t&&(s.deployment=t),i&&i.length>0&&(s.tags=i);let o=`${this.apiUrl}${k}/${encodeURIComponent(e)}`,{data:r,status:a}=await this.requestWithStatus(o,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Set Domain");return{...r,isCreate:a===201}}async getDomain(e){return await this.request(`${this.apiUrl}${k}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${k}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${k}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async confirmDomain(e){return await this.request(`${this.apiUrl}${k}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${k}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${k}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${k}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${st}`,{method:"GET"},"Get Account")}async createToken(e,t){let i={};return e!==void 0&&(i.ttl=e),t&&t.length>0&&(i.tags=t),await this.request(`${this.apiUrl}${me}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${me}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${me}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}async checkSPA(e){let t=e.find(r=>r.path==="index.html"||r.path==="/index.html");if(!t||t.size>100*1024)return!1;let i;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))i=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)i=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)i=await t.content.text();else return!1;let s={files:e.map(r=>r.path),index:i};return(await this.request(`${this.apiUrl}${rt}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw D.business("No files to deploy.");for(let t of e)if(!t.md5)throw D.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async prepareRequestPayload(e,t){if(g()==="browser")return{requestBody:this.createBrowserBody(e,t),requestHeaders:{}};if(g()==="node"){let{body:i,headers:s}=await this.createNodeBody(e,t);return{requestBody:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),requestHeaders:s}}else throw D.business("Unknown or unsupported execution environment")}createBrowserBody(e,t){let i=new FormData,s=[];for(let o of e){if(!(o.content instanceof File||o.content instanceof Blob))throw D.file(`Unsupported file.content type for browser FormData: ${o.path}`,o.path);if(!o.md5)throw D.file(`File missing md5 checksum: ${o.path}`,o.path);let r=this.getBrowserContentType(o.content instanceof File?o.content:o.path),a=new File([o.content],o.path,{type:r});i.append("files[]",a),s.push(o.md5)}return i.append("checksums",JSON.stringify(s)),t&&t.length>0&&i.append("tags",JSON.stringify(t)),i}async createNodeBody(e,t){let{FormData:i,File:s}=await import("formdata-node"),{FormDataEncoder:o}=await import("form-data-encoder"),r=new i,a=[];for(let l of e){let m=te(l.path),u;if(Buffer.isBuffer(l.content))u=new s([l.content],l.path,{type:m});else if(typeof Blob<"u"&&l.content instanceof Blob)u=new s([l.content],l.path,{type:m});else throw D.file(`Unsupported file.content type for Node.js FormData: ${l.path}`,l.path);if(!l.md5)throw D.file(`File missing md5 checksum: ${l.path}`,l.path);let T=l.path.startsWith("/")?l.path:"/"+l.path;r.append("files[]",u,T),a.push(l.md5)}r.append("checksums",JSON.stringify(a)),t&&t.length>0&&r.append("tags",JSON.stringify(t));let d=new o(r),c=[];for await(let l of d.encode())c.push(Buffer.from(l));let w=Buffer.concat(c);return{body:w,headers:{"Content-Type":d.contentType,"Content-Length":Buffer.byteLength(w).toString()}}}getBrowserContentType(e){return typeof e=="string"?te(e):e.type||te(e.name)}};$();import{ShipError as _e}from"@shipstatic/types";F();import{DEFAULT_API as ft}from"@shipstatic/types";async function mt(n){let e=g();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(oe(),Ne));return t(n)}else return{}}function _(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||ft,apiKey:n.apiKey!==void 0?n.apiKey:e.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:e.deployToken},i={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(i.apiKey=t.apiKey),t.deployToken!==void 0&&(i.deployToken=t.deployToken),i}function V(n,e){let t={...n};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}G();import{DEPLOYMENT_CONFIG_FILENAME as ze}from"@shipstatic/types";async function ht(){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:i}=await A(t);return{path:ze,content:t,size:e.length,md5:i}}async function Le(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===ze))return n;try{if(await e.checkSPA(n)){let s=await ht();return[...n,s]}}catch{}return n}function W(n,e,t,i,s){return{create:async(o,r={})=>{t&&await t();let a=e?V(r,e):r;if(s&&!s()&&!a.deployToken&&!a.apiKey)throw new Error("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");let d=n();if(!i)throw new Error("processInput function is not provided.");let c=await i(o,a);return c=await Le(c,d,a),await d.deploy(c,a)},list:async()=>(t&&await t(),n().listDeployments()),remove:async o=>{t&&await t(),await n().removeDeployment(o)},get:async o=>(t&&await t(),n().getDeployment(o))}}function J(n,e){return{set:async(t,i,s)=>(e&&await e(),n().setDomain(t,i,s)),get:async t=>(e&&await e(),n().getDomain(t)),list:async()=>(e&&await e(),n().listDomains()),remove:async t=>{e&&await e(),await n().removeDomain(t)},confirm:async t=>(e&&await e(),n().confirmDomain(t)),dns:async t=>(e&&await e(),n().getDomainDns(t)),records:async t=>(e&&await e(),n().getDomainRecords(t)),share:async t=>(e&&await e(),n().getDomainShare(t))}}function Y(n,e){return{get:async()=>(e&&await e(),n().getAccount())}}function X(n,e){return{create:async(t,i)=>(e&&await e(),n().createToken(t,i)),list:async()=>(e&&await e(),n().listTokens()),remove:async t=>{e&&await e(),await n().removeToken(t)}}}var U=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 R({...e,...t,getAuthHeaders:this.authHeadersCallback});let i=()=>this.ensureInitialized(),s=()=>this.http;this._deployments=W(s,this.clientOptions,i,(o,r)=>this.processInput(o,r),()=>this.hasAuth()),this._domains=J(s,i),this._account=Y(s,i),this._tokens=X(s,i)}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=b(),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 _e.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 _e.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){if(!this.auth)return{};switch(this.auth.type){case"token":return{Authorization:`Bearer ${this.auth.value}`};case"apiKey":return{Authorization:`Bearer ${this.auth.value}`};default:return{}}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};F();oe();import{ShipError as Re}from"@shipstatic/types";$();var f={};N(f,{ApiHttp:()=>R,DEFAULT_API:()=>ye,ErrorType:()=>Te,FILE_VALIDATION_STATUS:()=>h,JUNK_DIRECTORIES:()=>se,Ship:()=>U,ShipError:()=>Ce,__setTestEnvironment:()=>H,allValidFilesReady:()=>Se,calculateMD5:()=>A,createAccountResource:()=>Y,createDeploymentResource:()=>W,createDomainResource:()=>J,createTokenResource:()=>X,ensureShipError:()=>Ee,filterJunk:()=>O,formatFileSize:()=>K,getENV:()=>g,getValidFiles:()=>pe,loadConfig:()=>mt,mergeDeployOptions:()=>V,optimizeDeployPaths:()=>M,pluralize:()=>ge,resolveConfig:()=>_,validateFiles:()=>De});var v={};p(v,en);import*as en from"@shipstatic/types";p(f,v);import{DEFAULT_API as ye}from"@shipstatic/types";G();function ge(n,e,t,i=!0){let s=n===1?e:t;return i?`${n} ${s}`:s}re();le();F();import{FileValidationStatus as h}from"@shipstatic/types";import Ue from"mime-db";var vt=new Set(Object.keys(Ue)),wt=new Map(Object.entries(Ue).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)]));function K(n,e=1){if(n===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,s)).toFixed(e))+" "+i[s]}function Dt(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(".")===!1&&(n.startsWith(" ")||n.endsWith(" ")||n.endsWith(".")))return{valid:!1,reason:"File name cannot start/end with spaces or end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,i=n.split("/").pop()||n;return t.test(i)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function St(n,e){if(n.startsWith("."))return!0;let t=n.toLowerCase().split(".");if(t.length>1&&t[t.length-1]){let i=t[t.length-1],s=wt.get(e);if(s&&!s.has(i))return!1}return!0}function De(n,e){let t=[],i=[];if(n.length===0){let o="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:o,errors:[o],isClientError:!0}}}if(n.length>e.maxFilesCount){let o=`Number of files (${n.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:n.map(r=>({...r,status:h.VALIDATION_FAILED,statusMessage:o})),validFiles:[],error:{error:"File Count Exceeded",details:o,errors:[o],isClientError:!0}}}let s=0;for(let o of n){let r=h.READY,a="Ready for upload",d=o.name?Dt(o.name):{valid:!1,reason:"File name cannot be empty"};o.status===h.PROCESSING_ERROR?(r=h.PROCESSING_ERROR,a=o.statusMessage||"A file failed during processing.",t.push(`${o.name}: ${a}`)):!o.name||o.name.trim().length===0?(r=h.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${o.name||"(empty)"}: ${a}`)):o.name.includes("\0")?(r=h.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push(`${o.name}: ${a}`)):d.valid?o.size<=0?(r=h.EMPTY_FILE,a=o.size===0?"File is empty (0 bytes)":"File size must be positive",t.push(`${o.name}: ${a}`)):!o.type||o.type.trim().length===0?(r=h.VALIDATION_FAILED,a="File MIME type is required",t.push(`${o.name}: ${a}`)):e.allowedMimeTypes.some(c=>o.type.startsWith(c))?vt.has(o.type)?St(o.name,o.type)?o.size>e.maxFileSize?(r=h.VALIDATION_FAILED,a=`File size (${K(o.size)}) exceeds limit of ${K(e.maxFileSize)}`,t.push(`${o.name}: ${a}`)):(s+=o.size,s>e.maxTotalSize&&(r=h.VALIDATION_FAILED,a=`Total size would exceed limit of ${K(e.maxTotalSize)}`,t.push(`${o.name}: ${a}`))):(r=h.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${o.name}: ${a}`)):(r=h.VALIDATION_FAILED,a=`Invalid MIME type "${o.type}"`,t.push(`${o.name}: ${a}`)):(r=h.VALIDATION_FAILED,a=`File type "${o.type}" is not allowed`,t.push(`${o.name}: ${a}`)):(r=h.VALIDATION_FAILED,a=d.reason||"Invalid file name",t.push(`${o.name}: ${a}`)),i.push({...o,status:r,statusMessage:a})}if(t.length>0){let o=i.find(a=>a.status!==h.READY&&a.status!==h.PENDING),r="Validation Failed";return o?.status===h.PROCESSING_ERROR?r="Processing Error":o?.status===h.EMPTY_FILE?r="Empty File":o?.statusMessage?.includes("File name cannot be empty")||o?.statusMessage?.includes("Invalid file name")||o?.statusMessage?.includes("File name contains")||o?.statusMessage?.includes("File name uses")||o?.statusMessage?.includes("File name cannot start")||o?.statusMessage?.includes("traversal")?r="Invalid File Name":o?.statusMessage?.includes("File size must be positive")?r="Invalid File Size":o?.statusMessage?.includes("MIME type is required")?r="Missing MIME Type":o?.statusMessage?.includes("Invalid MIME type")?r="Invalid MIME Type":o?.statusMessage?.includes("not allowed")?r="Invalid File Type":o?.statusMessage?.includes("extension does not match")?r="Extension Mismatch":o?.statusMessage?.includes("Total size")?r="Total Size Exceeded":o?.statusMessage?.includes("exceeds limit")&&(r="File Too Large"),{files:i.map(a=>({...a,status:h.VALIDATION_FAILED})),validFiles:[],error:{error:r,details:t.length===1?t[0]:`${t.length} file(s) failed validation`,errors:t,isClientError:!0}}}return{files:i,validFiles:i,error:null}}function pe(n){return n.filter(e=>e.status===h.READY)}function Se(n){return pe(n).length>0}import{ShipError as Fe}from"@shipstatic/types";function Ee(n){return n instanceof Fe?n:n instanceof Error?Fe.business(n.message):Fe.business(String(n??"Unknown error"))}import{ShipError as Ce,ErrorType as Te}from"@shipstatic/types";p(y,f);oe();$();$();Pe();F();var Z=class extends U{constructor(e={}){if(g()!=="node")throw Re.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return _(e,{})}async loadFullConfig(){try{let e=await L(this.clientOptions.configFile),t=_(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let i=new R({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback});this.replaceHttpClient(i);let s=await this.http.getConfig();z(s)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#e(e))throw Re.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw Re.business("No files to deploy.");let{convertDeployInput:i}=await Promise.resolve().then(()=>(Xe(),Ye));return i(e,t,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},be=Z;p(ee,y);export{R as ApiHttp,ye as DEFAULT_API,Te as ErrorType,h as FILE_VALIDATION_STATUS,se as JUNK_DIRECTORIES,Z as Ship,Ce as ShipError,H as __setTestEnvironment,Se as allValidFilesReady,A as calculateMD5,Y as createAccountResource,W as createDeploymentResource,J as createDomainResource,X as createTokenResource,be as default,Ee as ensureShipError,O as filterJunk,K as formatFileSize,b as getCurrentConfig,g as getENV,pe as getValidFiles,L as loadConfig,V as mergeDeployOptions,M as optimizeDeployPaths,ge as pluralize,Q as processFilesForNode,_ as resolveConfig,z as setConfig,z as setPlatformConfig,De as validateFiles};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|