@shipstatic/ship 0.1.25 → 0.2.0

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.
@@ -0,0 +1,454 @@
1
+ import * as _shipstatic_types from '@shipstatic/types';
2
+ import { PingResponse, ConfigResponse, StaticFile, Deployment, DeploymentListResponse, Alias, AliasListResponse, Account, DeployInput, DeploymentResource, AliasResource, AccountResource, KeysResource, PlatformConfig } from '@shipstatic/types';
3
+ export * from '@shipstatic/types';
4
+ export { Account, Alias, DEFAULT_API, DeployInput, Deployment, PingResponse, ShipError, ShipErrorType } from '@shipstatic/types';
5
+
6
+ /**
7
+ * @file SDK-specific type definitions
8
+ * Consolidates all Ship SDK types into a single file for clarity.
9
+ * Core types come from @shipstatic/types, while SDK-specific types are defined here.
10
+ */
11
+
12
+ /**
13
+ * Universal deploy options for both Node.js and Browser environments
14
+ */
15
+ interface DeploymentOptions {
16
+ /** The API URL to use for this specific deploy. Overrides client's default. */
17
+ apiUrl?: string;
18
+ /** An AbortSignal to allow cancellation of the deploy operation. */
19
+ signal?: AbortSignal;
20
+ /** An optional subdomain to suggest for the deployment. Availability is subject to the API. */
21
+ subdomain?: string;
22
+ /** Callback invoked if the deploy is cancelled via the AbortSignal. */
23
+ onCancel?: () => void;
24
+ /** Maximum number of concurrent operations. */
25
+ maxConcurrency?: number;
26
+ /** Timeout in milliseconds for the deploy request. */
27
+ timeout?: number;
28
+ /** API key for this specific deploy. Overrides client's default. */
29
+ apiKey?: string;
30
+ /** Deploy token for this specific deploy. Overrides client's default. */
31
+ deployToken?: string;
32
+ /** Whether to auto-detect and optimize file paths by flattening common directories. Defaults to true. */
33
+ pathDetect?: boolean;
34
+ /** Whether to auto-detect SPAs and generate ship.json configuration. Defaults to true. */
35
+ spaDetect?: boolean;
36
+ /** Callback for overall deploy progress (0-100). */
37
+ onProgress?: (progress: number) => void;
38
+ /** Callback for detailed progress statistics. */
39
+ onProgressStats?: (progressStats: ProgressStats) => void;
40
+ }
41
+ /**
42
+ * Options for configuring an deploy operation via `apiClient.deployFiles`.
43
+ * Derived from DeploymentOptions but excludes client-side only options.
44
+ */
45
+ type ApiDeployOptions = Omit<DeploymentOptions, 'pathDetect'>;
46
+ /**
47
+ * Detailed statistics about the progress of an deploy operation.
48
+ */
49
+ interface ProgressStats {
50
+ /** The number of bytes loaded so far. */
51
+ loaded: number;
52
+ /** The total number of bytes to be loaded. May be 0 if unknown initially. */
53
+ total: number;
54
+ /** The progress as a fraction (loaded/total). Value is between 0 and 1. */
55
+ progress: number;
56
+ /** Optional identifier for the file this progress pertains to, if applicable. */
57
+ file?: string;
58
+ }
59
+ /**
60
+ * Options for configuring a `Ship` instance.
61
+ * Sets default API host, authentication credentials, progress callbacks, concurrency, and timeouts for the client.
62
+ */
63
+ interface ShipClientOptions {
64
+ /** Default API URL for the client instance. */
65
+ apiUrl?: string | undefined;
66
+ /** API key for authenticated deployments. */
67
+ apiKey?: string | undefined;
68
+ /** Deploy token for single-use deployments. */
69
+ deployToken?: string | undefined;
70
+ /** Path to custom config file. */
71
+ configFile?: string | undefined;
72
+ /**
73
+ * Default callback for overall deploy progress for deploys made with this client.
74
+ * @param progress - A number between 0 and 100.
75
+ */
76
+ onProgress?: ((progress: number) => void) | undefined;
77
+ /**
78
+ * Default callback for detailed progress statistics for deploys made with this client.
79
+ * @param progressStats - Progress statistics object.
80
+ */
81
+ onProgressStats?: ((progressStats: ProgressStats) => void) | undefined;
82
+ /**
83
+ * Default for maximum concurrent deploys.
84
+ * Used if an deploy operation doesn't specify its own `maxConcurrency`.
85
+ * Defaults to 4 if not set here or in the specific deploy call.
86
+ */
87
+ maxConcurrency?: number | undefined;
88
+ /**
89
+ * Default timeout in milliseconds for API requests made by this client instance.
90
+ * Used if an deploy operation doesn't specify its own timeout.
91
+ */
92
+ timeout?: number | undefined;
93
+ }
94
+
95
+ /**
96
+ * Handles direct HTTP communication with the Ship API, including deploys and health checks.
97
+ * Responsible for constructing requests, managing authentication, and error translation.
98
+ * @internal
99
+ */
100
+ declare class ApiHttp {
101
+ #private;
102
+ private readonly apiUrl;
103
+ private readonly apiKey;
104
+ private readonly deployToken;
105
+ /**
106
+ * Constructs a new ApiHttp instance with the provided client options.
107
+ * @param options - Client options including API host, authentication credentials, and timeout settings.
108
+ */
109
+ constructor(options: ShipClientOptions);
110
+ /**
111
+ * Sends a ping request to the Ship API server to verify connectivity and authentication.
112
+ * @returns Promise resolving to `true` if the ping is successful, `false` otherwise.
113
+ * @throws {ShipApiError} If the API returns an error response (4xx, 5xx).
114
+ * @throws {ShipNetworkError} If a network error occurs (e.g., DNS failure, connection refused).
115
+ */
116
+ ping(): Promise<boolean>;
117
+ /**
118
+ * Get full ping response from the API server
119
+ * @returns Promise resolving to the full PingResponse object.
120
+ */
121
+ getPingResponse(): Promise<PingResponse>;
122
+ /**
123
+ * Fetches platform configuration from the API.
124
+ * @returns Promise resolving to the config response.
125
+ * @throws {ShipError} If the config request fails.
126
+ */
127
+ getConfig(): Promise<ConfigResponse>;
128
+ /**
129
+ * Deploys an array of StaticFile objects to the Ship API.
130
+ * Constructs and sends a multipart/form-data POST request, handling both browser and Node.js environments.
131
+ * Validates files and manages deploy progress and error translation.
132
+ * @param files - Array of StaticFile objects to deploy (must include MD5 checksums).
133
+ * @param options - Optional per-deploy configuration (overrides instance defaults).
134
+ * @returns Promise resolving to a full Deployment object on success.
135
+ * @throws {ShipFileError} If a file is missing an MD5 checksum or content type is unsupported.
136
+ * @throws {ShipClientError} If no files are provided or if environment is unknown.
137
+ * @throws {ShipNetworkError} If a network error occurs during deploy.
138
+ * @throws {ShipApiError} If the API returns an error response.
139
+ * @throws {ShipCancelledError} If the deploy is cancelled via an AbortSignal.
140
+ */
141
+ deploy(files: StaticFile[], options?: ApiDeployOptions): Promise<Deployment>;
142
+ /**
143
+ * Lists all deployments for the authenticated account
144
+ * @returns Promise resolving to deployment list response
145
+ */
146
+ listDeployments(): Promise<DeploymentListResponse>;
147
+ /**
148
+ * Gets a specific deployment by ID
149
+ * @param id - Deployment ID to retrieve
150
+ * @returns Promise resolving to deployment details
151
+ */
152
+ getDeployment(id: string): Promise<Deployment>;
153
+ /**
154
+ * Removes a deployment by ID
155
+ * @param id - Deployment ID to remove
156
+ * @returns Promise resolving when removal is complete
157
+ */
158
+ removeDeployment(id: string): Promise<void>;
159
+ /**
160
+ * Sets an alias (create or update)
161
+ * @param name - Alias name
162
+ * @param deployment - Deployment name to point to
163
+ * @returns Promise resolving to the created/updated alias with operation context
164
+ */
165
+ setAlias(name: string, deployment: string): Promise<_shipstatic_types.Alias>;
166
+ /**
167
+ * Gets a specific alias by name
168
+ * @param name - Alias name to retrieve
169
+ * @returns Promise resolving to alias details
170
+ */
171
+ getAlias(name: string): Promise<Alias>;
172
+ /**
173
+ * Lists all aliases for the authenticated account
174
+ * @returns Promise resolving to alias list response
175
+ */
176
+ listAliases(): Promise<AliasListResponse>;
177
+ /**
178
+ * Removes an alias by name
179
+ * @param name - Alias name to remove
180
+ * @returns Promise resolving to removal confirmation
181
+ */
182
+ removeAlias(name: string): Promise<void>;
183
+ /**
184
+ * Triggers a manual DNS check for an external alias
185
+ * @param name - Alias name to check DNS for
186
+ * @returns Promise resolving to confirmation message
187
+ */
188
+ checkAlias(name: string): Promise<{
189
+ message: string;
190
+ }>;
191
+ /**
192
+ * Gets account details for the authenticated user
193
+ * @returns Promise resolving to account details
194
+ */
195
+ getAccount(): Promise<Account>;
196
+ /**
197
+ * Creates a new API key for the authenticated user
198
+ * @returns Promise resolving to the new API key
199
+ */
200
+ createApiKey(): Promise<{
201
+ apiKey: string;
202
+ }>;
203
+ /**
204
+ * Checks if files represent a SPA structure using AI analysis
205
+ * @param files - Array of StaticFile objects to analyze
206
+ * @returns Promise resolving to boolean indicating if it's a SPA
207
+ */
208
+ checkSPA(files: StaticFile[]): Promise<boolean>;
209
+ }
210
+
211
+ /**
212
+ * @file All Ship SDK resources in one place - impossibly simple.
213
+ */
214
+
215
+ declare function createDeploymentResource(getApi: () => ApiHttp, clientDefaults?: ShipClientOptions, ensureInit?: () => Promise<void>, processInput?: (input: DeployInput, options: DeploymentOptions) => Promise<StaticFile[]>): DeploymentResource;
216
+ declare function createAliasResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): AliasResource;
217
+ declare function createAccountResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): AccountResource;
218
+ declare function createKeysResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): KeysResource;
219
+
220
+ /**
221
+ * Abstract base class for Ship SDK implementations.
222
+ *
223
+ * Provides shared functionality while allowing environment-specific
224
+ * implementations to handle configuration loading and deployment processing.
225
+ */
226
+ declare abstract class Ship$1 {
227
+ protected http: ApiHttp;
228
+ protected readonly clientOptions: ShipClientOptions;
229
+ protected initPromise: Promise<void> | null;
230
+ protected _deployments: DeploymentResource;
231
+ protected _aliases: AliasResource;
232
+ protected _account: AccountResource;
233
+ protected _keys: KeysResource;
234
+ constructor(options?: ShipClientOptions);
235
+ protected abstract resolveInitialConfig(options: ShipClientOptions): any;
236
+ protected abstract loadFullConfig(): Promise<void>;
237
+ protected abstract processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
238
+ /**
239
+ * Ensure full initialization is complete - called lazily by resources
240
+ */
241
+ protected ensureInitialized(): Promise<void>;
242
+ /**
243
+ * Ping the API server to check connectivity
244
+ */
245
+ ping(): Promise<boolean>;
246
+ /**
247
+ * Deploy project (convenience shortcut to ship.deployments.create())
248
+ */
249
+ deploy(input: DeployInput, options?: DeploymentOptions): Promise<Deployment>;
250
+ /**
251
+ * Get current account information (convenience shortcut to ship.account.get())
252
+ */
253
+ whoami(): Promise<_shipstatic_types.Account>;
254
+ /**
255
+ * Get deployments resource (environment-specific)
256
+ */
257
+ get deployments(): DeploymentResource;
258
+ /**
259
+ * Get aliases resource
260
+ */
261
+ get aliases(): AliasResource;
262
+ /**
263
+ * Get account resource
264
+ */
265
+ get account(): AccountResource;
266
+ /**
267
+ * Get keys resource
268
+ */
269
+ get keys(): KeysResource;
270
+ }
271
+
272
+ /**
273
+ * @file Shared configuration logic for both environments.
274
+ */
275
+
276
+ type Config = PlatformConfig;
277
+ /**
278
+ * Universal configuration resolver for all environments.
279
+ * This is the single source of truth for config resolution.
280
+ */
281
+ declare function resolveConfig(userOptions?: ShipClientOptions, loadedConfig?: Partial<ShipClientOptions>): {
282
+ apiUrl: string;
283
+ apiKey?: string;
284
+ deployToken?: string;
285
+ };
286
+ /**
287
+ * Merge deployment options with client defaults.
288
+ * This is shared logic used by both environments.
289
+ */
290
+ declare function mergeDeployOptions(options: DeploymentOptions, clientDefaults: ShipClientOptions): DeploymentOptions;
291
+
292
+ interface MD5Result {
293
+ md5: string;
294
+ }
295
+ /**
296
+ * Unified MD5 calculation that delegates to environment-specific handlers
297
+ */
298
+ declare function calculateMD5(input: Blob | Buffer | string): Promise<MD5Result>;
299
+
300
+ /**
301
+ * Utility functions for string manipulation.
302
+ */
303
+ /**
304
+ * Simple utility to pluralize a word based on a count.
305
+ * @param count The number to determine pluralization.
306
+ * @param singular The singular form of the word.
307
+ * @param plural The plural form of the word.
308
+ * @param includeCount Whether to include the count in the returned string. Defaults to true.
309
+ * @returns A string with the count and the correctly pluralized word.
310
+ */
311
+ declare function pluralize(count: number, singular: string, plural: string, includeCount?: boolean): string;
312
+
313
+ /**
314
+ * List of directory names considered as junk
315
+ *
316
+ * Files within these directories (at any level in the path hierarchy) will be excluded.
317
+ * The comparison is case-insensitive for cross-platform compatibility.
318
+ *
319
+ * @internal
320
+ */
321
+ declare const JUNK_DIRECTORIES: readonly ["__MACOSX", ".Trashes", ".fseventsd", ".Spotlight-V100"];
322
+ /**
323
+ * Filters an array of file paths, removing those considered junk
324
+ *
325
+ * A path is filtered out if either:
326
+ * 1. The basename is identified as junk by the 'junk' package (e.g., .DS_Store, Thumbs.db)
327
+ * 2. Any directory segment in the path matches an entry in JUNK_DIRECTORIES (case-insensitive)
328
+ *
329
+ * All path separators are normalized to forward slashes for consistent cross-platform behavior.
330
+ *
331
+ * @param filePaths - An array of file path strings to filter
332
+ * @returns A new array containing only non-junk file paths
333
+ */
334
+ declare function filterJunk(filePaths: string[]): string[];
335
+
336
+ /**
337
+ * @file Deploy path optimization - the core logic that makes Ship deployments clean and intuitive.
338
+ * Automatically strips common parent directories to create clean deployment URLs.
339
+ */
340
+ /**
341
+ * Represents a file ready for deployment with its optimized path
342
+ */
343
+ interface DeployFile {
344
+ /** The clean deployment path (e.g., "assets/style.css") */
345
+ path: string;
346
+ /** Original filename */
347
+ name: string;
348
+ }
349
+ /**
350
+ * Core path optimization logic.
351
+ * Transforms messy local paths into clean deployment paths.
352
+ *
353
+ * @example
354
+ * Input: ["dist/index.html", "dist/assets/app.js"]
355
+ * Output: ["index.html", "assets/app.js"]
356
+ *
357
+ * @param filePaths - Raw file paths from the local filesystem
358
+ * @param options - Path processing options
359
+ */
360
+ declare function optimizeDeployPaths(filePaths: string[], options?: {
361
+ flatten?: boolean;
362
+ }): DeployFile[];
363
+
364
+ /**
365
+ * @file Environment detection utilities for the Ship SDK.
366
+ * Helps in determining whether the SDK is running in a Node.js, browser, or unknown environment.
367
+ */
368
+ /**
369
+ * Represents the detected or simulated JavaScript execution environment.
370
+ */
371
+ type ExecutionEnvironment = 'browser' | 'node' | 'unknown';
372
+ /**
373
+ * **FOR TESTING PURPOSES ONLY.**
374
+ *
375
+ * Allows tests to override the detected environment, forcing the SDK to behave
376
+ * as if it's running in the specified environment.
377
+ *
378
+ * @param env - The environment to simulate ('node', 'browser', 'unknown'),
379
+ * or `null` to clear the override and revert to actual environment detection.
380
+ * @internal
381
+ */
382
+ declare function __setTestEnvironment(env: ExecutionEnvironment | null): void;
383
+ /**
384
+ * Gets the current effective execution environment.
385
+ *
386
+ * This function first checks if a test environment override is active via {@link __setTestEnvironment}.
387
+ * If not, it detects the actual environment (Node.js, browser, or unknown).
388
+ *
389
+ * @returns The current execution environment: 'browser', 'node', or 'unknown'.
390
+ * @public
391
+ */
392
+ declare function getENV(): ExecutionEnvironment;
393
+
394
+ /**
395
+ * @file Browser configuration implementation - no file system access.
396
+ */
397
+
398
+ /**
399
+ * Browser config loading - only uses provided options.
400
+ */
401
+ declare function loadConfig(configFile?: string): Promise<Config>;
402
+ /**
403
+ * Set platform config in browser.
404
+ */
405
+ declare function setConfig(config: any): void;
406
+
407
+ /**
408
+ * @file Browser-specific file utilities for the Ship SDK.
409
+ * Provides helpers for processing browser files into deploy-ready objects and extracting common directory info.
410
+ */
411
+
412
+ /**
413
+ * Processes browser files (FileList or File[]) into an array of StaticFile objects ready for deploy.
414
+ * Calculates MD5, filters junk files, and applies automatic path optimization.
415
+ *
416
+ * @param browserFiles - FileList or File[] to process for deploy.
417
+ * @param options - Processing options including pathDetect for automatic path optimization.
418
+ * @returns Promise resolving to an array of StaticFile objects.
419
+ * @throws {ShipClientError} If called outside a browser or with invalid input.
420
+ */
421
+ declare function processFilesForBrowser(browserFiles: FileList | File[], options?: DeploymentOptions): Promise<StaticFile[]>;
422
+
423
+ /**
424
+ * @file Ship SDK for browser environments with streamlined configuration.
425
+ */
426
+
427
+ /**
428
+ * Ship SDK Client for browser environments.
429
+ *
430
+ * Optimized for browser compatibility with no Node.js dependencies.
431
+ * Configuration is provided explicitly through constructor options.
432
+ *
433
+ * @example
434
+ * ```typescript
435
+ * // Deploy with token obtained from server
436
+ * const ship = new Ship({
437
+ * deployToken: "token-xxxx",
438
+ * apiUrl: "https://api.shipstatic.dev"
439
+ * });
440
+ *
441
+ * // Deploy files from input element
442
+ * const files = fileInput.files;
443
+ * await ship.deploy(files);
444
+ * ```
445
+ */
446
+ declare class Ship extends Ship$1 {
447
+ #private;
448
+ constructor(options?: ShipClientOptions);
449
+ protected resolveInitialConfig(options: ShipClientOptions): any;
450
+ protected loadFullConfig(): Promise<void>;
451
+ protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
452
+ }
453
+
454
+ export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, Ship, type ShipClientOptions, __setTestEnvironment, calculateMD5, createAccountResource, createAliasResource, createDeploymentResource, createKeysResource, Ship as default, filterJunk, getENV, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForBrowser, resolveConfig, setConfig };