@shipstatic/ship 0.3.6 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as _shipstatic_types from '@shipstatic/types';
2
- import { PingResponse, ConfigResponse, StaticFile, Deployment, DeploymentListResponse, Domain, DomainListResponse, Account, TokenCreateResponse, TokenListResponse, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource, PlatformConfig } from '@shipstatic/types';
2
+ import { PingResponse, ConfigResponse, StaticFile, Deployment, DeploymentListResponse, Domain, DomainListResponse, Account, TokenCreateResponse, TokenListResponse, CheckoutSession, SubscriptionStatus, SubscriptionSyncResponse, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource, SubscriptionResource, PlatformConfig, ValidatableFile, FileValidationResult } from '@shipstatic/types';
3
3
  export * from '@shipstatic/types';
4
- export { Account, DEFAULT_API, DeployInput, Deployment, Domain, PingResponse, ShipError, ShipErrorType } from '@shipstatic/types';
4
+ export { Account, DEFAULT_API, DeployInput, Deployment, Domain, FileValidationStatus as FILE_VALIDATION_STATUS, PingResponse, ShipError, ShipErrorType } from '@shipstatic/types';
5
5
 
6
6
  /**
7
7
  * @file SDK-specific type definitions
@@ -224,6 +224,23 @@ declare class ApiHttp extends SimpleEvents {
224
224
  createToken(ttl?: number, tags?: string[]): Promise<TokenCreateResponse>;
225
225
  listTokens(): Promise<TokenListResponse>;
226
226
  removeToken(token: string): Promise<void>;
227
+ /**
228
+ * Create a Creem checkout session for subscription
229
+ * POST /subscriptions/checkout
230
+ */
231
+ createCheckout(): Promise<CheckoutSession>;
232
+ /**
233
+ * Get current subscription status and usage
234
+ * GET /subscriptions/status
235
+ */
236
+ getSubscriptionStatus(): Promise<SubscriptionStatus>;
237
+ /**
238
+ * Sync subscription ID after checkout redirect
239
+ * POST /subscriptions/sync
240
+ *
241
+ * @param subscriptionId - Subscription ID from Creem redirect URL
242
+ */
243
+ syncSubscription(subscriptionId: string): Promise<SubscriptionSyncResponse>;
227
244
  checkSPA(files: StaticFile[]): Promise<boolean>;
228
245
  private validateFiles;
229
246
  private prepareRequestPayload;
@@ -240,6 +257,7 @@ declare function createDeploymentResource(getApi: () => ApiHttp, clientDefaults?
240
257
  declare function createDomainResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): DomainResource;
241
258
  declare function createAccountResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): AccountResource;
242
259
  declare function createTokenResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): TokenResource;
260
+ declare function createSubscriptionResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): SubscriptionResource;
243
261
 
244
262
  /**
245
263
  * Abstract base class for Ship SDK implementations.
@@ -258,6 +276,7 @@ declare abstract class Ship$1 {
258
276
  protected _domains: DomainResource;
259
277
  protected _account: AccountResource;
260
278
  protected _tokens: TokenResource;
279
+ protected _subscriptions: SubscriptionResource;
261
280
  constructor(options?: ShipClientOptions);
262
281
  protected abstract resolveInitialConfig(options: ShipClientOptions): any;
263
282
  protected abstract loadFullConfig(): Promise<void>;
@@ -294,6 +313,10 @@ declare abstract class Ship$1 {
294
313
  * Get tokens resource
295
314
  */
296
315
  get tokens(): TokenResource;
316
+ /**
317
+ * Get subscriptions resource
318
+ */
319
+ get subscriptions(): SubscriptionResource;
297
320
  /**
298
321
  * Get API configuration (file upload limits, etc.)
299
322
  * Reuses platform config fetched during initialization, then caches the result
@@ -499,50 +522,6 @@ declare function getENV(): ExecutionEnvironment;
499
522
  * Provides client-side validation for file uploads before deployment
500
523
  */
501
524
 
502
- /**
503
- * File status constants for validation state tracking
504
- */
505
- declare const FILE_VALIDATION_STATUS: {
506
- readonly PENDING: "pending";
507
- readonly PROCESSING_ERROR: "processing_error";
508
- readonly EMPTY_FILE: "empty_file";
509
- readonly VALIDATION_FAILED: "validation_failed";
510
- readonly READY: "ready";
511
- };
512
- type FileValidationStatus = (typeof FILE_VALIDATION_STATUS)[keyof typeof FILE_VALIDATION_STATUS];
513
- /**
514
- * Client-side validation error structure
515
- */
516
- interface ValidationError {
517
- error: string;
518
- details: string;
519
- errors: string[];
520
- isClientError: true;
521
- }
522
- /**
523
- * Minimal file interface required for validation
524
- */
525
- interface ValidatableFile {
526
- name: string;
527
- size: number;
528
- type: string;
529
- status?: string;
530
- statusMessage?: string;
531
- }
532
- /**
533
- * File validation result
534
- *
535
- * NOTE: Validation is ATOMIC - if any file fails validation, ALL files are rejected.
536
- * This ensures deployments are all-or-nothing for data integrity.
537
- */
538
- interface FileValidationResult<T extends ValidatableFile> {
539
- /** All files with updated status */
540
- files: T[];
541
- /** Files that passed validation (empty if ANY file failed - atomic validation) */
542
- validFiles: T[];
543
- /** Validation error if any files failed */
544
- error: ValidationError | null;
545
- }
546
525
  /**
547
526
  * Format file size to human-readable string
548
527
  */
@@ -658,4 +637,4 @@ declare class Ship extends Ship$1 {
658
637
  protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
659
638
  }
660
639
 
661
- export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, FILE_VALIDATION_STATUS, type FileValidationResult, type FileValidationStatus, JUNK_DIRECTORIES, type MD5Result, type ProgressInfo, Ship, type ShipClientOptions, type ShipEvents, type ValidatableFile, type ValidationError, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getCurrentConfig, getENV, getValidFiles, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig, setConfig as setPlatformConfig, validateFiles };
640
+ export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ProgressInfo, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createSubscriptionResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getCurrentConfig, getENV, getValidFiles, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig, setConfig as setPlatformConfig, validateFiles };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as _shipstatic_types from '@shipstatic/types';
2
- import { PingResponse, ConfigResponse, StaticFile, Deployment, DeploymentListResponse, Domain, DomainListResponse, Account, TokenCreateResponse, TokenListResponse, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource, PlatformConfig } from '@shipstatic/types';
2
+ import { PingResponse, ConfigResponse, StaticFile, Deployment, DeploymentListResponse, Domain, DomainListResponse, Account, TokenCreateResponse, TokenListResponse, CheckoutSession, SubscriptionStatus, SubscriptionSyncResponse, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource, SubscriptionResource, PlatformConfig, ValidatableFile, FileValidationResult } from '@shipstatic/types';
3
3
  export * from '@shipstatic/types';
4
- export { Account, DEFAULT_API, DeployInput, Deployment, Domain, PingResponse, ShipError, ShipErrorType } from '@shipstatic/types';
4
+ export { Account, DEFAULT_API, DeployInput, Deployment, Domain, FileValidationStatus as FILE_VALIDATION_STATUS, PingResponse, ShipError, ShipErrorType } from '@shipstatic/types';
5
5
 
6
6
  /**
7
7
  * @file SDK-specific type definitions
@@ -224,6 +224,23 @@ declare class ApiHttp extends SimpleEvents {
224
224
  createToken(ttl?: number, tags?: string[]): Promise<TokenCreateResponse>;
225
225
  listTokens(): Promise<TokenListResponse>;
226
226
  removeToken(token: string): Promise<void>;
227
+ /**
228
+ * Create a Creem checkout session for subscription
229
+ * POST /subscriptions/checkout
230
+ */
231
+ createCheckout(): Promise<CheckoutSession>;
232
+ /**
233
+ * Get current subscription status and usage
234
+ * GET /subscriptions/status
235
+ */
236
+ getSubscriptionStatus(): Promise<SubscriptionStatus>;
237
+ /**
238
+ * Sync subscription ID after checkout redirect
239
+ * POST /subscriptions/sync
240
+ *
241
+ * @param subscriptionId - Subscription ID from Creem redirect URL
242
+ */
243
+ syncSubscription(subscriptionId: string): Promise<SubscriptionSyncResponse>;
227
244
  checkSPA(files: StaticFile[]): Promise<boolean>;
