@shipstatic/ship 0.3.2 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -10
- package/dist/browser.d.ts +95 -5
- package/dist/browser.js +4 -4
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +21 -21
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +91 -1
- package/dist/index.d.ts +91 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/dist/index.d.cts
CHANGED
|
@@ -439,6 +439,96 @@ declare function __setTestEnvironment(env: ExecutionEnvironment | null): void;
|
|
|
439
439
|
*/
|
|
440
440
|
declare function getENV(): ExecutionEnvironment;
|
|
441
441
|
|
|
442
|
+
/**
|
|
443
|
+
* @file File validation utilities for Ship SDK
|
|
444
|
+
* Provides client-side validation for file uploads before deployment
|
|
445
|
+
*/
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* File status constants for validation state tracking
|
|
449
|
+
*/
|
|
450
|
+
declare const FILE_VALIDATION_STATUS: {
|
|
451
|
+
readonly PENDING: "pending";
|
|
452
|
+
readonly PROCESSING_ERROR: "processing_error";
|
|
453
|
+
readonly EMPTY_FILE: "empty_file";
|
|
454
|
+
readonly VALIDATION_FAILED: "validation_failed";
|
|
455
|
+
readonly READY: "ready";
|
|
456
|
+
};
|
|
457
|
+
type FileValidationStatus = (typeof FILE_VALIDATION_STATUS)[keyof typeof FILE_VALIDATION_STATUS];
|
|
458
|
+
/**
|
|
459
|
+
* Client-side validation error structure
|
|
460
|
+
*/
|
|
461
|
+
interface ValidationError {
|
|
462
|
+
error: string;
|
|
463
|
+
details: string;
|
|
464
|
+
errors: string[];
|
|
465
|
+
isClientError: true;
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* Minimal file interface required for validation
|
|
469
|
+
*/
|
|
470
|
+
interface ValidatableFile {
|
|
471
|
+
name: string;
|
|
472
|
+
size: number;
|
|
473
|
+
type: string;
|
|
474
|
+
status?: string;
|
|
475
|
+
statusMessage?: string;
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* File validation result
|
|
479
|
+
*
|
|
480
|
+
* NOTE: Validation is ATOMIC - if any file fails validation, ALL files are rejected.
|
|
481
|
+
* This ensures deployments are all-or-nothing for data integrity.
|
|
482
|
+
*/
|
|
483
|
+
interface FileValidationResult<T extends ValidatableFile> {
|
|
484
|
+
/** All files with updated status */
|
|
485
|
+
files: T[];
|
|
486
|
+
/** Files that passed validation (empty if ANY file failed - atomic validation) */
|
|
487
|
+
validFiles: T[];
|
|
488
|
+
/** Validation error if any files failed */
|
|
489
|
+
error: ValidationError | null;
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Format file size to human-readable string
|
|
493
|
+
*/
|
|
494
|
+
declare function formatFileSize(bytes: number, decimals?: number): string;
|
|
495
|
+
/**
|
|
496
|
+
* Validate files against configuration limits
|
|
497
|
+
*
|
|
498
|
+
* ATOMIC VALIDATION: If ANY file fails validation, ALL files are rejected.
|
|
499
|
+
* This ensures deployments are all-or-nothing for data integrity.
|
|
500
|
+
*
|
|
501
|
+
* @param files - Array of files to validate
|
|
502
|
+
* @param config - Validation configuration from ship.getConfig()
|
|
503
|
+
* @returns Validation result with updated file status
|
|
504
|
+
*
|
|
505
|
+
* @example
|
|
506
|
+
* ```typescript
|
|
507
|
+
* const config = await ship.getConfig();
|
|
508
|
+
* const result = validateFiles(files, config);
|
|
509
|
+
*
|
|
510
|
+
* if (result.error) {
|
|
511
|
+
* // Validation failed - result.validFiles will be empty
|
|
512
|
+
* console.error(result.error.details);
|
|
513
|
+
* // Show individual file errors:
|
|
514
|
+
* result.files.forEach(f => console.log(`${f.name}: ${f.statusMessage}`));
|
|
515
|
+
* } else {
|
|
516
|
+
* // All files valid - safe to upload
|
|
517
|
+
* await ship.deploy(result.validFiles);
|
|
518
|
+
* }
|
|
519
|
+
* ```
|
|
520
|
+
*/
|
|
521
|
+
declare function validateFiles<T extends ValidatableFile>(files: T[], config: ConfigResponse): FileValidationResult<T>;
|
|
522
|
+
/**
|
|
523
|
+
* Get only the valid files from validation results
|
|
524
|
+
*/
|
|
525
|
+
declare function getValidFiles<T extends ValidatableFile>(files: T[]): T[];
|
|
526
|
+
/**
|
|
527
|
+
* Check if all valid files have required properties for upload
|
|
528
|
+
* (Can be extended to check for MD5, etc.)
|
|
529
|
+
*/
|
|
530
|
+
declare function allValidFilesReady<T extends ValidatableFile>(files: T[]): boolean;
|
|
531
|
+
|
|
442
532
|
/**
|
|
443
533
|
* @file Manages loading and validation of client configuration.
|
|
444
534
|
* This module uses `cosmiconfig` to find and load configuration from various
|
|
@@ -513,4 +603,4 @@ declare class Ship extends Ship$1 {
|
|
|
513
603
|
protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
|
|
514
604
|
}
|
|
515
605
|
|
|
516
|
-
export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, getCurrentConfig, getENV, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig, setConfig as setPlatformConfig };
|
|
606
|
+
export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, FILE_VALIDATION_STATUS, type FileValidationResult, type FileValidationStatus, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, 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 };
|
package/dist/index.d.ts
CHANGED
|
@@ -439,6 +439,96 @@ declare function __setTestEnvironment(env: ExecutionEnvironment | null): void;
|
|
|
439
439
|
*/
|
|
440
440
|
declare function getENV(): ExecutionEnvironment;
|
|
441
441
|
|
|
442
|
+
/**
|
|
443
|
+
* @file File validation utilities for Ship SDK
|
|
444
|
+
* Provides client-side validation for file uploads before deployment
|
|
445
|
+
*/
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* File status constants for validation state tracking
|
|
449
|
+
*/
|
|
450
|
+
declare const FILE_VALIDATION_STATUS: {
|
|
451
|
+
readonly PENDING: "pending";
|
|
452
|
+
readonly PROCESSING_ERROR: "processing_error";
|
|
453
|
+
readonly EMPTY_FILE: "empty_file";
|
|
454
|
+
readonly VALIDATION_FAILED: "validation_failed";
|
|
455
|
+
readonly READY: "ready";
|
|
456
|
+
};
|
|
457
|
+
type FileValidationStatus = (typeof FILE_VALIDATION_STATUS)[keyof typeof FILE_VALIDATION_STATUS];
|
|
458
|
+
/**
|
|
459
|
+
* Client-side validation error structure
|
|
460
|
+
*/
|
|
461
|
+
interface ValidationError {
|
|
462
|
+
error: string;
|
|
463
|
+
details: string;
|
|
464
|
+
errors: string[];
|
|
465
|
+
isClientError: true;
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* Minimal file interface required for validation
|
|
469
|
+
*/
|
|
470
|
+
interface ValidatableFile {
|
|
471
|
+
name: string;
|
|
472
|
+
size: number;
|
|
473
|
+
type: string;
|
|
474
|
+
status?: string;
|
|
475
|
+
statusMessage?: string;
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* File validation result
|
|
479
|
+
*
|
|
480
|
+
* NOTE: Validation is ATOMIC - if any file fails validation, ALL files are rejected.
|
|
481
|
+
* This ensures deployments are all-or-nothing for data integrity.
|
|
482
|
+
*/
|
|
483
|
+
interface FileValidationResult<T extends ValidatableFile> {
|
|
484
|
+
/** All files with updated status */
|
|
485
|
+
files: T[];
|
|
486
|
+
/** Files that passed validation (empty if ANY file failed - atomic validation) */
|
|
487
|
+
validFiles: T[];
|
|
488
|
+
/** Validation error if any files failed */
|
|
489
|
+
error: ValidationError | null;
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Format file size to human-readable string
|
|
493
|
+
*/
|
|
494
|
+
declare function formatFileSize(bytes: number, decimals?: number): string;
|
|
495
|
+
/**
|
|
496
|
+
* Validate files against configuration limits
|
|
497
|
+
*
|
|
498
|
+
* ATOMIC VALIDATION: If ANY file fails validation, ALL files are rejected.
|
|
499
|
+
* This ensures deployments are all-or-nothing for data integrity.
|
|
500
|
+
*
|
|
501
|
+
* @param files - Array of files to validate
|
|
502
|
+
* @param config - Validation configuration from ship.getConfig()
|
|
503
|
+
* @returns Validation result with updated file status
|
|
504
|
+
*
|
|
505
|
+
* @example
|
|
506
|
+
* ```typescript
|
|
507
|
+
* const config = await ship.getConfig();
|
|
508
|
+
* const result = validateFiles(files, config);
|
|
509
|
+
*
|
|
510
|
+
* if (result.error) {
|
|
511
|
+
* // Validation failed - result.validFiles will be empty
|
|
512
|
+
* console.error(result.error.details);
|
|
513
|
+
* // Show individual file errors:
|
|
514
|
+
* result.files.forEach(f => console.log(`${f.name}: ${f.statusMessage}`));
|
|
515
|
+
* } else {
|
|
516
|
+
* // All files valid - safe to upload
|
|
517
|
+
* await ship.deploy(result.validFiles);
|
|
518
|
+
* }
|
|
519
|
+
* ```
|
|
520
|
+
*/
|
|
521
|
+
declare function validateFiles<T extends ValidatableFile>(files: T[], config: ConfigResponse): FileValidationResult<T>;
|
|
522
|
+
/**
|
|
523
|
+
* Get only the valid files from validation results
|
|
524
|
+
*/
|
|
525
|
+
declare function getValidFiles<T extends ValidatableFile>(files: T[]): T[];
|
|
526
|
+
/**
|
|
527
|
+
* Check if all valid files have required properties for upload
|
|
528
|
+
* (Can be extended to check for MD5, etc.)
|
|
529
|
+
*/
|
|
530
|
+
declare function allValidFilesReady<T extends ValidatableFile>(files: T[]): boolean;
|
|
531
|
+
|
|
442
532
|
/**
|
|
443
533
|
* @file Manages loading and validation of client configuration.
|
|
444
534
|
* This module uses `cosmiconfig` to find and load configuration from various
|
|
@@ -513,4 +603,4 @@ declare class Ship extends Ship$1 {
|
|
|
513
603
|
protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
|
|
514
604
|
}
|
|
515
605
|
|
|
516
|
-
export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, getCurrentConfig, getENV, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig, setConfig as setPlatformConfig };
|
|
606
|
+
export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, FILE_VALIDATION_STATUS, type FileValidationResult, type FileValidationStatus, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, 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 };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Ee=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Ge=Object.prototype.hasOwnProperty;var x=(n,e)=>()=>(n&&(e=n(n=0)),e);var N=(n,e)=>{for(var t in e)Ee(n,t,{get:e[t],enumerable:!0})},Ce=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of He(e))!Ge.call(n,i)&&i!==t&&Ee(n,i,{get:()=>e[i],enumerable:!(o=je(e,i))||o.enumerable});return n},p=(n,e,t)=>(Ce(n,e,"default"),t&&Ce(t,e,"default"));var Fe={};N(Fe,{__setTestEnvironment:()=>K,getENV:()=>h});function K(n){pe=n}function Je(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function h(){return pe||Je()}var pe,v=x(()=>{"use strict";pe=null});import{ShipError as Ze}from"@shipstatic/types";function B(n){le=n}function R(){if(le===null)throw Ze.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return le}var le,$=x(()=>{"use strict";le=null});var be={};N(be,{loadConfig:()=>I});import{z as _}from"zod";import{ShipError as me}from"@shipstatic/types";function Re(n){try{return Qe.parse(n)}catch(e){if(e instanceof _.ZodError){let t=e.issues[0],o=t.path.length>0?` at ${t.path.join(".")}`:"";throw me.config(`Configuration validation failed${o}: ${t.message}`)}throw me.config("Configuration validation failed")}}async function et(n){try{if(h()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),o=e(fe,{searchPlaces:[`.${fe}rc`,"package.json",`${t.homedir()}/.${fe}rc`],stopDir:t.homedir()}),i;if(n?i=o.load(n):i=o.search(),i&&i.config)return Re(i.config)}catch(e){if(e instanceof me)throw e}return{}}async function I(n){if(h()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await et(n),o={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Re(o)}var fe,Qe,te=x(()=>{"use strict";v();fe="ship",Qe=_.object({apiUrl:_.string().url().optional(),apiKey:_.string().optional(),deployToken:_.string().optional()}).strict()});import{ShipError as L}from"@shipstatic/types";async function ot(n){let e=(await import("spark-md5")).default;return new Promise((t,o)=>{let r=Math.ceil(n.size/2097152),s=0,l=new e.ArrayBuffer,f=new FileReader,w=()=>{let g=s*2097152,a=Math.min(g+2097152,n.size);f.readAsArrayBuffer(n.slice(g,a))};f.onload=g=>{let a=g.target?.result;if(!a){o(L.business("Failed to read file chunk"));return}l.append(a),s++,s<r?w():t({md5:l.end()})},f.onerror=()=>{o(L.business("Failed to calculate MD5: FileReader error"))},w()})}async function it(n){let e=await import("crypto");if(Buffer.isBuffer(n)){let o=e.createHash("md5");return o.update(n),{md5:o.digest("hex")}}let t=await import("fs");return new Promise((o,i)=>{let r=e.createHash("md5"),s=t.createReadStream(n);s.on("error",l=>i(L.business(`Failed to read file for MD5: ${l.message}`))),s.on("data",l=>r.update(l)),s.on("end",()=>o({md5:r.digest("hex")}))})}async function b(n){let e=h();if(e==="browser"){if(!(n instanceof Blob))throw L.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return ot(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw L.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return it(n)}throw L.business("Unknown or unsupported execution environment for MD5 calculation.")}var j=x(()=>{"use strict";v()});import{isJunk as st}from"junk";function O(n){return!n||n.length===0?[]:n.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let o=t[t.length-1];if(st(o))return!1;let i=t.slice(0,-1);for(let r of i)if(ne.some(s=>r.toLowerCase()===s.toLowerCase()))return!1;return!0})}var ne,oe=x(()=>{"use strict";ne=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Oe(n){if(!n||n.length===0)return"";let e=n.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(r=>r.split("/").filter(Boolean)),o=[],i=Math.min(...t.map(r=>r.length));for(let r=0;r<i;r++){let s=t[0][r];if(t.every(l=>l[r]===s))o.push(s);else break}return o.join("/")}function ie(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var he=x(()=>{"use strict"});function A(n,e={}){if(e.flatten===!1)return n.map(o=>({path:ie(o),name:ye(o)}));let t=at(n);return n.map(o=>{let i=ie(o);if(t){let r=t.endsWith("/")?t:`${t}/`;i.startsWith(r)&&(i=i.substring(r.length))}return i||(i=ye(o)),{path:i,name:ye(o)}})}function at(n){if(!n.length)return"";let t=n.map(r=>ie(r)).map(r=>r.split("/")),o=[],i=Math.min(...t.map(r=>r.length));for(let r=0;r<i-1;r++){let s=t[0][r];if(t.every(l=>l[r]===s))o.push(s);else break}return o.join("/")}function ye(n){return n.split(/[/\\]/).pop()||n}var re=x(()=>{"use strict";he()});import{ShipError as U}from"@shipstatic/types";import*as k from"fs";import*as S from"path";function Ae(n){let e=[];try{let t=k.readdirSync(n);for(let o of t){let i=S.join(n,o),r=k.statSync(i);if(r.isDirectory()){let s=Ae(i);e.push(...s)}else r.isFile()&&e.push(i)}}catch(t){console.error(`Error reading directory ${n}:`,t)}return e}async function W(n,e={}){if(h()!=="node")throw U.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(m=>{let d=S.resolve(m);try{return k.statSync(d).isDirectory()?Ae(d):[d]}catch{throw U.file(`Path does not exist: ${m}`,m)}}),o=[...new Set(t)],i=O(o);if(i.length===0)return[];let r=n.map(m=>S.resolve(m)),s=Oe(r.map(m=>{try{return k.statSync(m).isDirectory()?m:S.dirname(m)}catch{return S.dirname(m)}})),l=i.map(m=>{if(s&&s.length>0){let d=S.relative(s,m);if(d&&typeof d=="string"&&!d.startsWith(".."))return d.replace(/\\/g,"/")}return S.basename(m)}),f=A(l,{flatten:e.pathDetect!==!1}),w=[],g=0,a=R();for(let m=0;m<i.length;m++){let d=i[m],E=f[m].path;try{let F=k.statSync(d);if(F.size===0){console.warn(`Skipping empty file: ${d}`);continue}if(F.size>a.maxFileSize)throw U.business(`File ${d} is too large. Maximum allowed size is ${a.maxFileSize/(1024*1024)}MB.`);if(g+=F.size,g>a.maxTotalSize)throw U.business(`Total deploy size is too large. Maximum allowed is ${a.maxTotalSize/(1024*1024)}MB.`);let se=k.readFileSync(d),{md5:qe}=await b(se);if(E.includes("\0")||E.includes("/../")||E.startsWith("../")||E.endsWith("/.."))throw U.business(`Security error: Unsafe file path "${E}" for file: ${d}`);w.push({path:E,content:se,size:se.length,md5:qe})}catch(F){if(F instanceof U&&F.isClientError&&F.isClientError())throw F;console.error(`Could not process file ${d}:`,F)}}if(w.length>a.maxFilesCount)throw U.business(`Too many files to deploy. Maximum allowed is ${a.maxFilesCount} files.`);return w}var Se=x(()=>{"use strict";v();j();oe();$();re();he()});import{ShipError as Ue}from"@shipstatic/types";async function Ne(n,e={}){let{getENV:t}=await Promise.resolve().then(()=>(v(),Fe));if(t()!=="browser")throw Ue.business("processFilesForBrowser can only be called in a browser environment.");let o=Array.isArray(n)?n:Array.from(n),i=o.map(a=>a.webkitRelativePath||a.name),r=A(i,{flatten:e.pathDetect!==!1}),s=[];for(let a=0;a<o.length;a++){let m=o[a],d=r[a].path;if(d.includes("..")||d.includes("\0"))throw Ue.business(`Security error: Unsafe file path "${d}" for file: ${m.name}`);s.push({file:m,relativePath:d})}let l=s.map(a=>a.relativePath),f=O(l),w=new Set(f),g=[];for(let a of s){if(!w.has(a.relativePath))continue;let{md5:m}=await b(a.file);g.push({content:a.file,path:a.relativePath,size:a.file.size,md5:m})}return g}var Be=x(()=>{"use strict";j();oe();re()});var Ke={};N(Ke,{convertBrowserInput:()=>Me,convertDeployInput:()=>pt,convertNodeInput:()=>De});import{ShipError as D}from"@shipstatic/types";function Ie(n,e={}){let t=R();if(!e.skipEmptyCheck&&n.length===0)throw D.business("No files to deploy.");if(n.length>t.maxFilesCount)throw D.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let o=0;for(let i of n){if(i.size>t.maxFileSize)throw D.business(`File ${i.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(o+=i.size,o>t.maxTotalSize)throw D.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function ze(n,e){if(e==="node"){if(!Array.isArray(n))throw D.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(n.length===0)throw D.business("No files to deploy.");if(!n.every(t=>typeof t=="string"))throw D.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&n instanceof HTMLInputElement&&!n.files)throw D.business("No files selected in HTMLInputElement")}function Le(n){let e=n.map(t=>({name:t.path,size:t.size}));return Ie(e,{skipEmptyCheck:!0}),n.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),n}async function De(n,e={}){ze(n,"node");let t=await W(n,e);return Le(t)}async function Me(n,e={}){ze(n,"browser");let t;if(n instanceof HTMLInputElement)t=Array.from(n.files);else if(typeof n=="object"&&n!==null&&typeof n.length=="number"&&typeof n.item=="function")t=Array.from(n);else if(Array.isArray(n)){if(n.length>0&&typeof n[0]=="string")throw D.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=n}else throw D.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=t.filter(i=>i.size===0?(console.warn(`Skipping empty file: ${i.name}`),!1):!0),Ie(t);let o=await Ne(t,e);return Le(o)}async function pt(n,e={},t){let o=h();if(o!=="node"&&o!=="browser")throw D.business("Unsupported execution environment.");let i;if(o==="node")if(typeof n=="string")i=await De([n],e);else if(Array.isArray(n)&&n.every(r=>typeof r=="string"))i=await De(n,e);else throw D.business("Invalid input type for Node.js environment. Expected string[] file paths.");else i=await Me(n,e);return i}var _e=x(()=>{"use strict";v();Se();Be();$()});var X={};N(X,{ApiHttp:()=>T,DEFAULT_API:()=>de,JUNK_DIRECTORIES:()=>ne,Ship:()=>Y,ShipError:()=>ge,ShipErrorType:()=>we,__setTestEnvironment:()=>K,calculateMD5:()=>b,createAccountResource:()=>J,createDeploymentResource:()=>H,createDomainResource:()=>G,createTokenResource:()=>V,default:()=>Pe,filterJunk:()=>O,getCurrentConfig:()=>R,getENV:()=>h,loadConfig:()=>I,mergeDeployOptions:()=>q,optimizeDeployPaths:()=>A,pluralize:()=>ue,processFilesForNode:()=>W,resolveConfig:()=>z,setConfig:()=>B,setPlatformConfig:()=>B});var u={};N(u,{ApiHttp:()=>T,DEFAULT_API:()=>de,JUNK_DIRECTORIES:()=>ne,Ship:()=>Y,ShipError:()=>ge,ShipErrorType:()=>we,__setTestEnvironment:()=>K,calculateMD5:()=>b,createAccountResource:()=>J,createDeploymentResource:()=>H,createDomainResource:()=>G,createTokenResource:()=>V,default:()=>Pe,filterJunk:()=>O,getCurrentConfig:()=>R,getENV:()=>h,loadConfig:()=>I,mergeDeployOptions:()=>q,optimizeDeployPaths:()=>A,pluralize:()=>ue,processFilesForNode:()=>W,resolveConfig:()=>z,setConfig:()=>B,setPlatformConfig:()=>B});import xe from"mime-db";var ae={};for(let n in xe){let e=xe[n];e&&e.extensions&&e.extensions.forEach(t=>{ae[t]||(ae[t]=n)})}function Z(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return ae[e]||"application/octet-stream"}import{ShipError as P,DEFAULT_API as Ve}from"@shipstatic/types";var Q=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let o=this.handlers.get(e);o&&(o.delete(t),o.size===0&&this.handlers.delete(e))}emit(e,...t){let o=this.handlers.get(e);if(!o)return;let i=Array.from(o);for(let r of i)try{r(...t)}catch(s){o.delete(r),e!=="error"&&setTimeout(()=>{s instanceof Error?this.emit("error",s,String(e)):this.emit("error",new Error(String(s)),String(e))},0)}}transfer(e){this.handlers.forEach((t,o)=>{t.forEach(i=>{e.on(o,i)})})}clear(){this.handlers.clear()}};v();var ee="/deployments",Te="/ping",C="/domains",We="/config",Ye="/account",ce="/tokens",Xe="/spa-check",T=class extends Q{constructor(e){super(),this.apiUrl=e.apiUrl||Ve,this.apiKey=e.apiKey??"",this.deployToken=e.deployToken??""}transferEventsTo(e){this.transfer(e)}async request(e,t={},o){let i=this.getAuthHeaders(t.headers),r={...t,headers:i,credentials:this.needsCredentials(i)?"include":void 0};this.emit("request",e,r);try{let s=await fetch(e,r);s.ok||await this.handleResponseError(s,o);let l=this.safeClone(s),f=this.safeClone(s);return this.emit("response",l,e),await this.parseResponse(f)}catch(s){throw this.emit("error",s,e),this.handleFetchError(s,o),s}}getAuthHeaders(e={}){let t={...e};return this.deployToken?t.Authorization=`Bearer ${this.deployToken}`:this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}needsCredentials(e){return!this.apiKey&&!this.deployToken&&!e.Authorization}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return await e.json()}async handleResponseError(e,t){let o={};try{e.headers.get("content-type")?.includes("application/json")?o=await e.json():o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}let i=o.message||o.error||`${t} failed due to API error`;throw e.status===401?P.authentication(i):P.api(i,e.status,o.code,o)}handleFetchError(e,t){throw e.name==="AbortError"?P.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?P.network(`${t} failed due to network error: ${e.message}`,e):e instanceof P?e:P.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${Te}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${Te}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${We}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:o,requestHeaders:i}=await this.prepareRequestPayload(e,t.tags),r={};t.deployToken?r={Authorization:`Bearer ${t.deployToken}`}:t.apiKey&&(r={Authorization:`Bearer ${t.apiKey}`});let s={method:"POST",body:o,headers:{...i,...r},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${ee}`,s,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${ee}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${ee}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${ee}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,t,o){let i={deployment:t};o&&o.length>0&&(i.tags=o);let r={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},s=this.getAuthHeaders(r.headers),l={...r,headers:s,credentials:this.needsCredentials(s)?"include":void 0};this.emit("request",`${this.apiUrl}${C}/${encodeURIComponent(e)}`,l);try{let f=await fetch(`${this.apiUrl}${C}/${encodeURIComponent(e)}`,l);f.ok||await this.handleResponseError(f,"Set Domain");let w=this.safeClone(f),g=this.safeClone(f);return this.emit("response",w,`${this.apiUrl}${C}/${encodeURIComponent(e)}`),{...await this.parseResponse(g),isCreate:f.status===201}}catch(f){throw this.emit("error",f,`${this.apiUrl}${C}/${encodeURIComponent(e)}`),this.handleFetchError(f,"Set Domain"),f}}async getDomain(e){return await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${C}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async confirmDomain(e){return await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${Ye}`,{method:"GET"},"Get Account")}async createToken(e,t){let o={};return e!==void 0&&(o.ttl=e),t&&t.length>0&&(o.tags=t),await this.request(`${this.apiUrl}${ce}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${ce}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${ce}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}async checkSPA(e){let t=e.find(s=>s.path==="index.html"||s.path==="/index.html");if(!t||t.size>100*1024)return!1;let o;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))o=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)o=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)o=await t.content.text();else return!1;let i={files:e.map(s=>s.path),index:o};return(await this.request(`${this.apiUrl}${Xe}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw P.business("No files to deploy.");for(let t of e)if(!t.md5)throw P.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async prepareRequestPayload(e,t){if(h()==="browser")return{requestBody:this.createBrowserBody(e,t),requestHeaders:{}};if(h()==="node"){let{body:o,headers:i}=await this.createNodeBody(e,t);return{requestBody:o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength),requestHeaders:i}}else throw P.business("Unknown or unsupported execution environment")}createBrowserBody(e,t){let o=new FormData,i=[];for(let r of e){if(!(r.content instanceof File||r.content instanceof Blob))throw P.file(`Unsupported file.content type for browser FormData: ${r.path}`,r.path);let s=this.getBrowserContentType(r.content instanceof File?r.content:r.path),l=new File([r.content],r.path,{type:s});o.append("files[]",l),i.push(r.md5)}return o.append("checksums",JSON.stringify(i)),t&&t.length>0&&o.append("tags",JSON.stringify(t)),o}async createNodeBody(e,t){let{FormData:o,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),s=new o,l=[];for(let a of e){let m=Z(a.path),d;if(Buffer.isBuffer(a.content))d=new i([a.content],a.path,{type:m});else if(typeof Blob<"u"&&a.content instanceof Blob)d=new i([a.content],a.path,{type:m});else throw P.file(`Unsupported file.content type for Node.js FormData: ${a.path}`,a.path);let E=a.path.startsWith("/")?a.path:"/"+a.path;s.append("files[]",d,E),l.push(a.md5)}s.append("checksums",JSON.stringify(l)),t&&t.length>0&&s.append("tags",JSON.stringify(t));let f=new r(s),w=[];for await(let a of f.encode())w.push(Buffer.from(a));let g=Buffer.concat(w);return{body:g,headers:{"Content-Type":f.contentType,"Content-Length":Buffer.byteLength(g).toString()}}}getBrowserContentType(e){return typeof e=="string"?Z(e):e.type||Z(e.name)}};$();v();import{DEFAULT_API as tt}from"@shipstatic/types";async function nt(n){let e=h();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(te(),be));return t(n)}else return{}}function z(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||tt,apiKey:n.apiKey!==void 0?n.apiKey:e.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:e.deployToken},o={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(o.apiKey=t.apiKey),t.deployToken!==void 0&&(o.deployToken=t.deployToken),o}function q(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.onProgressStats===void 0&&e.onProgressStats!==void 0&&(t.onProgressStats=e.onProgressStats),t}j();import{DEPLOYMENT_CONFIG_FILENAME as ke}from"@shipstatic/types";async function rt(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:o}=await b(t);return{path:ke,content:t,size:e.length,md5:o}}async function $e(n,e,t){if(t.spaDetect===!1||n.some(o=>o.path===ke))return n;try{if(await e.checkSPA(n)){let i=await rt();return[...n,i]}}catch{}return n}function H(n,e,t,o){return{create:async(i,r={})=>{t&&await t();let s=e?q(r,e):r,l=n();if(!o)throw new Error("processInput function is not provided.");let f=await o(i,s);return f=await $e(f,l,s),await l.deploy(f,s)},list:async()=>(t&&await t(),n().listDeployments()),remove:async i=>{t&&await t(),await n().removeDeployment(i)},get:async i=>(t&&await t(),n().getDeployment(i))}}function G(n,e){return{set:async(t,o,i)=>(e&&await e(),n().setDomain(t,o,i)),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 V(n,e){return{create:async(t,o)=>(e&&await e(),n().createToken(t,o)),list:async()=>(e&&await e(),n().listTokens()),remove:async t=>{e&&await e(),await n().removeToken(t)}}}var M=class{constructor(e={}){this.initPromise=null;this._config=null;this.clientOptions=e;let t=this.resolveInitialConfig(e);this.http=new T({...e,...t});let o=()=>this.ensureInitialized(),i=()=>this.http;this._deployments=H(i,this.clientOptions,o,(r,s)=>this.processInput(r,s)),this._domains=G(i,o),this._account=J(i,o),this._tokens=V(i,o)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=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}};v();te();import{ShipError as ve}from"@shipstatic/types";$();var c={};N(c,{ApiHttp:()=>T,DEFAULT_API:()=>de,JUNK_DIRECTORIES:()=>ne,Ship:()=>M,ShipError:()=>ge,ShipErrorType:()=>we,__setTestEnvironment:()=>K,calculateMD5:()=>b,createAccountResource:()=>J,createDeploymentResource:()=>H,createDomainResource:()=>G,createTokenResource:()=>V,filterJunk:()=>O,getENV:()=>h,loadConfig:()=>nt,mergeDeployOptions:()=>q,optimizeDeployPaths:()=>A,pluralize:()=>ue,resolveConfig:()=>z});var y={};p(y,Lt);import*as Lt from"@shipstatic/types";p(c,y);import{DEFAULT_API as de}from"@shipstatic/types";j();function ue(n,e,t,o=!0){let i=n===1?e:t;return o?`${n} ${i}`:i}oe();re();v();import{ShipError as ge,ShipErrorType as we}from"@shipstatic/types";p(u,c);te();$();$();Se();v();var Y=class extends M{constructor(e={}){if(h()!=="node")throw ve.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return z(e,{})}async loadFullConfig(){try{let e=await I(this.clientOptions.configFile),t=z(this.clientOptions,e),o=new T({...this.clientOptions,...t});this.replaceHttpClient(o);let i=await this.http.getConfig();B(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#e(e))throw ve.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw ve.business("No files to deploy.");let{convertDeployInput:o}=await Promise.resolve().then(()=>(_e(),Ke));return o(e,t,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},Pe=Y;p(X,u);export{T as ApiHttp,de as DEFAULT_API,ne as JUNK_DIRECTORIES,Y as Ship,ge as ShipError,we as ShipErrorType,K as __setTestEnvironment,b as calculateMD5,J as createAccountResource,H as createDeploymentResource,G as createDomainResource,V as createTokenResource,Pe as default,O as filterJunk,R as getCurrentConfig,h as getENV,I as loadConfig,q as mergeDeployOptions,A as optimizeDeployPaths,ue as pluralize,W as processFilesForNode,z as resolveConfig,B as setConfig,B as setPlatformConfig};
|
|
1
|
+
var Ae=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var T=(n,e)=>()=>(n&&(e=n(n=0)),e);var M=(n,e)=>{for(var t in e)Ae(n,t,{get:e[t],enumerable:!0})},Re=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Xe(e))!Ze.call(n,s)&&s!==t&&Ae(n,s,{get:()=>e[s],enumerable:!(i=Ye(e,s))||i.enumerable});return n},l=(n,e,t)=>(Re(n,e,"default"),t&&Re(t,e,"default"));var Ie={};M(Ie,{__setTestEnvironment:()=>q,getENV:()=>y});function q(n){fe=n}function Qe(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function y(){return fe||Qe()}var fe,w=T(()=>{"use strict";fe=null});import{ShipError as ot}from"@shipstatic/types";function _(n){ue=n}function A(){if(ue===null)throw ot.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 ke={};M(ke,{loadConfig:()=>L});import{z as V}from"zod";import{ShipError as he}from"@shipstatic/types";function Oe(n){try{return st.parse(n)}catch(e){if(e instanceof V.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 rt(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 Oe(s.config)}catch(e){if(e instanceof he)throw e}return{}}async function L(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 rt(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Oe(i)}var de,st,ie=T(()=>{"use strict";w();de="ship",st=V.object({apiUrl:V.string().url().optional(),apiKey:V.string().optional(),deployToken:V.string().optional()}).strict()});import{ShipError as z}from"@shipstatic/types";async function lt(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,S=()=>{let D=r*2097152,p=Math.min(D+2097152,n.size);f.readAsArrayBuffer(n.slice(D,p))};f.onload=D=>{let p=D.target?.result;if(!p){i(z.business("Failed to read file chunk"));return}a.append(p),r++,r<o?S():t({md5:a.end()})},f.onerror=()=>{i(z.business("Failed to calculate MD5: FileReader error"))},S()})}async function ct(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(z.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 z.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return lt(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw z.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return ct(n)}throw z.business("Unknown or unsupported execution environment for MD5 calculation.")}var G=T(()=>{"use strict";w()});import{isJunk as mt}from"junk";function O(n){return!n||n.length===0?[]:n.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let i=t[t.length-1];if(mt(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 _e(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 Se=T(()=>{"use strict"});function k(n,e={}){if(e.flatten===!1)return n.map(i=>({path:re(i),name:De(i)}));let t=ut(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 ut(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";Se()});import{ShipError as N}from"@shipstatic/types";import*as I from"fs";import*as v from"path";function Ue(n){let e=[];try{let t=I.readdirSync(n);for(let i of t){let s=v.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=v.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=O(i);if(s.length===0)return[];let o=n.map(m=>v.resolve(m)),r=_e(o.map(m=>{try{return I.statSync(m).isDirectory()?m:v.dirname(m)}catch{return v.dirname(m)}})),a=s.map(m=>{if(r&&r.length>0){let u=v.relative(r,m);if(u&&typeof u=="string"&&!u.startsWith(".."))return u.replace(/\\/g,"/")}return v.basename(m)}),f=k(a,{flatten:e.pathDetect!==!1}),S=[],D=0,p=A();for(let m=0;m<s.length;m++){let u=s[m],C=f[m].path;try{let x=I.statSync(u);if(x.size===0){console.warn(`Skipping empty file: ${u}`);continue}if(x.size>p.maxFileSize)throw N.business(`File ${u} is too large. Maximum allowed size is ${p.maxFileSize/(1024*1024)}MB.`);if(D+=x.size,D>p.maxTotalSize)throw N.business(`Total deploy size is too large. Maximum allowed is ${p.maxTotalSize/(1024*1024)}MB.`);let le=I.readFileSync(u),{md5:Je}=await b(le);if(C.includes("\0")||C.includes("/../")||C.startsWith("../")||C.endsWith("/.."))throw N.business(`Security error: Unsafe file path "${C}" for file: ${u}`);S.push({path:C,content:le,size:le.length,md5:Je})}catch(x){if(x instanceof N&&x.isClientError&&x.isClientError())throw x;console.error(`Could not process file ${u}:`,x)}}if(S.length>p.maxFilesCount)throw N.business(`Too many files to deploy. Maximum allowed is ${p.maxFilesCount} files.`);return S}var Pe=T(()=>{"use strict";w();G();se();$();ae();Se()});import{ShipError as ze}from"@shipstatic/types";async function Be(n,e={}){let{getENV:t}=await Promise.resolve().then(()=>(w(),Ie));if(t()!=="browser")throw ze.business("processFilesForBrowser can only be called in a browser environment.");let i=n,s=i.map(p=>p.webkitRelativePath||p.name),o=k(s,{flatten:e.pathDetect!==!1}),r=[];for(let p=0;p<i.length;p++){let m=i[p],u=o[p].path;if(u.includes("..")||u.includes("\0"))throw ze.business(`Security error: Unsafe file path "${u}" for file: ${m.name}`);r.push({file:m,relativePath:u})}let a=r.map(p=>p.relativePath),f=O(a),S=new Set(f),D=[];for(let p of r){if(!S.has(p.relativePath))continue;let{md5:m}=await b(p.file);D.push({content:p.file,path:p.relativePath,size:p.file.size,md5:m})}return D}var Ke=T(()=>{"use strict";G();se();ae()});var He={};M(He,{convertBrowserInput:()=>Ge,convertDeployInput:()=>St,convertNodeInput:()=>Ce});import{ShipError as P}from"@shipstatic/types";function qe(n,e={}){let t=A();if(!e.skipEmptyCheck&&n.length===0)throw P.business("No files to deploy.");if(n.length>t.maxFilesCount)throw P.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 P.business(`File ${s.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(i+=s.size,i>t.maxTotalSize)throw P.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 P.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(n.length===0)throw P.business("No files to deploy.");if(!n.every(t=>typeof t=="string"))throw P.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 qe(e,{skipEmptyCheck:!0}),n.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),n}async function Ce(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 P.business("Invalid input type for browser environment. Expected File[].");t=n}else throw P.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),qe(t);let i=await Be(t,e);return je(i)}async function St(n,e={},t){let i=y();if(i!=="node"&&i!=="browser")throw P.business("Unsupported execution environment.");let s;if(i==="node")if(typeof n=="string")s=await Ce([n],e);else if(Array.isArray(n)&&n.every(o=>typeof o=="string"))s=await Ce(n,e);else throw P.business("Invalid input type for Node.js environment. Expected string[] file paths.");else s=await Ge(n,e);return s}var We=T(()=>{"use strict";w();Pe();Ke();$()});var Q={};M(Q,{ApiHttp:()=>R,DEFAULT_API:()=>ye,FILE_VALIDATION_STATUS:()=>d,JUNK_DIRECTORIES:()=>oe,Ship:()=>Z,ShipError:()=>Fe,ShipErrorType:()=>Ee,__setTestEnvironment:()=>q,allValidFilesReady:()=>we,calculateMD5:()=>b,createAccountResource:()=>J,createDeploymentResource:()=>H,createDomainResource:()=>W,createTokenResource:()=>Y,default:()=>xe,filterJunk:()=>O,formatFileSize:()=>K,getCurrentConfig:()=>A,getENV:()=>y,getValidFiles:()=>pe,loadConfig:()=>L,mergeDeployOptions:()=>j,optimizeDeployPaths:()=>k,pluralize:()=>ge,processFilesForNode:()=>X,resolveConfig:()=>U,setConfig:()=>_,setPlatformConfig:()=>_,validateFiles:()=>ve});var h={};M(h,{ApiHttp:()=>R,DEFAULT_API:()=>ye,FILE_VALIDATION_STATUS:()=>d,JUNK_DIRECTORIES:()=>oe,Ship:()=>Z,ShipError:()=>Fe,ShipErrorType:()=>Ee,__setTestEnvironment:()=>q,allValidFilesReady:()=>we,calculateMD5:()=>b,createAccountResource:()=>J,createDeploymentResource:()=>H,createDomainResource:()=>W,createTokenResource:()=>Y,default:()=>xe,filterJunk:()=>O,formatFileSize:()=>K,getCurrentConfig:()=>A,getENV:()=>y,getValidFiles:()=>pe,loadConfig:()=>L,mergeDeployOptions:()=>j,optimizeDeployPaths:()=>k,pluralize:()=>ge,processFilesForNode:()=>X,resolveConfig:()=>U,setConfig:()=>_,setPlatformConfig:()=>_,validateFiles:()=>ve});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 et}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()}};w();var ne="/deployments",$e="/ping",E="/domains",tt="/config",nt="/account",me="/tokens",it="/spa-check",R=class extends te{constructor(e){super(),this.apiUrl=e.apiUrl||et,this.apiKey=e.apiKey??"",this.deployToken=e.deployToken??""}transferEventsTo(e){this.transfer(e)}async request(e,t={},i){let s=this.getAuthHeaders(t.headers),o={...t,headers:s,credentials:this.needsCredentials(s)?"include":void 0};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={...e};return this.deployToken?t.Authorization=`Bearer ${this.deployToken}`:this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}needsCredentials(e){return!this.apiKey&&!this.deployToken&&!e.Authorization}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}${tt}`,{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:this.needsCredentials(r)?"include":void 0};this.emit("request",`${this.apiUrl}${E}/${encodeURIComponent(e)}`,a);try{let f=await fetch(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,a);f.ok||await this.handleResponseError(f,"Set Domain");let S=this.safeClone(f),D=this.safeClone(f);return this.emit("response",S,`${this.apiUrl}${E}/${encodeURIComponent(e)}`),{...await this.parseResponse(D),isCreate:f.status===201}}catch(f){throw this.emit("error",f,`${this.apiUrl}${E}/${encodeURIComponent(e)}`),this.handleFetchError(f,"Set Domain"),f}}async getDomain(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${E}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async confirmDomain(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${nt}`,{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}${it}`,{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 p of e){let m=ee(p.path),u;if(Buffer.isBuffer(p.content))u=new s([p.content],p.path,{type:m});else if(typeof Blob<"u"&&p.content instanceof Blob)u=new s([p.content],p.path,{type:m});else throw F.file(`Unsupported file.content type for Node.js FormData: ${p.path}`,p.path);let C=p.path.startsWith("/")?p.path:"/"+p.path;r.append("files[]",u,C),a.push(p.md5)}r.append("checksums",JSON.stringify(a)),t&&t.length>0&&r.append("tags",JSON.stringify(t));let f=new o(r),S=[];for await(let p of f.encode())S.push(Buffer.from(p));let D=Buffer.concat(S);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)}};$();w();import{DEFAULT_API as at}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(),ke));return t(n)}else return{}}function U(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||at,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.onProgressStats===void 0&&e.onProgressStats!==void 0&&(t.onProgressStats=e.onProgressStats),t}G();import{DEPLOYMENT_CONFIG_FILENAME as Ne}from"@shipstatic/types";async function ft(){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 ft();return[...n,s]}}catch{}return n}function H(n,e,t,i){return{create:async(s,o={})=>{t&&await t();let r=e?j(o,e):o,a=n();if(!i)throw new Error("processInput function is not provided.");let f=await i(s,r);return f=await Me(f,a,r),await a.deploy(f,r)},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 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.clientOptions=e;let t=this.resolveInitialConfig(e);this.http=new R({...e,...t});let i=()=>this.ensureInitialized(),s=()=>this.http;this._deployments=H(s,this.clientOptions,i,(o,r)=>this.processInput(o,r)),this._domains=W(s,i),this._account=J(s,i),this._tokens=Y(s,i)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=A(),this._config)}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}};w();ie();import{ShipError as Te}from"@shipstatic/types";$();var c={};M(c,{ApiHttp:()=>R,DEFAULT_API:()=>ye,FILE_VALIDATION_STATUS:()=>d,JUNK_DIRECTORIES:()=>oe,Ship:()=>B,ShipError:()=>Fe,ShipErrorType:()=>Ee,__setTestEnvironment:()=>q,allValidFilesReady:()=>we,calculateMD5:()=>b,createAccountResource:()=>J,createDeploymentResource:()=>H,createDomainResource:()=>W,createTokenResource:()=>Y,filterJunk:()=>O,formatFileSize:()=>K,getENV:()=>y,getValidFiles:()=>pe,loadConfig:()=>pt,mergeDeployOptions:()=>j,optimizeDeployPaths:()=>k,pluralize:()=>ge,resolveConfig:()=>U,validateFiles:()=>ve});var g={};l(g,Jt);import*as Jt from"@shipstatic/types";l(c,g);import{DEFAULT_API as ye}from"@shipstatic/types";G();function ge(n,e,t,i=!0){let s=n===1?e:t;return i?`${n} ${s}`:s}se();ae();w();import Le from"mime-db";var dt=new Set(Object.keys(Le)),ht=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 yt(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 gt(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=ht.get(e);if(s&&!s.has(i))return!1}return!0}function ve(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?yt(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(S=>o.type.startsWith(S))?dt.has(o.type)?gt(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 pe(n){return n.filter(e=>e.status===d.READY)}function we(n){return pe(n).length>0}import{ShipError as Fe,ShipErrorType as Ee}from"@shipstatic/types";l(h,c);ie();$();$();Pe();w();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 U(e,{})}async loadFullConfig(){try{let e=await L(this.clientOptions.configFile),t=U(this.clientOptions,e),i=new R({...this.clientOptions,...t});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(()=>(We(),He));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;l(Q,h);export{R as ApiHttp,ye as DEFAULT_API,d as FILE_VALIDATION_STATUS,oe as JUNK_DIRECTORIES,Z as Ship,Fe as ShipError,Ee as ShipErrorType,q as __setTestEnvironment,we as allValidFilesReady,b as calculateMD5,J as createAccountResource,H as createDeploymentResource,W as createDomainResource,Y as createTokenResource,xe as default,O as filterJunk,K as formatFileSize,A as getCurrentConfig,y as getENV,pe as getValidFiles,L as loadConfig,j as mergeDeployOptions,k as optimizeDeployPaths,ge as pluralize,X as processFilesForNode,U as resolveConfig,_ as setConfig,_ as setPlatformConfig,ve as validateFiles};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|