@shipstatic/ship 0.3.13 → 0.3.15
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 +9 -6
- package/dist/browser.d.ts +71 -35
- package/dist/browser.js +40 -5
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +23 -27
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +73 -30
- package/dist/index.d.ts +73 -30
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as _shipstatic_types from '@shipstatic/types';
|
|
2
|
-
import { ProgressInfo, PingResponse, ConfigResponse,
|
|
2
|
+
import { ProgressInfo, StaticFile, PingResponse, ConfigResponse, Deployment, DeploymentListResponse, Domain, DomainListResponse, DomainDnsResponse, DomainRecordsResponse, Account, TokenCreateResponse, TokenListResponse, ResolvedConfig, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource, ValidatableFile, FileValidationResult, ShipError } from '@shipstatic/types';
|
|
3
3
|
export * from '@shipstatic/types';
|
|
4
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
|
|
|
@@ -37,12 +37,25 @@ interface DeploymentOptions {
|
|
|
37
37
|
tags?: string[];
|
|
38
38
|
/** Callback for deploy progress with detailed statistics. */
|
|
39
39
|
onProgress?: (info: ProgressInfo) => void;
|
|
40
|
+
/** Client/tool identifier for this deployment (e.g., 'sdk', 'cli', 'web'). Alphanumeric only. */
|
|
41
|
+
via?: string;
|
|
42
|
+
/** Caller identifier for multi-tenant deployments (alphanumeric, dot, underscore, hyphen). */
|
|
43
|
+
caller?: string;
|
|
40
44
|
}
|
|
45
|
+
type ApiDeployOptions = Omit<DeploymentOptions, 'pathDetect'>;
|
|
41
46
|
/**
|
|
42
|
-
*
|
|
43
|
-
*
|
|
47
|
+
* Prepared request body for deployment.
|
|
48
|
+
* Created by platform-specific code, consumed by HTTP client.
|
|
44
49
|
*/
|
|
45
|
-
|
|
50
|
+
interface DeployBody {
|
|
51
|
+
body: FormData | ArrayBuffer;
|
|
52
|
+
headers: Record<string, string>;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Function that creates a deploy request body from files.
|
|
56
|
+
* Implemented differently for Node.js and Browser.
|
|
57
|
+
*/
|
|
58
|
+
type DeployBodyCreator = (files: StaticFile[], tags?: string[], via?: string) => Promise<DeployBody>;
|
|
46
59
|
/**
|
|
47
60
|
* Options for configuring a `Ship` instance.
|
|
48
61
|
* Sets default API host, authentication credentials, progress callbacks, concurrency, and timeouts for the client.
|
|
@@ -81,6 +94,11 @@ interface ShipClientOptions {
|
|
|
81
94
|
* to proceed with cookie-based credentials.
|
|
82
95
|
*/
|
|
83
96
|
useCredentials?: boolean | undefined;
|
|
97
|
+
/**
|
|
98
|
+
* Default caller identifier for multi-tenant deployments.
|
|
99
|
+
* Alphanumeric characters, dots, underscores, and hyphens allowed (max 128 chars).
|
|
100
|
+
*/
|
|
101
|
+
caller?: string | undefined;
|
|
84
102
|
}
|
|
85
103
|
/**
|
|
86
104
|
* Event map for Ship SDK events
|
|
@@ -136,23 +154,19 @@ declare class SimpleEvents {
|
|
|
136
154
|
}
|
|
137
155
|
|
|
138
156
|
/**
|
|
139
|
-
* @file HTTP client
|
|
140
|
-
* Clean, direct implementation with reliable error handling
|
|
157
|
+
* @file HTTP client for Ship API.
|
|
141
158
|
*/
|
|
142
159
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
* - Reliable error handling
|
|
148
|
-
*/
|
|
160
|
+
interface ApiHttpOptions extends ShipClientOptions {
|
|
161
|
+
getAuthHeaders: () => Record<string, string>;
|
|
162
|
+
createDeployBody: DeployBodyCreator;
|
|
163
|
+
}
|
|
149
164
|
declare class ApiHttp extends SimpleEvents {
|
|
150
165
|
private readonly apiUrl;
|
|
151
166
|
private readonly getAuthHeadersCallback;
|
|
152
167
|
private readonly timeout;
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
});
|
|
168
|
+
private readonly createDeployBody;
|
|
169
|
+
constructor(options: ApiHttpOptions);
|
|
156
170
|
/**
|
|
157
171
|
* Transfer events to another client (clean intentional API)
|
|
158
172
|
*/
|
|
@@ -201,7 +215,7 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
201
215
|
getDomain(name: string): Promise<Domain>;
|
|
202
216
|
listDomains(): Promise<DomainListResponse>;
|
|
203
217
|
removeDomain(name: string): Promise<void>;
|
|
204
|
-
|
|
218
|
+
verifyDomain(name: string): Promise<{
|
|
205
219
|
message: string;
|
|
206
220
|
}>;
|
|
207
221
|
getDomainDns(name: string): Promise<DomainDnsResponse>;
|
|
@@ -215,11 +229,6 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
215
229
|
listTokens(): Promise<TokenListResponse>;
|
|
216
230
|
removeToken(token: string): Promise<void>;
|
|
217
231
|
checkSPA(files: StaticFile[]): Promise<boolean>;
|
|
218
|
-
private validateFiles;
|
|
219
|
-
private prepareRequestPayload;
|
|
220
|
-
private createBrowserBody;
|
|
221
|
-
private createNodeBody;
|
|
222
|
-
private getBrowserContentType;
|
|
223
232
|
}
|
|
224
233
|
|
|
225
234
|
/**
|
|
@@ -234,8 +243,6 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
234
243
|
* This means CLI flags always win, followed by env vars, then config files.
|
|
235
244
|
*/
|
|
236
245
|
|
|
237
|
-
type Config = PlatformConfig;
|
|
238
|
-
|
|
239
246
|
/**
|
|
240
247
|
* Universal configuration resolver for all environments.
|
|
241
248
|
* This is the single source of truth for config resolution.
|
|
@@ -248,13 +255,28 @@ declare function resolveConfig(userOptions?: ShipClientOptions, loadedConfig?: P
|
|
|
248
255
|
declare function mergeDeployOptions(options: DeploymentOptions, clientDefaults: ShipClientOptions): DeploymentOptions;
|
|
249
256
|
|
|
250
257
|
/**
|
|
251
|
-
*
|
|
258
|
+
* Ship SDK resource factory functions.
|
|
252
259
|
*/
|
|
253
260
|
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
261
|
+
/**
|
|
262
|
+
* Shared context for all resource factories.
|
|
263
|
+
*/
|
|
264
|
+
interface ResourceContext {
|
|
265
|
+
getApi: () => ApiHttp;
|
|
266
|
+
ensureInit: () => Promise<void>;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Extended context for deployment resource.
|
|
270
|
+
*/
|
|
271
|
+
interface DeploymentResourceContext extends ResourceContext {
|
|
272
|
+
processInput: (input: DeployInput, options: DeploymentOptions) => Promise<StaticFile[]>;
|
|
273
|
+
clientDefaults?: ShipClientOptions;
|
|
274
|
+
hasAuth?: () => boolean;
|
|
275
|
+
}
|
|
276
|
+
declare function createDeploymentResource(ctx: DeploymentResourceContext): DeploymentResource;
|
|
277
|
+
declare function createDomainResource(ctx: ResourceContext): DomainResource;
|
|
278
|
+
declare function createAccountResource(ctx: ResourceContext): AccountResource;
|
|
279
|
+
declare function createTokenResource(ctx: ResourceContext): TokenResource;
|
|
258
280
|
|
|
259
281
|
/**
|
|
260
282
|
* Abstract base class for Ship SDK implementations.
|
|
@@ -277,6 +299,7 @@ declare abstract class Ship$1 {
|
|
|
277
299
|
protected abstract resolveInitialConfig(options: ShipClientOptions): ResolvedConfig;
|
|
278
300
|
protected abstract loadFullConfig(): Promise<void>;
|
|
279
301
|
protected abstract processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
|
|
302
|
+
protected abstract getDeployBodyCreator(): DeployBodyCreator;
|
|
280
303
|
/**
|
|
281
304
|
* Ensure full initialization is complete - called lazily by resources
|
|
282
305
|
*/
|
|
@@ -535,6 +558,26 @@ declare function getValidFiles<T extends ValidatableFile>(files: T[]): T[];
|
|
|
535
558
|
*/
|
|
536
559
|
declare function allValidFilesReady<T extends ValidatableFile>(files: T[]): boolean;
|
|
537
560
|
|
|
561
|
+
/**
|
|
562
|
+
* @file Error utilities for consistent error handling across SDK consumers.
|
|
563
|
+
*/
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* Ensure any error is wrapped as a ShipError.
|
|
567
|
+
* Useful for catch blocks where the error type is unknown.
|
|
568
|
+
*
|
|
569
|
+
* @example
|
|
570
|
+
* ```ts
|
|
571
|
+
* try {
|
|
572
|
+
* await someOperation();
|
|
573
|
+
* } catch (err) {
|
|
574
|
+
* const shipError = ensureShipError(err);
|
|
575
|
+
* // Now you can safely use shipError.message, shipError.type, etc.
|
|
576
|
+
* }
|
|
577
|
+
* ```
|
|
578
|
+
*/
|
|
579
|
+
declare function ensureShipError(err: unknown): ShipError;
|
|
580
|
+
|
|
538
581
|
/**
|
|
539
582
|
* @file Manages loading and validation of client configuration.
|
|
540
583
|
* This module uses `cosmiconfig` to find and load configuration from various
|
|
@@ -602,11 +645,11 @@ declare function processFilesForNode(paths: string[], options?: DeploymentOption
|
|
|
602
645
|
* ```
|
|
603
646
|
*/
|
|
604
647
|
declare class Ship extends Ship$1 {
|
|
605
|
-
#private;
|
|
606
648
|
constructor(options?: ShipClientOptions);
|
|
607
649
|
protected resolveInitialConfig(options: ShipClientOptions): ResolvedConfig;
|
|
608
650
|
protected loadFullConfig(): Promise<void>;
|
|
609
651
|
protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
|
|
652
|
+
protected getDeployBodyCreator(): DeployBodyCreator;
|
|
610
653
|
}
|
|
611
654
|
|
|
612
|
-
export { type ApiDeployOptions, ApiHttp, type
|
|
655
|
+
export { type ApiDeployOptions, ApiHttp, type ApiHttpOptions, type DeployBody, type DeployBodyCreator, type DeployFile, type DeploymentOptions, type DeploymentResourceContext, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ResourceContext, 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 as setPlatformConfig, validateFiles };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as _shipstatic_types from '@shipstatic/types';
|
|
2
|
-
import { ProgressInfo, PingResponse, ConfigResponse,
|
|
2
|
+
import { ProgressInfo, StaticFile, PingResponse, ConfigResponse, Deployment, DeploymentListResponse, Domain, DomainListResponse, DomainDnsResponse, DomainRecordsResponse, Account, TokenCreateResponse, TokenListResponse, ResolvedConfig, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource, ValidatableFile, FileValidationResult, ShipError } from '@shipstatic/types';
|
|
3
3
|
export * from '@shipstatic/types';
|
|
4
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
|
|
|
@@ -37,12 +37,25 @@ interface DeploymentOptions {
|
|
|
37
37
|
tags?: string[];
|
|
38
38
|
/** Callback for deploy progress with detailed statistics. */
|
|
39
39
|
onProgress?: (info: ProgressInfo) => void;
|
|
40
|
+
/** Client/tool identifier for this deployment (e.g., 'sdk', 'cli', 'web'). Alphanumeric only. */
|
|
41
|
+
via?: string;
|
|
42
|
+
/** Caller identifier for multi-tenant deployments (alphanumeric, dot, underscore, hyphen). */
|
|
43
|
+
caller?: string;
|
|
40
44
|
}
|
|
45
|
+
type ApiDeployOptions = Omit<DeploymentOptions, 'pathDetect'>;
|
|
41
46
|
/**
|
|
42
|
-
*
|
|
43
|
-
*
|
|
47
|
+
* Prepared request body for deployment.
|
|
48
|
+
* Created by platform-specific code, consumed by HTTP client.
|
|
44
49
|
*/
|
|
45
|
-
|
|
50
|
+
interface DeployBody {
|
|
51
|
+
body: FormData | ArrayBuffer;
|
|
52
|
+
headers: Record<string, string>;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Function that creates a deploy request body from files.
|
|
56
|
+
* Implemented differently for Node.js and Browser.
|
|
57
|
+
*/
|
|
58
|
+
type DeployBodyCreator = (files: StaticFile[], tags?: string[], via?: string) => Promise<DeployBody>;
|
|
46
59
|
/**
|
|
47
60
|
* Options for configuring a `Ship` instance.
|
|
48
61
|
* Sets default API host, authentication credentials, progress callbacks, concurrency, and timeouts for the client.
|
|
@@ -81,6 +94,11 @@ interface ShipClientOptions {
|
|
|
81
94
|
* to proceed with cookie-based credentials.
|
|
82
95
|
*/
|
|
83
96
|
useCredentials?: boolean | undefined;
|
|
97
|
+
/**
|
|
98
|
+
* Default caller identifier for multi-tenant deployments.
|
|
99
|
+
* Alphanumeric characters, dots, underscores, and hyphens allowed (max 128 chars).
|
|
100
|
+
*/
|
|
101
|
+
caller?: string | undefined;
|
|
84
102
|
}
|
|
85
103
|
/**
|
|
86
104
|
* Event map for Ship SDK events
|
|
@@ -136,23 +154,19 @@ declare class SimpleEvents {
|
|
|
136
154
|
}
|
|
137
155
|
|
|
138
156
|
/**
|
|
139
|
-
* @file HTTP client
|
|
140
|
-
* Clean, direct implementation with reliable error handling
|
|
157
|
+
* @file HTTP client for Ship API.
|
|
141
158
|
*/
|
|
142
159
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
* - Reliable error handling
|
|
148
|
-
*/
|
|
160
|
+
interface ApiHttpOptions extends ShipClientOptions {
|
|
161
|
+
getAuthHeaders: () => Record<string, string>;
|
|
162
|
+
createDeployBody: DeployBodyCreator;
|
|
163
|
+
}
|
|
149
164
|
declare class ApiHttp extends SimpleEvents {
|
|
150
165
|
private readonly apiUrl;
|
|
151
166
|
private readonly getAuthHeadersCallback;
|
|
152
167
|
private readonly timeout;
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
});
|
|
168
|
+
private readonly createDeployBody;
|
|
169
|
+
constructor(options: ApiHttpOptions);
|
|
156
170
|
/**
|
|
157
171
|
* Transfer events to another client (clean intentional API)
|
|
158
172
|
*/
|
|
@@ -201,7 +215,7 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
201
215
|
getDomain(name: string): Promise<Domain>;
|
|
202
216
|
listDomains(): Promise<DomainListResponse>;
|
|
203
217
|
removeDomain(name: string): Promise<void>;
|
|
204
|
-
|
|
218
|
+
verifyDomain(name: string): Promise<{
|
|
205
219
|
message: string;
|
|
206
220
|
}>;
|
|
207
221
|
getDomainDns(name: string): Promise<DomainDnsResponse>;
|
|
@@ -215,11 +229,6 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
215
229
|
listTokens(): Promise<TokenListResponse>;
|
|
216
230
|
removeToken(token: string): Promise<void>;
|
|
217
231
|
checkSPA(files: StaticFile[]): Promise<boolean>;
|
|
218
|
-
private validateFiles;
|
|
219
|
-
private prepareRequestPayload;
|
|
220
|
-
private createBrowserBody;
|
|
221
|
-
private createNodeBody;
|
|
222
|
-
private getBrowserContentType;
|
|
223
232
|
}
|
|
224
233
|
|
|
225
234
|
/**
|
|
@@ -234,8 +243,6 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
234
243
|
* This means CLI flags always win, followed by env vars, then config files.
|
|
235
244
|
*/
|
|
236
245
|
|
|
237
|
-
type Config = PlatformConfig;
|
|
238
|
-
|
|
239
246
|
/**
|
|
240
247
|
* Universal configuration resolver for all environments.
|
|
241
248
|
* This is the single source of truth for config resolution.
|
|
@@ -248,13 +255,28 @@ declare function resolveConfig(userOptions?: ShipClientOptions, loadedConfig?: P
|
|
|
248
255
|
declare function mergeDeployOptions(options: DeploymentOptions, clientDefaults: ShipClientOptions): DeploymentOptions;
|
|
249
256
|
|
|
250
257
|
/**
|
|
251
|
-
*
|
|
258
|
+
* Ship SDK resource factory functions.
|
|
252
259
|
*/
|
|
253
260
|
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
261
|
+
/**
|
|
262
|
+
* Shared context for all resource factories.
|
|
263
|
+
*/
|
|
264
|
+
interface ResourceContext {
|
|
265
|
+
getApi: () => ApiHttp;
|
|
266
|
+
ensureInit: () => Promise<void>;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Extended context for deployment resource.
|
|
270
|
+
*/
|
|
271
|
+
interface DeploymentResourceContext extends ResourceContext {
|
|
272
|
+
processInput: (input: DeployInput, options: DeploymentOptions) => Promise<StaticFile[]>;
|
|
273
|
+
clientDefaults?: ShipClientOptions;
|
|
274
|
+
hasAuth?: () => boolean;
|
|
275
|
+
}
|
|
276
|
+
declare function createDeploymentResource(ctx: DeploymentResourceContext): DeploymentResource;
|
|
277
|
+
declare function createDomainResource(ctx: ResourceContext): DomainResource;
|
|
278
|
+
declare function createAccountResource(ctx: ResourceContext): AccountResource;
|
|
279
|
+
declare function createTokenResource(ctx: ResourceContext): TokenResource;
|
|
258
280
|
|
|
259
281
|
/**
|
|
260
282
|
* Abstract base class for Ship SDK implementations.
|
|
@@ -277,6 +299,7 @@ declare abstract class Ship$1 {
|
|
|
277
299
|
protected abstract resolveInitialConfig(options: ShipClientOptions): ResolvedConfig;
|
|
278
300
|
protected abstract loadFullConfig(): Promise<void>;
|
|
279
301
|
protected abstract processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
|
|
302
|
+
protected abstract getDeployBodyCreator(): DeployBodyCreator;
|
|
280
303
|
/**
|
|
281
304
|
* Ensure full initialization is complete - called lazily by resources
|
|
282
305
|
*/
|
|
@@ -535,6 +558,26 @@ declare function getValidFiles<T extends ValidatableFile>(files: T[]): T[];
|
|
|
535
558
|
*/
|
|
536
559
|
declare function allValidFilesReady<T extends ValidatableFile>(files: T[]): boolean;
|
|
537
560
|
|
|
561
|
+
/**
|
|
562
|
+
* @file Error utilities for consistent error handling across SDK consumers.
|
|
563
|
+
*/
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* Ensure any error is wrapped as a ShipError.
|
|
567
|
+
* Useful for catch blocks where the error type is unknown.
|
|
568
|
+
*
|
|
569
|
+
* @example
|
|
570
|
+
* ```ts
|
|
571
|
+
* try {
|
|
572
|
+
* await someOperation();
|
|
573
|
+
* } catch (err) {
|
|
574
|
+
* const shipError = ensureShipError(err);
|
|
575
|
+
* // Now you can safely use shipError.message, shipError.type, etc.
|
|
576
|
+
* }
|
|
577
|
+
* ```
|
|
578
|
+
*/
|
|
579
|
+
declare function ensureShipError(err: unknown): ShipError;
|
|
580
|
+
|
|
538
581
|
/**
|
|
539
582
|
* @file Manages loading and validation of client configuration.
|
|
540
583
|
* This module uses `cosmiconfig` to find and load configuration from various
|
|
@@ -602,11 +645,11 @@ declare function processFilesForNode(paths: string[], options?: DeploymentOption
|
|
|
602
645
|
* ```
|
|
603
646
|
*/
|
|
604
647
|
declare class Ship extends Ship$1 {
|
|
605
|
-
#private;
|
|
606
648
|
constructor(options?: ShipClientOptions);
|
|
607
649
|
protected resolveInitialConfig(options: ShipClientOptions): ResolvedConfig;
|
|
608
650
|
protected loadFullConfig(): Promise<void>;
|
|
609
651
|
protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
|
|
652
|
+
protected getDeployBodyCreator(): DeployBodyCreator;
|
|
610
653
|
}
|
|
611
654
|
|
|
612
|
-
export { type ApiDeployOptions, ApiHttp, type
|
|
655
|
+
export { type ApiDeployOptions, ApiHttp, type ApiHttpOptions, type DeployBody, type DeployBodyCreator, type DeployFile, type DeploymentOptions, type DeploymentResourceContext, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ResourceContext, 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 as setPlatformConfig, validateFiles };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var be=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var P=(n,e)=>()=>(n&&(e=n(n=0)),e);var N=(n,e)=>{for(var t in e)be(n,t,{get:e[t],enumerable:!0})},Re=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Qe(e))!Ze.call(n,s)&&s!==t&&be(n,s,{get:()=>e[s],enumerable:!(i=Xe(e,s))||i.enumerable});return n},c=(n,e,t)=>(Re(n,e,"default"),t&&Re(t,e,"default"));var ke={};N(ke,{__setTestEnvironment:()=>H,getENV:()=>g});function H(n){fe=n}function et(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function g(){return fe||et()}var fe,F=P(()=>{"use strict";fe=null});import{ShipError as rt}from"@shipstatic/types";function z(n){ue=n}function b(){if(ue===null)throw rt.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 Oe={};N(Oe,{loadConfig:()=>L});import{z as j}from"zod";import{ShipError as he}from"@shipstatic/types";function $e(n){try{return at.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 lt(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 $e(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 lt(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return $e(i)}var de,at,oe=P(()=>{"use strict";F();de="ship",at=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 ft(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,p=()=>{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?p():t({md5:a.end()})},d.onerror=()=>{i(B.business("Failed to calculate MD5: FileReader error"))},p()})}async function mt(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 ft(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 mt(n)}throw B.business("Unknown or unsupported execution environment for MD5 calculation.")}var G=P(()=>{"use strict";F()});import{isJunk as dt}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(dt(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 Le(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=ht(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 ht(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 Be(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=Be(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()?Be(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=Le(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}),p=[],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:Ye}=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}`);p.push({path:T,content:q,size:q.length,md5:Ye})}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(p.length>l.maxFilesCount)throw I.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return p}var Ce=P(()=>{"use strict";F();G();re();$();le();ve()});import{ShipError as Ue}from"@shipstatic/types";async function Ke(n,e={}){let{getENV:t}=await Promise.resolve().then(()=>(F(),ke));if(t()!=="browser")throw Ue.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 Ue.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),p=new Set(d),w=[];for(let l of r){if(!p.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 qe=P(()=>{"use strict";G();re();le()});var We={};N(We,{convertBrowserInput:()=>Ge,convertDeployInput:()=>Dt,convertNodeInput:()=>Te});import{ShipError as C}from"@shipstatic/types";function He(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 je(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 Ve(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 Te(n,e={}){je(n,"node");let t=await Q(n,e);return Ve(t)}async function Ge(n,e={}){je(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 Ve(i)}async function Dt(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 Te([n],e);else if(Array.isArray(n)&&n.every(o=>typeof o=="string"))s=await Te(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=P(()=>{"use strict";F();Ce();qe();$()});var ee={};N(ee,{ApiHttp:()=>R,DEFAULT_API:()=>ye,ErrorType:()=>Ee,FILE_VALIDATION_STATUS:()=>h,JUNK_DIRECTORIES:()=>se,Ship:()=>Z,ShipError:()=>Fe,__setTestEnvironment:()=>H,allValidFilesReady:()=>Se,calculateMD5:()=>A,createAccountResource:()=>Y,createDeploymentResource:()=>W,createDomainResource:()=>J,createTokenResource:()=>X,default:()=>xe,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:()=>Ee,FILE_VALIDATION_STATUS:()=>h,JUNK_DIRECTORIES:()=>se,Ship:()=>Z,ShipError:()=>Fe,__setTestEnvironment:()=>H,allValidFilesReady:()=>Se,calculateMD5:()=>A,createAccountResource:()=>Y,createDeploymentResource:()=>W,createDomainResource:()=>J,createTokenResource:()=>X,default:()=>xe,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 Ae from"mime-db";var ce={};for(let n in Ae){let e=Ae[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 tt}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",Ie="/ping",k="/domains",nt="/config",it="/account",me="/tokens",ot="/spa-check",st=3e4,R=class extends ne{constructor(e){super(),this.apiUrl=e.apiUrl||tt,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??st}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 p=await fetch(e,d);clearTimeout(r),p.ok||await this.handleResponseError(p,i);let w=this.safeClone(p),l=this.safeClone(p);return this.emit("response",w,e),await this.parseResponse(l)}catch(p){throw clearTimeout(r),this.emit("error",p,e),this.handleFetchError(p,i),p}}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 p=await fetch(e,d);clearTimeout(r),p.ok||await this.handleResponseError(p,i);let w=this.safeClone(p),l=this.safeClone(p);return this.emit("response",w,e),{data:await this.parseResponse(l),status:p.status}}catch(p){throw clearTimeout(r),this.emit("error",p,e),this.handleFetchError(p,i),p}}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}${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}${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}${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 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),p=[];for await(let l of d.encode())p.push(Buffer.from(l));let w=Buffer.concat(p);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 ze}from"@shipstatic/types";F();import{DEFAULT_API as pt}from"@shipstatic/types";async function ct(n){let e=g();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(oe(),Oe));return t(n)}else return{}}function _(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||pt,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 Me}from"@shipstatic/types";async function ut(){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:Me,content:t,size:e.length,md5:i}}async function Ne(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===Me))return n;try{if(await e.checkSPA(n)){let s=await ut();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 p=await i(o,a);return p=await Ne(p,d,a),await d.deploy(p,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 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();oe();import{ShipError as Pe}from"@shipstatic/types";$();var f={};N(f,{ApiHttp:()=>R,DEFAULT_API:()=>ye,ErrorType:()=>Ee,FILE_VALIDATION_STATUS:()=>h,JUNK_DIRECTORIES:()=>se,Ship:()=>U,ShipError:()=>Fe,__setTestEnvironment:()=>H,allValidFilesReady:()=>Se,calculateMD5:()=>A,createAccountResource:()=>Y,createDeploymentResource:()=>W,createDomainResource:()=>J,createTokenResource:()=>X,filterJunk:()=>O,formatFileSize:()=>K,getENV:()=>g,getValidFiles:()=>pe,loadConfig:()=>ct,mergeDeployOptions:()=>V,optimizeDeployPaths:()=>M,pluralize:()=>ge,resolveConfig:()=>_,validateFiles:()=>De});var v={};c(v,Qt);import*as Qt from"@shipstatic/types";c(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 _e from"mime-db";var yt=new Set(Object.keys(_e)),gt=new Map(Object.entries(_e).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 vt(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 wt(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=gt.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?vt(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(p=>o.type.startsWith(p))?yt.has(o.type)?wt(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,ErrorType as Ee}from"@shipstatic/types";c(y,f);oe();$();$();Ce();F();var Z=class extends U{constructor(e={}){if(g()!=="node")throw Pe.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 Pe.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw Pe.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}},xe=Z;c(ee,y);export{R as ApiHttp,ye as DEFAULT_API,Ee as ErrorType,h as FILE_VALIDATION_STATUS,se as JUNK_DIRECTORIES,Z as Ship,Fe as ShipError,H as __setTestEnvironment,Se as allValidFilesReady,A as calculateMD5,Y as createAccountResource,W as createDeploymentResource,J as createDomainResource,X as createTokenResource,xe as default,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};
|
|
1
|
+
var Pe=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var Ge=Object.prototype.hasOwnProperty;var x=(n,e)=>()=>(n&&(e=n(n=0)),e);var _=(n,e)=>{for(var t in e)Pe(n,t,{get:e[t],enumerable:!0})},Ae=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of je(e))!Ge.call(n,r)&&r!==t&&Pe(n,r,{get:()=>e[r],enumerable:!(o=Ve(e,r))||o.enumerable});return n},p=(n,e,t)=>(Ae(n,e,"default"),t&&Ae(t,e,"default"));import{ShipError as Ze}from"@shipstatic/types";function L(n){ae=n}function I(){if(ae===null)throw Ze.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ae}var ae,U=x(()=>{"use strict";ae=null});function Z(n){pe=n}function et(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function C(){return pe||et()}var pe,P=x(()=>{"use strict";pe=null});var be={};_(be,{loadConfig:()=>k});import{z}from"zod";import{ShipError as ce}from"@shipstatic/types";function Ie(n){try{return tt.parse(n)}catch(e){if(e instanceof z.ZodError){let t=e.issues[0],o=t.path.length>0?` at ${t.path.join(".")}`:"";throw ce.config(`Configuration validation failed${o}: ${t.message}`)}throw ce.config("Configuration validation failed")}}async function nt(n){try{if(C()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),o=e(le,{searchPlaces:[`.${le}rc`,"package.json",`${t.homedir()}/.${le}rc`],stopDir:t.homedir()}),r;if(n?r=o.load(n):r=o.search(),r&&r.config)return Ie(r.config)}catch(e){if(e instanceof ce)throw e}return{}}async function k(n){if(C()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await nt(n),o={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Ie(o)}var le,tt,ee=x(()=>{"use strict";P();le="ship",tt=z.object({apiUrl:z.string().url().optional(),apiKey:z.string().optional(),deployToken:z.string().optional()}).strict()});import{ShipError as $}from"@shipstatic/types";async function rt(n){let e=(await import("spark-md5")).default;return new Promise((t,o)=>{let i=Math.ceil(n.size/2097152),s=0,a=new e.ArrayBuffer,f=new FileReader,c=()=>{let y=s*2097152,l=Math.min(y+2097152,n.size);f.readAsArrayBuffer(n.slice(y,l))};f.onload=y=>{let l=y.target?.result;if(!l){o($.business("Failed to read file chunk"));return}a.append(l),s++,s<i?c():t({md5:a.end()})},f.onerror=()=>{o($.business("Failed to calculate MD5: FileReader error"))},c()})}async function st(n){let e=await import("crypto");if(Buffer.isBuffer(n)){let o=e.createHash("md5");return o.update(n),{md5:o.digest("hex")}}let t=await import("fs");return new Promise((o,r)=>{let i=e.createHash("md5"),s=t.createReadStream(n);s.on("error",a=>r($.business(`Failed to read file for MD5: ${a.message}`))),s.on("data",a=>i.update(a)),s.on("end",()=>o({md5:i.digest("hex")}))})}async function b(n){let e=C();if(e==="browser"){if(!(n instanceof Blob))throw $.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return rt(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 st(n)}throw $.business("Unknown or unsupported execution environment for MD5 calculation.")}var te=x(()=>{"use strict";P()});import{isJunk as pt}from"junk";function G(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 o=t[t.length-1];if(pt(o))return!1;let r=t.slice(0,-1);for(let i of r)if(ne.some(s=>i.toLowerCase()===s.toLowerCase()))return!1;return!0})}var ne,de=x(()=>{"use strict";ne=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ue(n){if(!n||n.length===0)return"";let e=n.filter(i=>i&&typeof i=="string").map(i=>i.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(i=>i.split("/").filter(Boolean)),o=[],r=Math.min(...t.map(i=>i.length));for(let i=0;i<r;i++){let s=t[0][i];if(t.every(a=>a[i]===s))o.push(s);else break}return o.join("/")}function oe(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var he=x(()=>{"use strict"});function W(n,e={}){if(e.flatten===!1)return n.map(o=>({path:oe(o),name:ye(o)}));let t=lt(n);return n.map(o=>{let r=oe(o);if(t){let i=t.endsWith("/")?t:`${t}/`;r.startsWith(i)&&(r=r.substring(i.length))}return r||(r=ye(o)),{path:r,name:ye(o)}})}function lt(n){if(!n.length)return"";let t=n.map(i=>oe(i)).map(i=>i.split("/")),o=[],r=Math.min(...t.map(i=>i.length));for(let i=0;i<r-1;i++){let s=t[0][i];if(t.every(a=>a[i]===s))o.push(s);else break}return o.join("/")}function ye(n){return n.split(/[/\\]/).pop()||n}var ge=x(()=>{"use strict";he()});var qe={};_(qe,{processFilesForNode:()=>re});import{ShipError as F}from"@shipstatic/types";import*as E from"fs";import*as v from"path";function Ke(n,e=new Set){let t=[],o=E.realpathSync(n);if(e.has(o))return t;e.add(o);let r=E.readdirSync(n);for(let i of r){let s=v.join(n,i),a=E.statSync(s);if(a.isDirectory()){let f=Ke(s,e);t.push(...f)}else a.isFile()&&t.push(s)}return t}async function re(n,e={}){if(C()!=="node")throw F.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(h=>{let g=v.resolve(h);try{return E.statSync(g).isDirectory()?Ke(g):[g]}catch{throw F.file(`Path does not exist: ${h}`,h)}}),o=[...new Set(t)],r=G(o);if(r.length===0)return[];let i=n.map(h=>v.resolve(h)),s=Ue(i.map(h=>{try{return E.statSync(h).isDirectory()?h:v.dirname(h)}catch{return v.dirname(h)}})),a=r.map(h=>{if(s&&s.length>0){let g=v.relative(s,h);if(g&&typeof g=="string"&&!g.startsWith(".."))return g.replace(/\\/g,"/")}return v.basename(h)}),f=W(a,{flatten:e.pathDetect!==!1}),c=[],y=0,l=I();for(let h=0;h<r.length;h++){let g=r[h],S=f[h].path;try{let T=E.statSync(g);if(T.size===0)continue;if(T.size>l.maxFileSize)throw F.business(`File ${g} is too large. Maximum allowed size is ${l.maxFileSize/(1024*1024)}MB.`);if(y+=T.size,y>l.maxTotalSize)throw F.business(`Total deploy size is too large. Maximum allowed is ${l.maxTotalSize/(1024*1024)}MB.`);let B=E.readFileSync(g),{md5:He}=await b(B);if(S.includes("\0")||S.includes("/../")||S.startsWith("../")||S.endsWith("/.."))throw F.business(`Security error: Unsafe file path "${S}" for file: ${g}`);c.push({path:S,content:B,size:B.length,md5:He})}catch(T){if(T instanceof F)throw T;let B=T instanceof Error?T.message:String(T);throw F.file(`Failed to read file "${g}": ${B}`,g)}}if(c.length>l.maxFilesCount)throw F.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return c}var Re=x(()=>{"use strict";P();te();de();U();ge();he()});var J={};_(J,{ApiHttp:()=>R,DEFAULT_API:()=>fe,ErrorType:()=>Te,FILE_VALIDATION_STATUS:()=>m,JUNK_DIRECTORIES:()=>ne,Ship:()=>Y,ShipError:()=>Se,__setTestEnvironment:()=>Z,allValidFilesReady:()=>Ce,calculateMD5:()=>b,createAccountResource:()=>V,createDeploymentResource:()=>q,createDomainResource:()=>H,createTokenResource:()=>j,default:()=>we,ensureShipError:()=>Ee,filterJunk:()=>G,formatFileSize:()=>M,getCurrentConfig:()=>I,getENV:()=>C,getValidFiles:()=>ie,loadConfig:()=>k,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>W,pluralize:()=>me,processFilesForNode:()=>re,resolveConfig:()=>O,setPlatformConfig:()=>L,validateFiles:()=>De});var d={};_(d,{ApiHttp:()=>R,DEFAULT_API:()=>fe,ErrorType:()=>Te,FILE_VALIDATION_STATUS:()=>m,JUNK_DIRECTORIES:()=>ne,Ship:()=>Y,ShipError:()=>Se,__setTestEnvironment:()=>Z,allValidFilesReady:()=>Ce,calculateMD5:()=>b,createAccountResource:()=>V,createDeploymentResource:()=>q,createDomainResource:()=>H,createTokenResource:()=>j,default:()=>we,ensureShipError:()=>Ee,filterJunk:()=>G,formatFileSize:()=>M,getCurrentConfig:()=>I,getENV:()=>C,getValidFiles:()=>ie,loadConfig:()=>k,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>W,pluralize:()=>me,processFilesForNode:()=>re,resolveConfig:()=>O,setPlatformConfig:()=>L,validateFiles:()=>De});import{ShipError as w,DEFAULT_API as We}from"@shipstatic/types";var X=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 o=this.handlers.get(e);o&&(o.delete(t),o.size===0&&this.handlers.delete(e))}emit(e,...t){let o=this.handlers.get(e);if(!o)return;let r=Array.from(o);for(let i of r)try{i(...t)}catch(s){o.delete(i),e!=="error"&&setTimeout(()=>{s instanceof Error?this.emit("error",s,String(e)):this.emit("error",new Error(String(s)),String(e))},0)}}transfer(e){this.handlers.forEach((t,o)=>{t.forEach(r=>{e.on(o,r)})})}clear(){this.handlers.clear()}};var Q="/deployments",Fe="/ping",A="/domains",Ye="/config",Je="/account",se="/tokens",Xe="/spa-check",Qe=3e4,R=class extends X{constructor(e){super(),this.apiUrl=e.apiUrl||We,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Qe,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async request(e,t={},o){let r=this.getAuthHeaders(t.headers),i=new AbortController,s=setTimeout(()=>i.abort(),this.timeout),a=t.signal?this.combineSignals(t.signal,i.signal):i.signal,f={...t,headers:r,credentials:r.Authorization?void 0:"include",signal:a};this.emit("request",e,f);try{let c=await fetch(e,f);clearTimeout(s),c.ok||await this.handleResponseError(c,o);let y=this.safeClone(c),l=this.safeClone(c);return this.emit("response",y,e),await this.parseResponse(l)}catch(c){throw clearTimeout(s),this.emit("error",c,e),this.handleFetchError(c,o),c}}combineSignals(e,t){let o=new AbortController,r=()=>o.abort();return e.addEventListener("abort",r),t.addEventListener("abort",r),(e.aborted||t.aborted)&&o.abort(),o.signal}async requestWithStatus(e,t={},o){let r=this.getAuthHeaders(t.headers),i=new AbortController,s=setTimeout(()=>i.abort(),this.timeout),a=t.signal?this.combineSignals(t.signal,i.signal):i.signal,f={...t,headers:r,credentials:r.Authorization?void 0:"include",signal:a};this.emit("request",e,f);try{let c=await fetch(e,f);clearTimeout(s),c.ok||await this.handleResponseError(c,o);let y=this.safeClone(c),l=this.safeClone(c);return this.emit("response",y,e),{data:await this.parseResponse(l),status:c.status}}catch(c){throw clearTimeout(s),this.emit("error",c,e),this.handleFetchError(c,o),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 o={};try{e.headers.get("content-type")?.includes("application/json")?o=await e.json():o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}let r=o.message||o.error||`${t} failed due to API error`;throw e.status===401?w.authentication(r):w.api(r,e.status,o.code,o)}handleFetchError(e,t){throw e.name==="AbortError"?w.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?w.network(`${t} failed due to network error: ${e.message}`,e):e instanceof w?e:w.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${Fe}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${Fe}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${Ye}`,{method:"GET"},"Config")}async deploy(e,t={}){if(!e.length)throw w.business("No files to deploy.");for(let a of e)if(!a.md5)throw w.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:o,headers:r}=await this.createDeployBody(e,t.tags,t.via),i={};t.deployToken?i.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(i.Authorization=`Bearer ${t.apiKey}`),t.caller&&(i["X-Caller"]=t.caller);let s={method:"POST",body:o,headers:{...r,...i},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${Q}`,s,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${Q}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${Q}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${Q}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,t,o){let r={};t&&(r.deployment=t),o&&o.length>0&&(r.tags=o);let i=`${this.apiUrl}${A}/${encodeURIComponent(e)}`,{data:s,status:a}=await this.requestWithStatus(i,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"Set Domain");return{...s,isCreate:a===201}}async getDomain(e){return await this.request(`${this.apiUrl}${A}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${A}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${A}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async verifyDomain(e){return await this.request(`${this.apiUrl}${A}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${A}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${A}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${A}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${Je}`,{method:"GET"},"Get Account")}async createToken(e,t){let o={};return e!==void 0&&(o.ttl=e),t&&t.length>0&&(o.tags=t),await this.request(`${this.apiUrl}${se}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${se}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${se}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}async checkSPA(e){let t=e.find(s=>s.path==="index.html"||s.path==="/index.html");if(!t||t.size>100*1024)return!1;let o;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))o=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)o=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)o=await t.content.text();else return!1;let r={files:e.map(s=>s.path),index:o};return(await this.request(`${this.apiUrl}${Xe}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"SPA Check")).isSPA}};U();import{ShipError as Ne}from"@shipstatic/types";import{ShipError as $e}from"@shipstatic/types";P();import{DEFAULT_API as ot}from"@shipstatic/types";async function it(n){let e=C();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(ee(),be));return t(n)}else return{}}function O(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||ot,apiKey:n.apiKey!==void 0?n.apiKey:e.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:e.deployToken},o={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(o.apiKey=t.apiKey),t.deployToken!==void 0&&(o.deployToken=t.deployToken),o}function K(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.caller===void 0&&e.caller!==void 0&&(t.caller=e.caller),t}te();import{DEPLOYMENT_CONFIG_FILENAME as ke}from"@shipstatic/types";async function at(){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:o}=await b(t);return{path:ke,content:t,size:e.length,md5:o}}async function Oe(n,e,t){if(t.spaDetect===!1||n.some(o=>o.path===ke))return n;try{if(await e.checkSPA(n)){let r=await at();return[...n,r]}}catch{}return n}function q(n){let{getApi:e,ensureInit:t,processInput:o,clientDefaults:r,hasAuth:i}=n;return{create:async(s,a={})=>{await t();let f=r?K(a,r):a;if(i&&!i()&&!f.deployToken&&!f.apiKey)throw $e.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!o)throw $e.config("processInput function is not provided.");let c=e(),y=await o(s,f);return y=await Oe(y,c,f),c.deploy(y,f)},list:async()=>(await t(),e().listDeployments()),remove:async s=>{await t(),await e().removeDeployment(s)},get:async s=>(await t(),e().getDeployment(s))}}function H(n){let{getApi:e,ensureInit:t}=n;return{set:async(o,r,i)=>(await t(),e().setDomain(o,r,i)),get:async o=>(await t(),e().getDomain(o)),list:async()=>(await t(),e().listDomains()),remove:async o=>{await t(),await e().removeDomain(o)},verify:async o=>(await t(),e().verifyDomain(o)),dns:async o=>(await t(),e().getDomainDns(o)),records:async o=>(await t(),e().getDomainRecords(o)),share:async o=>(await t(),e().getDomainShare(o))}}function V(n){let{getApi:e,ensureInit:t}=n;return{get:async()=>(await t(),e().getAccount())}}function j(n){let{getApi:e,ensureInit:t}=n;return{create:async(o,r)=>(await t(),e().createToken(o,r)),list:async()=>(await t(),e().listTokens()),remove:async o=>{await t(),await e().removeToken(o)}}}var N=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,createDeployBody:this.getDeployBodyCreator()});let o={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=q({...o,processInput:(r,i)=>this.processInput(r,i),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=H(o),this._account=V(o),this._tokens=j(o)}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=I(),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 Ne.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 Ne.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();ee();import{ShipError as xe}from"@shipstatic/types";U();import{ShipError as _e}from"@shipstatic/types";import Me from"mime-db";var ue={};for(let n in Me){let e=Me[n];e&&e.extensions&&e.extensions.forEach(t=>{ue[t]||(ue[t]=n)})}function Be(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return ue[e]||"application/octet-stream"}async function Le(n,e,t){let{FormData:o,File:r}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),s=new o,a=[];for(let l of n){let h=Be(l.path),g;if(Buffer.isBuffer(l.content))g=new r([l.content],l.path,{type:h});else if(typeof Blob<"u"&&l.content instanceof Blob)g=new r([l.content],l.path,{type:h});else throw _e.file(`Unsupported file.content type for Node.js: ${l.path}`,l.path);if(!l.md5)throw _e.file(`File missing md5 checksum: ${l.path}`,l.path);let S=l.path.startsWith("/")?l.path:"/"+l.path;s.append("files[]",g,S),a.push(l.md5)}s.append("checksums",JSON.stringify(a)),e&&e.length>0&&s.append("tags",JSON.stringify(e)),t&&s.append("via",t);let f=new i(s),c=[];for await(let l of f.encode())c.push(Buffer.from(l));let y=Buffer.concat(c);return{body:y.buffer.slice(y.byteOffset,y.byteOffset+y.byteLength),headers:{"Content-Type":f.contentType,"Content-Length":Buffer.byteLength(y).toString()}}}var u={};_(u,{ApiHttp:()=>R,DEFAULT_API:()=>fe,ErrorType:()=>Te,FILE_VALIDATION_STATUS:()=>m,JUNK_DIRECTORIES:()=>ne,Ship:()=>N,ShipError:()=>Se,__setTestEnvironment:()=>Z,allValidFilesReady:()=>Ce,calculateMD5:()=>b,createAccountResource:()=>V,createDeploymentResource:()=>q,createDomainResource:()=>H,createTokenResource:()=>j,ensureShipError:()=>Ee,filterJunk:()=>G,formatFileSize:()=>M,getENV:()=>C,getValidFiles:()=>ie,loadConfig:()=>it,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>W,pluralize:()=>me,resolveConfig:()=>O,validateFiles:()=>De});var D={};p(D,Jt);import*as Jt from"@shipstatic/types";p(u,D);import{DEFAULT_API as fe}from"@shipstatic/types";te();function me(n,e,t,o=!0){let r=n===1?e:t;return o?`${n} ${r}`:r}de();ge();P();import{FileValidationStatus as m}from"@shipstatic/types";import ze from"mime-db";var ct=new Set(Object.keys(ze)),ut=new Map(Object.entries(ze).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)]));var ft=[[/File name cannot|Invalid file name|File name contains|File name uses|traversal/i,"Invalid File Name"],[/File size must be positive/i,"Invalid File Size"],[/MIME type is required/i,"Missing MIME Type"],[/Invalid MIME type/i,"Invalid MIME Type"],[/not allowed/i,"Invalid File Type"],[/extension does not match/i,"Extension Mismatch"],[/Total size/i,"Total Size Exceeded"],[/exceeds limit/i,"File Too Large"]];function mt(n,e){if(n===m.PROCESSING_ERROR)return"Processing Error";if(n===m.EMPTY_FILE)return"Empty File";if(!e)return"Validation Failed";for(let[t,o]of ft)if(t.test(e))return o;return"Validation Failed"}function M(n,e=1){if(n===0)return"0 Bytes";let t=1024,o=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,r)).toFixed(e))+" "+o[r]}function dt(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,o=n.split("/").pop()||n;return t.test(o)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function ht(n,e){if(n.startsWith("."))return!0;let t=n.toLowerCase().split(".");if(t.length>1&&t[t.length-1]){let o=t[t.length-1],r=ut.get(e);if(r&&!r.has(o))return!1}return!0}function De(n,e){let t=[],o=[];if(n.length===0){let i="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:i,errors:[i],isClientError:!0}}}if(n.length>e.maxFilesCount){let i=`Number of files (${n.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:n.map(s=>({...s,status:m.VALIDATION_FAILED,statusMessage:i})),validFiles:[],error:{error:"File Count Exceeded",details:i,errors:[i],isClientError:!0}}}let r=0;for(let i of n){let s=m.READY,a="Ready for upload",f=i.name?dt(i.name):{valid:!1,reason:"File name cannot be empty"};i.status===m.PROCESSING_ERROR?(s=m.PROCESSING_ERROR,a=i.statusMessage||"A file failed during processing.",t.push(`${i.name}: ${a}`)):!i.name||i.name.trim().length===0?(s=m.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${i.name||"(empty)"}: ${a}`)):i.name.includes("\0")?(s=m.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push(`${i.name}: ${a}`)):f.valid?i.size<=0?(s=m.EMPTY_FILE,a=i.size===0?"File is empty (0 bytes)":"File size must be positive",t.push(`${i.name}: ${a}`)):!i.type||i.type.trim().length===0?(s=m.VALIDATION_FAILED,a="File MIME type is required",t.push(`${i.name}: ${a}`)):e.allowedMimeTypes.some(c=>i.type.startsWith(c))?ct.has(i.type)?ht(i.name,i.type)?i.size>e.maxFileSize?(s=m.VALIDATION_FAILED,a=`File size (${M(i.size)}) exceeds limit of ${M(e.maxFileSize)}`,t.push(`${i.name}: ${a}`)):(r+=i.size,r>e.maxTotalSize&&(s=m.VALIDATION_FAILED,a=`Total size would exceed limit of ${M(e.maxTotalSize)}`,t.push(`${i.name}: ${a}`))):(s=m.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${i.name}: ${a}`)):(s=m.VALIDATION_FAILED,a=`Invalid MIME type "${i.type}"`,t.push(`${i.name}: ${a}`)):(s=m.VALIDATION_FAILED,a=`File type "${i.type}" is not allowed`,t.push(`${i.name}: ${a}`)):(s=m.VALIDATION_FAILED,a=f.reason||"Invalid file name",t.push(`${i.name}: ${a}`)),o.push({...i,status:s,statusMessage:a})}if(t.length>0){let i=o.find(a=>a.status!==m.READY&&a.status!==m.PENDING),s=mt(i?.status,i?.statusMessage);return{files:o.map(a=>({...a,status:m.VALIDATION_FAILED})),validFiles:[],error:{error:s,details:t.length===1?t[0]:`${t.length} file(s) failed validation`,errors:t,isClientError:!0}}}return{files:o,validFiles:o,error:null}}function ie(n){return n.filter(e=>e.status===m.READY)}function Ce(n){return ie(n).length>0}import{ShipError as ve}from"@shipstatic/types";function Ee(n){return n instanceof ve?n:n instanceof Error?ve.business(n.message):ve.business(String(n??"Unknown error"))}import{ShipError as Se,ErrorType as Te}from"@shipstatic/types";p(d,u);ee();U();Re();P();var Y=class extends N{constructor(e={}){if(C()!=="node")throw xe.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return O(e,{})}async loadFullConfig(){try{let e=await k(this.clientOptions.configFile),t=O(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let o=new R({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(o);let r=await this.http.getConfig();L(r)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){let o=typeof e=="string"?[e]:e;if(!Array.isArray(o)||!o.every(i=>typeof i=="string"))throw xe.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw xe.business("No files to deploy.");let{processFilesForNode:r}=await Promise.resolve().then(()=>(Re(),qe));return r(o,t)}getDeployBodyCreator(){return Le}},we=Y;p(J,d);export{R as ApiHttp,fe as DEFAULT_API,Te as ErrorType,m as FILE_VALIDATION_STATUS,ne as JUNK_DIRECTORIES,Y as Ship,Se as ShipError,Z as __setTestEnvironment,Ce as allValidFilesReady,b as calculateMD5,V as createAccountResource,q as createDeploymentResource,H as createDomainResource,j as createTokenResource,we as default,Ee as ensureShipError,G as filterJunk,M as formatFileSize,I as getCurrentConfig,C as getENV,ie as getValidFiles,k as loadConfig,K as mergeDeployOptions,W as optimizeDeployPaths,me as pluralize,re as processFilesForNode,O as resolveConfig,L as setPlatformConfig,De as validateFiles};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|