228
245
  private validateFiles;
229
246
  private prepareRequestPayload;
@@ -240,6 +257,7 @@ declare function createDeploymentResource(getApi: () => ApiHttp, clientDefaults?
240
257
  declare function createDomainResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): DomainResource;
241
258
  declare function createAccountResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): AccountResource;
242
259
  declare function createTokenResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): TokenResource;
260
+ declare function createSubscriptionResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): SubscriptionResource;
243
261
 
244
262
  /**
245
263
  * Abstract base class for Ship SDK implementations.
@@ -258,6 +276,7 @@ declare abstract class Ship$1 {
258
276
  protected _domains: DomainResource;
259
277
  protected _account: AccountResource;
260
278
  protected _tokens: TokenResource;
279
+ protected _subscriptions: SubscriptionResource;
261
280
  constructor(options?: ShipClientOptions);
262
281
  protected abstract resolveInitialConfig(options: ShipClientOptions): any;
263
282
  protected abstract loadFullConfig(): Promise<void>;
@@ -294,6 +313,10 @@ declare abstract class Ship$1 {
294
313
  * Get tokens resource
295
314
  */
296
315
  get tokens(): TokenResource;
316
+ /**
317
+ * Get subscriptions resource
318
+ */
319
+ get subscriptions(): SubscriptionResource;
297
320
  /**
298
321
  * Get API configuration (file upload limits, etc.)
299
322
  * Reuses platform config fetched during initialization, then caches the result
@@ -499,50 +522,6 @@ declare function getENV(): ExecutionEnvironment;
499
522
  * Provides client-side validation for file uploads before deployment
500
523
  */
501
524
 
502
- /**
503
- * File status constants for validation state tracking
504
- */
505
- declare const FILE_VALIDATION_STATUS: {
506
- readonly PENDING: "pending";
507
- readonly PROCESSING_ERROR: "processing_error";
508
- readonly EMPTY_FILE: "empty_file";
509
- readonly VALIDATION_FAILED: "validation_failed";
510
- readonly READY: "ready";
511
- };
512
- type FileValidationStatus = (typeof FILE_VALIDATION_STATUS)[keyof typeof FILE_VALIDATION_STATUS];
513
- /**
514
- * Client-side validation error structure
515
- */
516
- interface ValidationError {
517
- error: string;
518
- details: string;
519
- errors: string[];
520
- isClientError: true;
521
- }
522
- /**
523
- * Minimal file interface required for validation
524
- */
525
- interface ValidatableFile {
526
- name: string;
527
- size: number;
528
- type: string;
529
- status?: string;
530
- statusMessage?: string;
531
- }
532
- /**
533
- * File validation result
534
- *
535
- * NOTE: Validation is ATOMIC - if any file fails validation, ALL files are rejected.
536
- * This ensures deployments are all-or-nothing for data integrity.
537
- */
538
- interface FileValidationResult<T extends ValidatableFile> {
539
- /** All files with updated status */
540
- files: T[];
541
- /** Files that passed validation (empty if ANY file failed - atomic validation) */
542
- validFiles: T[];
543
- /** Validation error if any files failed */
544
- error: ValidationError | null;
545
- }
546
525
  /**
547
526
  * Format file size to human-readable string
548
527
  */
@@ -658,4 +637,4 @@ declare class Ship extends Ship$1 {
658
637
  protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
659
638
  }
660
639
 
661
- export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, FILE_VALIDATION_STATUS, type FileValidationResult, type FileValidationStatus, JUNK_DIRECTORIES, type MD5Result, type ProgressInfo, Ship, type ShipClientOptions, type ShipEvents, type ValidatableFile, type ValidationError, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getCurrentConfig, getENV, getValidFiles, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig, setConfig as setPlatformConfig, validateFiles };
640
+ export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ProgressInfo, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createSubscriptionResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getCurrentConfig, getENV, getValidFiles, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig, setConfig as setPlatformConfig, validateFiles };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Re=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var Qe=Object.prototype.hasOwnProperty;var T=(n,e)=>()=>(n&&(e=n(n=0)),e);var M=(n,e)=>{for(var t in e)Re(n,t,{get:e[t],enumerable:!0})},Ae=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ze(e))!Qe.call(n,s)&&s!==t&&Re(n,s,{get:()=>e[s],enumerable:!(i=Xe(e,s))||i.enumerable});return n},p=(n,e,t)=>(Ae(n,e,"default"),t&&Ae(t,e,"default"));var Ie={};M(Ie,{__setTestEnvironment:()=>q,getENV:()=>y});function q(n){fe=n}function et(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function y(){return fe||et()}var fe,E=T(()=>{"use strict";fe=null});import{ShipError as st}from"@shipstatic/types";function _(n){ue=n}function R(){if(ue===null)throw st.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ue}var ue,$=T(()=>{"use strict";ue=null});var Oe={};M(Oe,{loadConfig:()=>z});import{z as H}from"zod";import{ShipError as he}from"@shipstatic/types";function ke(n){try{return rt.parse(n)}catch(e){if(e instanceof H.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw he.config(`Configuration validation failed${i}: ${t.message}`)}throw he.config("Configuration validation failed")}}async function at(n){try{if(y()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(de,{searchPlaces:[`.${de}rc`,"package.json",`${t.homedir()}/.${de}rc`],stopDir:t.homedir()}),s;if(n?s=i.load(n):s=i.search(),s&&s.config)return ke(s.config)}catch(e){if(e instanceof he)throw e}return{}}async function z(n){if(y()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await at(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return ke(i)}var de,rt,ie=T(()=>{"use strict";E();de="ship",rt=H.object({apiUrl:H.string().url().optional(),apiKey:H.string().optional(),deployToken:H.string().optional()}).strict()});import{ShipError as U}from"@shipstatic/types";async function ct(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let o=Math.ceil(n.size/2097152),r=0,a=new e.ArrayBuffer,f=new FileReader,g=()=>{let D=r*2097152,l=Math.min(D+2097152,n.size);f.readAsArrayBuffer(n.slice(D,l))};f.onload=D=>{let l=D.target?.result;if(!l){i(U.business("Failed to read file chunk"));return}a.append(l),r++,r<o?g():t({md5:a.end()})},f.onerror=()=>{i(U.business("Failed to calculate MD5: FileReader error"))},g()})}async function ft(n){let e=await import("crypto");if(Buffer.isBuffer(n)){let i=e.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let t=await import("fs");return new Promise((i,s)=>{let o=e.createHash("md5"),r=t.createReadStream(n);r.on("error",a=>s(U.business(`Failed to read file for MD5: ${a.message}`))),r.on("data",a=>o.update(a)),r.on("end",()=>i({md5:o.digest("hex")}))})}async function b(n){let e=y();if(e==="browser"){if(!(n instanceof Blob))throw U.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return ct(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw U.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return ft(n)}throw U.business("Unknown or unsupported execution environment for MD5 calculation.")}var j=T(()=>{"use strict";E()});import{isJunk as ut}from"junk";function k(n){return!n||n.length===0?[]:n.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let i=t[t.length-1];if(ut(i))return!1;let s=t.slice(0,-1);for(let o of s)if(oe.some(r=>o.toLowerCase()===r.toLowerCase()))return!1;return!0})}var oe,se=T(()=>{"use strict";oe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function ze(n){if(!n||n.length===0)return"";let e=n.filter(o=>o&&typeof o=="string").map(o=>o.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(o=>o.split("/").filter(Boolean)),i=[],s=Math.min(...t.map(o=>o.length));for(let o=0;o<s;o++){let r=t[0][o];if(t.every(a=>a[o]===r))i.push(r);else break}return i.join("/")}function re(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ve=T(()=>{"use strict"});function O(n,e={}){if(e.flatten===!1)return n.map(i=>({path:re(i),name:De(i)}));let t=dt(n);return n.map(i=>{let s=re(i);if(t){let o=t.endsWith("/")?t:`${t}/`;s.startsWith(o)&&(s=s.substring(o.length))}return s||(s=De(i)),{path:s,name:De(i)}})}function dt(n){if(!n.length)return"";let t=n.map(o=>re(o)).map(o=>o.split("/")),i=[],s=Math.min(...t.map(o=>o.length));for(let o=0;o<s-1;o++){let r=t[0][o];if(t.every(a=>a[o]===r))i.push(r);else break}return i.join("/")}function De(n){return n.split(/[/\\]/).pop()||n}var ae=T(()=>{"use strict";ve()});import{ShipError as N}from"@shipstatic/types";import*as I from"fs";import*as w from"path";function Ue(n){let e=[];try{let t=I.readdirSync(n);for(let i of t){let s=w.join(n,i),o=I.statSync(s);if(o.isDirectory()){let r=Ue(s);e.push(...r)}else o.isFile()&&e.push(s)}}catch(t){console.error(`Error reading directory ${n}:`,t)}return e}async function X(n,e={}){if(y()!=="node")throw N.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(m=>{let u=w.resolve(m);try{return I.statSync(u).isDirectory()?Ue(u):[u]}catch{throw N.file(`Path does not exist: ${m}`,m)}}),i=[...new Set(t)],s=k(i);if(s.length===0)return[];let o=n.map(m=>w.resolve(m)),r=ze(o.map(m=>{try{return I.statSync(m).isDirectory()?m:w.dirname(m)}catch{return w.dirname(m)}})),a=s.map(m=>{if(r&&r.length>0){let u=w.relative(r,m);if(u&&typeof u=="string"&&!u.startsWith(".."))return u.replace(/\\/g,"/")}return w.basename(m)}),f=O(a,{flatten:e.pathDetect!==!1}),g=[],D=0,l=R();for(let m=0;m<s.length;m++){let u=s[m],P=f[m].path;try{let x=I.statSync(u);if(x.size===0){console.warn(`Skipping empty file: ${u}`);continue}if(x.size>l.maxFileSize)throw N.business(`File ${u} is too large. Maximum allowed size is ${l.maxFileSize/(1024*1024)}MB.`);if(D+=x.size,D>l.maxTotalSize)throw N.business(`Total deploy size is too large. Maximum allowed is ${l.maxTotalSize/(1024*1024)}MB.`);let pe=I.readFileSync(u),{md5:Ye}=await b(pe);if(P.includes("\0")||P.includes("/../")||P.startsWith("../")||P.endsWith("/.."))throw N.business(`Security error: Unsafe file path "${P}" for file: ${u}`);g.push({path:P,content:pe,size:pe.length,md5:Ye})}catch(x){if(x instanceof N&&x.isClientError&&x.isClientError())throw x;console.error(`Could not process file ${u}:`,x)}}if(g.length>l.maxFilesCount)throw N.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return g}var Ce=T(()=>{"use strict";E();j();se();$();ae();ve()});import{ShipError as Be}from"@shipstatic/types";async function Ke(n,e={}){let{getENV:t}=await Promise.resolve().then(()=>(E(),Ie));if(t()!=="browser")throw Be.business("processFilesForBrowser can only be called in a browser environment.");let i=n,s=i.map(l=>l.webkitRelativePath||l.name),o=O(s,{flatten:e.pathDetect!==!1}),r=[];for(let l=0;l<i.length;l++){let m=i[l],u=o[l].path;if(u.includes("..")||u.includes("\0"))throw Be.business(`Security error: Unsafe file path "${u}" for file: ${m.name}`);r.push({file:m,relativePath:u})}let a=r.map(l=>l.relativePath),f=k(a),g=new Set(f),D=[];for(let l of r){if(!g.has(l.relativePath))continue;let{md5:m}=await b(l.file);D.push({content:l.file,path:l.relativePath,size:l.file.size,md5:m})}return D}var qe=T(()=>{"use strict";j();se();ae()});var We={};M(We,{convertBrowserInput:()=>Ge,convertDeployInput:()=>Dt,convertNodeInput:()=>Pe});import{ShipError as C}from"@shipstatic/types";function He(n,e={}){let t=R();if(!e.skipEmptyCheck&&n.length===0)throw C.business("No files to deploy.");if(n.length>t.maxFilesCount)throw C.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let i=0;for(let s of n){if(s.size>t.maxFileSize)throw C.business(`File ${s.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(i+=s.size,i>t.maxTotalSize)throw C.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Ve(n,e){if(e==="node"){if(!Array.isArray(n))throw C.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(n.length===0)throw C.business("No files to deploy.");if(!n.every(t=>typeof t=="string"))throw C.business("Invalid input type for Node.js environment. Expected string[] file paths.")}}function je(n){let e=n.map(t=>({name:t.path,size:t.size}));return He(e,{skipEmptyCheck:!0}),n.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),n}async function Pe(n,e={}){Ve(n,"node");let t=await X(n,e);return je(t)}async function Ge(n,e={}){Ve(n,"browser");let t;if(Array.isArray(n)){if(n.length>0&&typeof n[0]=="string")throw C.business("Invalid input type for browser environment. Expected File[].");t=n}else throw C.business("Invalid input type for browser environment. Expected File[].");t=t.filter(s=>s.size===0?(console.warn(`Skipping empty file: ${s.name}`),!1):!0),He(t);let i=await Ke(t,e);return je(i)}async function Dt(n,e={},t){let i=y();if(i!=="node"&&i!=="browser")throw C.business("Unsupported execution environment.");let s;if(i==="node")if(typeof n=="string")s=await Pe([n],e);else if(Array.isArray(n)&&n.every(o=>typeof o=="string"))s=await Pe(n,e);else throw C.business("Invalid input type for Node.js environment. Expected string[] file paths.");else s=await Ge(n,e);return s}var Je=T(()=>{"use strict";E();Ce();qe();$()});var Q={};M(Q,{ApiHttp:()=>A,DEFAULT_API:()=>ye,FILE_VALIDATION_STATUS:()=>d,JUNK_DIRECTORIES:()=>oe,Ship:()=>Z,ShipError:()=>Fe,ShipErrorType:()=>Se,__setTestEnvironment:()=>q,allValidFilesReady:()=>Ee,calculateMD5:()=>b,createAccountResource:()=>J,createDeploymentResource:()=>G,createDomainResource:()=>W,createTokenResource:()=>Y,default:()=>xe,filterJunk:()=>k,formatFileSize:()=>K,getCurrentConfig:()=>R,getENV:()=>y,getValidFiles:()=>le,loadConfig:()=>z,mergeDeployOptions:()=>V,optimizeDeployPaths:()=>O,pluralize:()=>ge,processFilesForNode:()=>X,resolveConfig:()=>L,setConfig:()=>_,setPlatformConfig:()=>_,validateFiles:()=>we});var h={};M(h,{ApiHttp:()=>A,DEFAULT_API:()=>ye,FILE_VALIDATION_STATUS:()=>d,JUNK_DIRECTORIES:()=>oe,Ship:()=>Z,ShipError:()=>Fe,ShipErrorType:()=>Se,__setTestEnvironment:()=>q,allValidFilesReady:()=>Ee,calculateMD5:()=>b,createAccountResource:()=>J,createDeploymentResource:()=>G,createDomainResource:()=>W,createTokenResource:()=>Y,default:()=>xe,filterJunk:()=>k,formatFileSize:()=>K,getCurrentConfig:()=>R,getENV:()=>y,getValidFiles:()=>le,loadConfig:()=>z,mergeDeployOptions:()=>V,optimizeDeployPaths:()=>O,pluralize:()=>ge,processFilesForNode:()=>X,resolveConfig:()=>L,setConfig:()=>_,setPlatformConfig:()=>_,validateFiles:()=>we});import be from"mime-db";var ce={};for(let n in be){let e=be[n];e&&e.extensions&&e.extensions.forEach(t=>{ce[t]||(ce[t]=n)})}function ee(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return ce[e]||"application/octet-stream"}import{ShipError as F,DEFAULT_API as tt}from"@shipstatic/types";var te=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let i=this.handlers.get(e);i&&(i.delete(t),i.size===0&&this.handlers.delete(e))}emit(e,...t){let i=this.handlers.get(e);if(!i)return;let s=Array.from(i);for(let o of s)try{o(...t)}catch(r){i.delete(o),e!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(e)):this.emit("error",new Error(String(r)),String(e))},0)}}transfer(e){this.handlers.forEach((t,i)=>{t.forEach(s=>{e.on(i,s)})})}clear(){this.handlers.clear()}};E();var ne="/deployments",$e="/ping",S="/domains",nt="/config",it="/account",me="/tokens",ot="/spa-check",A=class extends te{constructor(e){super(),this.apiUrl=e.apiUrl||tt,this.getAuthHeadersCallback=e.getAuthHeaders}transferEventsTo(e){this.transfer(e)}async request(e,t={},i){let s=this.getAuthHeaders(t.headers),o={...t,headers:s,credentials:s.Authorization?void 0:"include"};this.emit("request",e,o);try{let r=await fetch(e,o);r.ok||await this.handleResponseError(r,i);let a=this.safeClone(r),f=this.safeClone(r);return this.emit("response",a,e),await this.parseResponse(f)}catch(r){throw this.emit("error",r,e),this.handleFetchError(r,i),r}}getAuthHeaders(e={}){let t=this.getAuthHeadersCallback();return{...e,...t}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return await e.json()}async handleResponseError(e,t){let i={};try{e.headers.get("content-type")?.includes("application/json")?i=await e.json():i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let s=i.message||i.error||`${t} failed due to API error`;throw e.status===401?F.authentication(s):F.api(s,e.status,i.code,i)}handleFetchError(e,t){throw e.name==="AbortError"?F.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?F.network(`${t} failed due to network error: ${e.message}`,e):e instanceof F?e:F.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${$e}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${$e}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${nt}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:i,requestHeaders:s}=await this.prepareRequestPayload(e,t.tags),o={};t.deployToken?o={Authorization:`Bearer ${t.deployToken}`}:t.apiKey&&(o={Authorization:`Bearer ${t.apiKey}`});let r={method:"POST",body:i,headers:{...s,...o},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${ne}`,r,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${ne}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${ne}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${ne}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,t,i){let s={deployment:t};i&&i.length>0&&(s.tags=i);let o={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},r=this.getAuthHeaders(o.headers),a={...o,headers:r,credentials:r.Authorization?void 0:"include"};this.emit("request",`${this.apiUrl}${S}/${encodeURIComponent(e)}`,a);try{let f=await fetch(`${this.apiUrl}${S}/${encodeURIComponent(e)}`,a);f.ok||await this.handleResponseError(f,"Set Domain");let g=this.safeClone(f),D=this.safeClone(f);return this.emit("response",g,`${this.apiUrl}${S}/${encodeURIComponent(e)}`),{...await this.parseResponse(D),isCreate:f.status===201}}catch(f){throw this.emit("error",f,`${this.apiUrl}${S}/${encodeURIComponent(e)}`),this.handleFetchError(f,"Set Domain"),f}}async getDomain(e){return await this.request(`${this.apiUrl}${S}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${S}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${S}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async confirmDomain(e){return await this.request(`${this.apiUrl}${S}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${S}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${S}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${S}/${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 F.business("No files to deploy.");for(let t of e)if(!t.md5)throw F.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async prepareRequestPayload(e,t){if(y()==="browser")return{requestBody:this.createBrowserBody(e,t),requestHeaders:{}};if(y()==="node"){let{body:i,headers:s}=await this.createNodeBody(e,t);return{requestBody:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),requestHeaders:s}}else throw F.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 F.file(`Unsupported file.content type for browser FormData: ${o.path}`,o.path);let r=this.getBrowserContentType(o.content instanceof File?o.content:o.path),a=new File([o.content],o.path,{type:r});i.append("files[]",a),s.push(o.md5)}return i.append("checksums",JSON.stringify(s)),t&&t.length>0&&i.append("tags",JSON.stringify(t)),i}async createNodeBody(e,t){let{FormData:i,File:s}=await import("formdata-node"),{FormDataEncoder:o}=await import("form-data-encoder"),r=new i,a=[];for(let l of e){let m=ee(l.path),u;if(Buffer.isBuffer(l.content))u=new s([l.content],l.path,{type:m});else if(typeof Blob<"u"&&l.content instanceof Blob)u=new s([l.content],l.path,{type:m});else throw F.file(`Unsupported file.content type for Node.js FormData: ${l.path}`,l.path);let P=l.path.startsWith("/")?l.path:"/"+l.path;r.append("files[]",u,P),a.push(l.md5)}r.append("checksums",JSON.stringify(a)),t&&t.length>0&&r.append("tags",JSON.stringify(t));let f=new o(r),g=[];for await(let l of f.encode())g.push(Buffer.from(l));let D=Buffer.concat(g);return{body:D,headers:{"Content-Type":f.contentType,"Content-Length":Buffer.byteLength(D).toString()}}}getBrowserContentType(e){return typeof e=="string"?ee(e):e.type||ee(e.name)}};$();import{ShipError as _e}from"@shipstatic/types";E();import{DEFAULT_API as lt}from"@shipstatic/types";async function pt(n){let e=y();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(ie(),Oe));return t(n)}else return{}}function L(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||lt,apiKey:n.apiKey!==void 0?n.apiKey:e.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:e.deployToken},i={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(i.apiKey=t.apiKey),t.deployToken!==void 0&&(i.deployToken=t.deployToken),i}function V(n,e){let t={...n};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t}j();import{DEPLOYMENT_CONFIG_FILENAME as Ne}from"@shipstatic/types";async function mt(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:i}=await b(t);return{path:Ne,content:t,size:e.length,md5:i}}async function Me(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===Ne))return n;try{if(await e.checkSPA(n)){let s=await mt();return[...n,s]}}catch{}return n}function G(n,e,t,i,s){return{create:async(o,r={})=>{if(s&&!s()&&!r.deployToken&&!r.apiKey)throw new Error("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");t&&await t();let a=e?V(r,e):r,f=n();if(!i)throw new Error("processInput function is not provided.");let g=await i(o,a);return g=await Me(g,f,a),await f.deploy(g,a)},list:async()=>(t&&await t(),n().listDeployments()),remove:async o=>{t&&await t(),await n().removeDeployment(o)},get:async o=>(t&&await t(),n().getDeployment(o))}}function W(n,e){return{set:async(t,i,s)=>(e&&await e(),n().setDomain(t,i,s)),get:async t=>(e&&await e(),n().getDomain(t)),list:async()=>(e&&await e(),n().listDomains()),remove:async t=>{e&&await e(),await n().removeDomain(t)},confirm:async t=>(e&&await e(),n().confirmDomain(t)),dns:async t=>(e&&await e(),n().getDomainDns(t)),records:async t=>(e&&await e(),n().getDomainRecords(t)),share:async t=>(e&&await e(),n().getDomainShare(t))}}function J(n,e){return{get:async()=>(e&&await e(),n().getAccount())}}function Y(n,e){return{create:async(t,i)=>(e&&await e(),n().createToken(t,i)),list:async()=>(e&&await e(),n().listTokens()),remove:async t=>{e&&await e(),await n().removeToken(t)}}}var B=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 A({...e,...t,getAuthHeaders:this.authHeadersCallback});let i=()=>this.ensureInitialized(),s=()=>this.http;this._deployments=G(s,this.clientOptions,i,(o,r)=>this.processInput(o,r),()=>this.hasAuth()),this._domains=W(s,i),this._account=J(s,i),this._tokens=Y(s,i)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=R(),this._config)}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}setDeployToken(e){if(!e||typeof e!="string")throw _e.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw _e.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){if(!this.auth)return{};switch(this.auth.type){case"token":return{Authorization:`Bearer ${this.auth.value}`};case"apiKey":return{Authorization:`Bearer ${this.auth.value}`};default:return{}}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};E();ie();import{ShipError as Te}from"@shipstatic/types";$();var c={};M(c,{ApiHttp:()=>A,DEFAULT_API:()=>ye,FILE_VALIDATION_STATUS:()=>d,JUNK_DIRECTORIES:()=>oe,Ship:()=>B,ShipError:()=>Fe,ShipErrorType:()=>Se,__setTestEnvironment:()=>q,allValidFilesReady:()=>Ee,calculateMD5:()=>b,createAccountResource:()=>J,createDeploymentResource:()=>G,createDomainResource:()=>W,createTokenResource:()=>Y,filterJunk:()=>k,formatFileSize:()=>K,getENV:()=>y,getValidFiles:()=>le,loadConfig:()=>pt,mergeDeployOptions:()=>V,optimizeDeployPaths:()=>O,pluralize:()=>ge,resolveConfig:()=>L,validateFiles:()=>we});var v={};p(v,Xt);import*as Xt from"@shipstatic/types";p(c,v);import{DEFAULT_API as ye}from"@shipstatic/types";j();function ge(n,e,t,i=!0){let s=n===1?e:t;return i?`${n} ${s}`:s}se();ae();E();import Le from"mime-db";var ht=new Set(Object.keys(Le)),yt=new Map(Object.entries(Le).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)])),d={PENDING:"pending",PROCESSING_ERROR:"processing_error",EMPTY_FILE:"empty_file",VALIDATION_FAILED:"validation_failed",READY:"ready"};function K(n,e=1){if(n===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,s)).toFixed(e))+" "+i[s]}function gt(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(".")===!1&&(n.startsWith(" ")||n.endsWith(" ")||n.endsWith(".")))return{valid:!1,reason:"File name cannot start/end with spaces or end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,i=n.split("/").pop()||n;return t.test(i)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function vt(n,e){if(n.startsWith("."))return!0;let t=n.toLowerCase().split(".");if(t.length>1&&t[t.length-1]){let i=t[t.length-1],s=yt.get(e);if(s&&!s.has(i))return!1}return!0}function we(n,e){let t=[],i=[];if(n.length===0){let o="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:o,errors:[o],isClientError:!0}}}if(n.length>e.maxFilesCount){let o=`Number of files (${n.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:n.map(r=>({...r,status:d.VALIDATION_FAILED,statusMessage:o})),validFiles:[],error:{error:"File Count Exceeded",details:o,errors:[o],isClientError:!0}}}let s=0;for(let o of n){let r=d.READY,a="Ready for upload",f=o.name?gt(o.name):{valid:!1,reason:"File name cannot be empty"};o.status===d.PROCESSING_ERROR?(r=d.PROCESSING_ERROR,a=o.statusMessage||"A file failed during processing.",t.push(`${o.name}: ${a}`)):!o.name||o.name.trim().length===0?(r=d.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${o.name||"(empty)"}: ${a}`)):o.name.includes("\0")?(r=d.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push(`${o.name}: ${a}`)):f.valid?o.size<=0?(r=d.EMPTY_FILE,a=o.size===0?"File is empty (0 bytes)":"File size must be positive",t.push(`${o.name}: ${a}`)):!o.type||o.type.trim().length===0?(r=d.VALIDATION_FAILED,a="File MIME type is required",t.push(`${o.name}: ${a}`)):e.allowedMimeTypes.some(g=>o.type.startsWith(g))?ht.has(o.type)?vt(o.name,o.type)?o.size>e.maxFileSize?(r=d.VALIDATION_FAILED,a=`File size (${K(o.size)}) exceeds limit of ${K(e.maxFileSize)}`,t.push(`${o.name}: ${a}`)):(s+=o.size,s>e.maxTotalSize&&(r=d.VALIDATION_FAILED,a=`Total size would exceed limit of ${K(e.maxTotalSize)}`,t.push(`${o.name}: ${a}`))):(r=d.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${o.name}: ${a}`)):(r=d.VALIDATION_FAILED,a=`Invalid MIME type "${o.type}"`,t.push(`${o.name}: ${a}`)):(r=d.VALIDATION_FAILED,a=`File type "${o.type}" is not allowed`,t.push(`${o.name}: ${a}`)):(r=d.VALIDATION_FAILED,a=f.reason||"Invalid file name",t.push(`${o.name}: ${a}`)),i.push({...o,status:r,statusMessage:a})}if(t.length>0){let o=i.find(a=>a.status!==d.READY&&a.status!==d.PENDING),r="Validation Failed";return o?.status===d.PROCESSING_ERROR?r="Processing Error":o?.status===d.EMPTY_FILE?r="Empty File":o?.statusMessage?.includes("File name cannot be empty")||o?.statusMessage?.includes("Invalid file name")||o?.statusMessage?.includes("File name contains")||o?.statusMessage?.includes("File name uses")||o?.statusMessage?.includes("File name cannot start")||o?.statusMessage?.includes("traversal")?r="Invalid File Name":o?.statusMessage?.includes("File size must be positive")?r="Invalid File Size":o?.statusMessage?.includes("MIME type is required")?r="Missing MIME Type":o?.statusMessage?.includes("Invalid MIME type")?r="Invalid MIME Type":o?.statusMessage?.includes("not allowed")?r="Invalid File Type":o?.statusMessage?.includes("extension does not match")?r="Extension Mismatch":o?.statusMessage?.includes("Total size")?r="Total Size Exceeded":o?.statusMessage?.includes("exceeds limit")&&(r="File Too Large"),{files:i.map(a=>({...a,status:d.VALIDATION_FAILED})),validFiles:[],error:{error:r,details:t.length===1?t[0]:`${t.length} file(s) failed validation`,errors:t,isClientError:!0}}}return{files:i,validFiles:i,error:null}}function le(n){return n.filter(e=>e.status===d.READY)}function Ee(n){return le(n).length>0}import{ShipError as Fe,ShipErrorType as Se}from"@shipstatic/types";p(h,c);ie();$();$();Ce();E();var Z=class extends B{constructor(e={}){if(y()!=="node")throw Te.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return L(e,{})}async loadFullConfig(){try{let e=await z(this.clientOptions.configFile),t=L(this.clientOptions,e),i=new A({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback});this.replaceHttpClient(i);let s=await this.http.getConfig();_(s)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#e(e))throw Te.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw Te.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;p(Q,h);export{A as ApiHttp,ye as DEFAULT_API,d as FILE_VALIDATION_STATUS,oe as JUNK_DIRECTORIES,Z as Ship,Fe as ShipError,Se as ShipErrorType,q as __setTestEnvironment,Ee as allValidFilesReady,b as calculateMD5,J as createAccountResource,G as createDeploymentResource,W as createDomainResource,Y as createTokenResource,xe as default,k as filterJunk,K as formatFileSize,R as getCurrentConfig,y as getENV,le as getValidFiles,z as loadConfig,V as mergeDeployOptions,O as optimizeDeployPaths,ge as pluralize,X as processFilesForNode,L as resolveConfig,_ as setConfig,_ as setPlatformConfig,we as validateFiles};
1
+ var $e=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var T=(n,e)=>()=>(n&&(e=n(n=0)),e);var M=(n,e)=>{for(var t in e)$e(n,t,{get:e[t],enumerable:!0})},Ae=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of et(e))!tt.call(n,o)&&o!==t&&$e(n,o,{get:()=>e[o],enumerable:!(i=Qe(e,o))||i.enumerable});return n},l=(n,e,t)=>(Ae(n,e,"default"),t&&Ae(t,e,"default"));var Ie={};M(Ie,{__setTestEnvironment:()=>q,getENV:()=>y});function q(n){fe=n}function nt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function y(){return fe||nt()}var fe,D=T(()=>{"use strict";fe=null});import{ShipError as at}from"@shipstatic/types";function U(n){he=n}function R(){if(he===null)throw at.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return he}var he,k=T(()=>{"use strict";he=null});var Me={};M(Me,{loadConfig:()=>z});import{z as H}from"zod";import{ShipError as ge}from"@shipstatic/types";function Ne(n){try{return pt.parse(n)}catch(e){if(e instanceof H.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw ge.config(`Configuration validation failed${i}: ${t.message}`)}throw ge.config("Configuration validation failed")}}async function lt(n){try{if(y()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(ye,{searchPlaces:[`.${ye}rc`,"package.json",`${t.homedir()}/.${ye}rc`],stopDir:t.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return Ne(o.config)}catch(e){if(e instanceof ge)throw e}return{}}async function z(n){if(y()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await lt(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Ne(i)}var ye,pt,se=T(()=>{"use strict";D();ye="ship",pt=H.object({apiUrl:H.string().url().optional(),apiKey:H.string().optional(),deployToken:H.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 s=Math.ceil(n.size/2097152),r=0,a=new e.ArrayBuffer,u=new FileReader,g=()=>{let v=r*2097152,p=Math.min(v+2097152,n.size);u.readAsArrayBuffer(n.slice(v,p))};u.onload=v=>{let p=v.target?.result;if(!p){i(B.business("Failed to read file chunk"));return}a.append(p),r++,r<s?g():t({md5:a.end()})},u.onerror=()=>{i(B.business("Failed to calculate MD5: FileReader error"))},g()})}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,o)=>{let s=e.createHash("md5"),r=t.createReadStream(n);r.on("error",a=>o(B.business(`Failed to read file for MD5: ${a.message}`))),r.on("data",a=>s.update(a)),r.on("end",()=>i({md5:s.digest("hex")}))})}async function A(n){let e=y();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 V=T(()=>{"use strict";D()});import{isJunk as ht}from"junk";function I(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(ht(i))return!1;let o=t.slice(0,-1);for(let s of o)if(oe.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var oe,re=T(()=>{"use strict";oe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Be(n){if(!n||n.length===0)return"";let e=n.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(s=>s.split("/").filter(Boolean)),i=[],o=Math.min(...t.map(s=>s.length));for(let s=0;s<o;s++){let r=t[0][s];if(t.every(a=>a[s]===r))i.push(r);else break}return i.join("/")}function ae(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var we=T(()=>{"use strict"});function O(n,e={}){if(e.flatten===!1)return n.map(i=>({path:ae(i),name:De(i)}));let t=yt(n);return n.map(i=>{let o=ae(i);if(t){let s=t.endsWith("/")?t:`${t}/`;o.startsWith(s)&&(o=o.substring(s.length))}return o||(o=De(i)),{path:o,name:De(i)}})}function yt(n){if(!n.length)return"";let t=n.map(s=>ae(s)).map(s=>s.split("/")),i=[],o=Math.min(...t.map(s=>s.length));for(let s=0;s<o-1;s++){let r=t[0][s];if(t.every(a=>a[s]===r))i.push(r);else break}return i.join("/")}function De(n){return n.split(/[/\\]/).pop()||n}var pe=T(()=>{"use strict";we()});import{ShipError as N}from"@shipstatic/types";import*as $ from"fs";import*as w from"path";function Ke(n){let e=[];try{let t=$.readdirSync(n);for(let i of t){let o=w.join(n,i),s=$.statSync(o);if(s.isDirectory()){let r=Ke(o);e.push(...r)}else s.isFile()&&e.push(o)}}catch(t){console.error(`Error reading directory ${n}:`,t)}return e}async function Z(n,e={}){if(y()!=="node")throw N.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(f=>{let m=w.resolve(f);try{return $.statSync(m).isDirectory()?Ke(m):[m]}catch{throw N.file(`Path does not exist: ${f}`,f)}}),i=[...new Set(t)],o=I(i);if(o.length===0)return[];let s=n.map(f=>w.resolve(f)),r=Be(s.map(f=>{try{return $.statSync(f).isDirectory()?f:w.dirname(f)}catch{return w.dirname(f)}})),a=o.map(f=>{if(r&&r.length>0){let m=w.relative(r,f);if(m&&typeof m=="string"&&!m.startsWith(".."))return m.replace(/\\/g,"/")}return w.basename(f)}),u=O(a,{flatten:e.pathDetect!==!1}),g=[],v=0,p=R();for(let f=0;f<o.length;f++){let m=o[f],P=u[f].path;try{let b=$.statSync(m);if(b.size===0){console.warn(`Skipping empty file: ${m}`);continue}if(b.size>p.maxFileSize)throw N.business(`File ${m} is too large. Maximum allowed size is ${p.maxFileSize/(1024*1024)}MB.`);if(v+=b.size,v>p.maxTotalSize)throw N.business(`Total deploy size is too large. Maximum allowed is ${p.maxTotalSize/(1024*1024)}MB.`);let ce=$.readFileSync(m),{md5:Ze}=await A(ce);if(P.includes("\0")||P.includes("/../")||P.startsWith("../")||P.endsWith("/.."))throw N.business(`Security error: Unsafe file path "${P}" for file: ${m}`);g.push({path:P,content:ce,size:ce.length,md5:Ze})}catch(b){if(b instanceof N&&b.isClientError&&b.isClientError())throw b;console.error(`Could not process file ${m}:`,b)}}if(g.length>p.maxFilesCount)throw N.business(`Too many files to deploy. Maximum allowed is ${p.maxFilesCount} files.`);return g}var Te=T(()=>{"use strict";D();V();re();k();pe();we()});import{ShipError as qe}from"@shipstatic/types";async function He(n,e={}){let{getENV:t}=await Promise.resolve().then(()=>(D(),Ie));if(t()!=="browser")throw qe.business("processFilesForBrowser can only be called in a browser environment.");let i=n,o=i.map(p=>p.webkitRelativePath||p.name),s=O(o,{flatten:e.pathDetect!==!1}),r=[];for(let p=0;p<i.length;p++){let f=i[p],m=s[p].path;if(m.includes("..")||m.includes("\0"))throw qe.business(`Security error: Unsafe file path "${m}" for file: ${f.name}`);r.push({file:f,relativePath:m})}let a=r.map(p=>p.relativePath),u=I(a),g=new Set(u),v=[];for(let p of r){if(!g.has(p.relativePath))continue;let{md5:f}=await A(p.file);v.push({content:p.file,path:p.relativePath,size:p.file.size,md5:f})}return v}var je=T(()=>{"use strict";V();re();pe()});var Ye={};M(Ye,{convertBrowserInput:()=>We,convertDeployInput:()=>Dt,convertNodeInput:()=>be});import{ShipError as C}from"@shipstatic/types";function Ve(n,e={}){let t=R();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 o of n){if(o.size>t.maxFileSize)throw C.business(`File ${o.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(i+=o.size,i>t.maxTotalSize)throw C.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Ge(n,e){if(e==="node"){if(!Array.isArray(n))throw C.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(n.length===0)throw C.business("No files to deploy.");if(!n.every(t=>typeof t=="string"))throw C.business("Invalid input type for Node.js environment. Expected string[] file paths.")}}function Je(n){let e=n.map(t=>({name:t.path,size:t.size}));return Ve(e,{skipEmptyCheck:!0}),n.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),n}async function be(n,e={}){Ge(n,"node");let t=await Z(n,e);return Je(t)}async function We(n,e={}){Ge(n,"browser");let t;if(Array.isArray(n)){if(n.length>0&&typeof n[0]=="string")throw C.business("Invalid input type for browser environment. Expected File[].");t=n}else throw C.business("Invalid input type for browser environment. Expected File[].");t=t.filter(o=>o.size===0?(console.warn(`Skipping empty file: ${o.name}`),!1):!0),Ve(t);let i=await He(t,e);return Je(i)}async function Dt(n,e={},t){let i=y();if(i!=="node"&&i!=="browser")throw C.business("Unsupported execution environment.");let o;if(i==="node")if(typeof n=="string")o=await be([n],e);else if(Array.isArray(n)&&n.every(s=>typeof s=="string"))o=await be(n,e);else throw C.business("Invalid input type for Node.js environment. Expected string[] file paths.");else o=await We(n,e);return o}var Xe=T(()=>{"use strict";D();Te();je();k()});var ee={};M(ee,{ApiHttp:()=>x,DEFAULT_API:()=>Se,FILE_VALIDATION_STATUS:()=>d,JUNK_DIRECTORIES:()=>oe,Ship:()=>Q,ShipError:()=>Ce,ShipErrorType:()=>Pe,__setTestEnvironment:()=>q,allValidFilesReady:()=>Ee,calculateMD5:()=>A,createAccountResource:()=>W,createDeploymentResource:()=>G,createDomainResource:()=>J,createSubscriptionResource:()=>X,createTokenResource:()=>Y,default:()=>Re,filterJunk:()=>I,formatFileSize:()=>K,getCurrentConfig:()=>R,getENV:()=>y,getValidFiles:()=>le,loadConfig:()=>z,mergeDeployOptions:()=>j,optimizeDeployPaths:()=>O,pluralize:()=>ve,processFilesForNode:()=>Z,resolveConfig:()=>_,setConfig:()=>U,setPlatformConfig:()=>U,validateFiles:()=>Fe});var h={};M(h,{ApiHttp:()=>x,DEFAULT_API:()=>Se,FILE_VALIDATION_STATUS:()=>d,JUNK_DIRECTORIES:()=>oe,Ship:()=>Q,ShipError:()=>Ce,ShipErrorType:()=>Pe,__setTestEnvironment:()=>q,allValidFilesReady:()=>Ee,calculateMD5:()=>A,createAccountResource:()=>W,createDeploymentResource:()=>G,createDomainResource:()=>J,createSubscriptionResource:()=>X,createTokenResource:()=>Y,default:()=>Re,filterJunk:()=>I,formatFileSize:()=>K,getCurrentConfig:()=>R,getENV:()=>y,getValidFiles:()=>le,loadConfig:()=>z,mergeDeployOptions:()=>j,optimizeDeployPaths:()=>O,pluralize:()=>ve,processFilesForNode:()=>Z,resolveConfig:()=>_,setConfig:()=>U,setPlatformConfig:()=>U,validateFiles:()=>Fe});import ke from"mime-db";var ue={};for(let n in ke){let e=ke[n];e&&e.extensions&&e.extensions.forEach(t=>{ue[t]||(ue[t]=n)})}function te(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return ue[e]||"application/octet-stream"}import{ShipError as F,DEFAULT_API as it}from"@shipstatic/types";var ne=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let i=this.handlers.get(e);i&&(i.delete(t),i.size===0&&this.handlers.delete(e))}emit(e,...t){let i=this.handlers.get(e);if(!i)return;let o=Array.from(i);for(let s of o)try{s(...t)}catch(r){i.delete(s),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(o=>{e.on(i,o)})})}clear(){this.handlers.clear()}};D();var ie="/deployments",Oe="/ping",E="/domains",st="/config",ot="/account",me="/tokens",de="/subscriptions",rt="/spa-check",x=class extends ne{constructor(e){super(),this.apiUrl=e.apiUrl||it,this.getAuthHeadersCallback=e.getAuthHeaders}transferEventsTo(e){this.transfer(e)}async request(e,t={},i){let o=this.getAuthHeaders(t.headers),s={...t,headers:o,credentials:o.Authorization?void 0:"include"};this.emit("request",e,s);try{let r=await fetch(e,s);r.ok||await this.handleResponseError(r,i);let a=this.safeClone(r),u=this.safeClone(r);return this.emit("response",a,e),await this.parseResponse(u)}catch(r){throw this.emit("error",r,e),this.handleFetchError(r,i),r}}getAuthHeaders(e={}){let t=this.getAuthHeadersCallback();return{...e,...t}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return await e.json()}async handleResponseError(e,t){let i={};try{e.headers.get("content-type")?.includes("application/json")?i=await e.json():i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let o=i.message||i.error||`${t} failed due to API error`;throw e.status===401?F.authentication(o):F.api(o,e.status,i.code,i)}handleFetchError(e,t){throw e.name==="AbortError"?F.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?F.network(`${t} failed due to network error: ${e.message}`,e):e instanceof F?e:F.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${Oe}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${Oe}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${st}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:i,requestHeaders:o}=await this.prepareRequestPayload(e,t.tags),s={};t.deployToken?s={Authorization:`Bearer ${t.deployToken}`}:t.apiKey&&(s={Authorization:`Bearer ${t.apiKey}`});let r={method:"POST",body:i,headers:{...o,...s},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 o={deployment:t};i&&i.length>0&&(o.tags=i);let s={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},r=this.getAuthHeaders(s.headers),a={...s,headers:r,credentials:r.Authorization?void 0:"include"};this.emit("request",`${this.apiUrl}${E}/${encodeURIComponent(e)}`,a);try{let u=await fetch(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,a);u.ok||await this.handleResponseError(u,"Set Domain");let g=this.safeClone(u),v=this.safeClone(u);return this.emit("response",g,`${this.apiUrl}${E}/${encodeURIComponent(e)}`),{...await this.parseResponse(v),isCreate:u.status===201}}catch(u){throw this.emit("error",u,`${this.apiUrl}${E}/${encodeURIComponent(e)}`),this.handleFetchError(u,"Set Domain"),u}}async getDomain(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${E}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async confirmDomain(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${ot}`,{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 createCheckout(){return this.request(`${this.apiUrl}${de}/checkout`,{method:"POST",headers:{"Content-Type":"application/json"}},"Create checkout session")}async getSubscriptionStatus(){return this.request(`${this.apiUrl}${de}/status`,{method:"GET"},"Get subscription status")}async syncSubscription(e){return this.request(`${this.apiUrl}${de}/sync`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({subscriptionId:e})},"Sync subscription")}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 o={files:e.map(r=>r.path),index:i};return(await this.request(`${this.apiUrl}${rt}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw F.business("No files to deploy.");for(let t of e)if(!t.md5)throw F.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async prepareRequestPayload(e,t){if(y()==="browser")return{requestBody:this.createBrowserBody(e,t),requestHeaders:{}};if(y()==="node"){let{body:i,headers:o}=await this.createNodeBody(e,t);return{requestBody:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),requestHeaders:o}}else throw F.business("Unknown or unsupported execution environment")}createBrowserBody(e,t){let i=new FormData,o=[];for(let s of e){if(!(s.content instanceof File||s.content instanceof Blob))throw F.file(`Unsupported file.content type for browser FormData: ${s.path}`,s.path);let r=this.getBrowserContentType(s.content instanceof File?s.content:s.path),a=new File([s.content],s.path,{type:r});i.append("files[]",a),o.push(s.md5)}return i.append("checksums",JSON.stringify(o)),t&&t.length>0&&i.append("tags",JSON.stringify(t)),i}async createNodeBody(e,t){let{FormData:i,File:o}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new i,a=[];for(let p of e){let f=te(p.path),m;if(Buffer.isBuffer(p.content))m=new o([p.content],p.path,{type:f});else if(typeof Blob<"u"&&p.content instanceof Blob)m=new o([p.content],p.path,{type:f});else throw F.file(`Unsupported file.content type for Node.js FormData: ${p.path}`,p.path);let P=p.path.startsWith("/")?p.path:"/"+p.path;r.append("files[]",m,P),a.push(p.md5)}r.append("checksums",JSON.stringify(a)),t&&t.length>0&&r.append("tags",JSON.stringify(t));let u=new s(r),g=[];for await(let p of u.encode())g.push(Buffer.from(p));let v=Buffer.concat(g);return{body:v,headers:{"Content-Type":u.contentType,"Content-Length":Buffer.byteLength(v).toString()}}}getBrowserContentType(e){return typeof e=="string"?te(e):e.type||te(e.name)}};k();import{ShipError as _e}from"@shipstatic/types";D();import{DEFAULT_API as ct}from"@shipstatic/types";async function ut(n){let e=y();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(se(),Me));return t(n)}else return{}}function _(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||ct,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 j(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}V();import{DEPLOYMENT_CONFIG_FILENAME as Ue}from"@shipstatic/types";async function dt(){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:Ue,content:t,size:e.length,md5:i}}async function ze(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===Ue))return n;try{if(await e.checkSPA(n)){let o=await dt();return[...n,o]}}catch{}return n}function G(n,e,t,i,o){return{create:async(s,r={})=>{if(o&&!o()&&!r.deployToken&&!r.apiKey)throw new Error("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");t&&await t();let a=e?j(r,e):r,u=n();if(!i)throw new Error("processInput function is not provided.");let g=await i(s,a);return g=await ze(g,u,a),await u.deploy(g,a)},list:async()=>(t&&await t(),n().listDeployments()),remove:async s=>{t&&await t(),await n().removeDeployment(s)},get:async s=>(t&&await t(),n().getDeployment(s))}}function J(n,e){return{set:async(t,i,o)=>(e&&await e(),n().setDomain(t,i,o)),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 W(n,e){return{get:async()=>(e&&await e(),n().getAccount())}}function Y(n,e){return{create:async(t,i)=>(e&&await e(),n().createToken(t,i)),list:async()=>(e&&await e(),n().listTokens()),remove:async t=>{e&&await e(),await n().removeToken(t)}}}function X(n,e){return{checkout:async()=>(e&&await e(),n().createCheckout()),status:async()=>(e&&await e(),n().getSubscriptionStatus()),sync:async t=>(e&&await e(),n().syncSubscription(t))}}var L=class{constructor(e={}){this.initPromise=null;this._config=null;this.auth=null;this.clientOptions=e,e.deployToken?this.auth={type:"token",value:e.deployToken}:e.apiKey&&(this.auth={type:"apiKey",value:e.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(e);this.http=new x({...e,...t,getAuthHeaders:this.authHeadersCallback});let i=()=>this.ensureInitialized(),o=()=>this.http;this._deployments=G(o,this.clientOptions,i,(s,r)=>this.processInput(s,r),()=>this.hasAuth()),this._domains=J(o,i),this._account=W(o,i),this._tokens=Y(o,i),this._subscriptions=X(o,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}get subscriptions(){return this._subscriptions}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=R(),this._config)}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}setDeployToken(e){if(!e||typeof e!="string")throw _e.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw _e.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){if(!this.auth)return{};switch(this.auth.type){case"token":return{Authorization:`Bearer ${this.auth.value}`};case"apiKey":return{Authorization:`Bearer ${this.auth.value}`};default:return{}}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};D();se();import{ShipError as xe}from"@shipstatic/types";k();var c={};M(c,{ApiHttp:()=>x,DEFAULT_API:()=>Se,FILE_VALIDATION_STATUS:()=>d,JUNK_DIRECTORIES:()=>oe,Ship:()=>L,ShipError:()=>Ce,ShipErrorType:()=>Pe,__setTestEnvironment:()=>q,allValidFilesReady:()=>Ee,calculateMD5:()=>A,createAccountResource:()=>W,createDeploymentResource:()=>G,createDomainResource:()=>J,createSubscriptionResource:()=>X,createTokenResource:()=>Y,filterJunk:()=>I,formatFileSize:()=>K,getENV:()=>y,getValidFiles:()=>le,loadConfig:()=>ut,mergeDeployOptions:()=>j,optimizeDeployPaths:()=>O,pluralize:()=>ve,resolveConfig:()=>_,validateFiles:()=>Fe});var S={};l(S,Qt);import*as Qt from"@shipstatic/types";l(c,S);import{DEFAULT_API as Se}from"@shipstatic/types";V();function ve(n,e,t,i=!0){let o=n===1?e:t;return i?`${n} ${o}`:o}re();pe();D();import{FileValidationStatus as d}from"@shipstatic/types";import Le from"mime-db";var gt=new Set(Object.keys(Le)),St=new Map(Object.entries(Le).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"],o=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,o)).toFixed(e))+" "+i[o]}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],o=St.get(e);if(o&&!o.has(i))return!1}return!0}function Fe(n,e){let t=[],i=[];if(n.length===0){let s="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:s,errors:[s],isClientError:!0}}}if(n.length>e.maxFilesCount){let s=`Number of files (${n.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:n.map(r=>({...r,status:d.VALIDATION_FAILED,statusMessage:s})),validFiles:[],error:{error:"File Count Exceeded",details:s,errors:[s],isClientError:!0}}}let o=0;for(let s of n){let r=d.READY,a="Ready for upload",u=s.name?vt(s.name):{valid:!1,reason:"File name cannot be empty"};s.status===d.PROCESSING_ERROR?(r=d.PROCESSING_ERROR,a=s.statusMessage||"A file failed during processing.",t.push(`${s.name}: ${a}`)):!s.name||s.name.trim().length===0?(r=d.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${s.name||"(empty)"}: ${a}`)):s.name.includes("\0")?(r=d.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push(`${s.name}: ${a}`)):u.valid?s.size<=0?(r=d.EMPTY_FILE,a=s.size===0?"File is empty (0 bytes)":"File size must be positive",t.push(`${s.name}: ${a}`)):!s.type||s.type.trim().length===0?(r=d.VALIDATION_FAILED,a="File MIME type is required",t.push(`${s.name}: ${a}`)):e.allowedMimeTypes.some(g=>s.type.startsWith(g))?gt.has(s.type)?wt(s.name,s.type)?s.size>e.maxFileSize?(r=d.VALIDATION_FAILED,a=`File size (${K(s.size)}) exceeds limit of ${K(e.maxFileSize)}`,t.push(`${s.name}: ${a}`)):(o+=s.size,o>e.maxTotalSize&&(r=d.VALIDATION_FAILED,a=`Total size would exceed limit of ${K(e.maxTotalSize)}`,t.push(`${s.name}: ${a}`))):(r=d.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${s.name}: ${a}`)):(r=d.VALIDATION_FAILED,a=`Invalid MIME type "${s.type}"`,t.push(`${s.name}: ${a}`)):(r=d.VALIDATION_FAILED,a=`File type "${s.type}" is not allowed`,t.push(`${s.name}: ${a}`)):(r=d.VALIDATION_FAILED,a=u.reason||"Invalid file name",t.push(`${s.name}: ${a}`)),i.push({...s,status:r,statusMessage:a})}if(t.length>0){let s=i.find(a=>a.status!==d.READY&&a.status!==d.PENDING),r="Validation Failed";return s?.status===d.PROCESSING_ERROR?r="Processing Error":s?.status===d.EMPTY_FILE?r="Empty File":s?.statusMessage?.includes("File name cannot be empty")||s?.statusMessage?.includes("Invalid file name")||s?.statusMessage?.includes("File name contains")||s?.statusMessage?.includes("File name uses")||s?.statusMessage?.includes("File name cannot start")||s?.statusMessage?.includes("traversal")?r="Invalid File Name":s?.statusMessage?.includes("File size must be positive")?r="Invalid File Size":s?.statusMessage?.includes("MIME type is required")?r="Missing MIME Type":s?.statusMessage?.includes("Invalid MIME type")?r="Invalid MIME Type":s?.statusMessage?.includes("not allowed")?r="Invalid File Type":s?.statusMessage?.includes("extension does not match")?r="Extension Mismatch":s?.statusMessage?.includes("Total size")?r="Total Size Exceeded":s?.statusMessage?.includes("exceeds limit")&&(r="File Too Large"),{files:i.map(a=>({...a,status:d.VALIDATION_FAILED})),validFiles:[],error:{error:r,details:t.length===1?t[0]:`${t.length} file(s) failed validation`,errors:t,isClientError:!0}}}return{files:i,validFiles:i,error:null}}function le(n){return n.filter(e=>e.status===d.READY)}function Ee(n){return le(n).length>0}import{ShipError as Ce,ShipErrorType as Pe}from"@shipstatic/types";l(h,c);se();k();k();Te();D();var Q=class extends L{constructor(e={}){if(y()!=="node")throw xe.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return _(e,{})}async loadFullConfig(){try{let e=await z(this.clientOptions.configFile),t=_(this.clientOptions,e),i=new x({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback});this.replaceHttpClient(i);let o=await this.http.getConfig();U(o)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#e(e))throw xe.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw xe.business("No files to deploy.");let{convertDeployInput:i}=await Promise.resolve().then(()=>(Xe(),Ye));return i(e,t,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},Re=Q;l(ee,h);export{x as ApiHttp,Se as DEFAULT_API,d as FILE_VALIDATION_STATUS,oe as JUNK_DIRECTORIES,Q as Ship,Ce as ShipError,Pe as ShipErrorType,q as __setTestEnvironment,Ee as allValidFilesReady,A as calculateMD5,W as createAccountResource,G as createDeploymentResource,J as createDomainResource,X as createSubscriptionResource,Y as createTokenResource,Re as default,I as filterJunk,K as formatFileSize,R as getCurrentConfig,y as getENV,le as getValidFiles,z as loadConfig,j as mergeDeployOptions,O as optimizeDeployPaths,ve as pluralize,Z as processFilesForNode,_ as resolveConfig,U as setConfig,U as setPlatformConfig,Fe as validateFiles};
2
2
  //# sourceMappingURL=index.js.map