@shipstatic/ship 0.9.3 → 0.9.5
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 +6 -4
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +15 -15
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../node_modules/.pnpm/@shipstatic+types@0.9.5/node_modules/@shipstatic/types/dist/index.js","../src/shared/lib/env.ts","../src/shared/lib/md5.ts","../src/shared/lib/junk.ts","../src/shared/lib/path.ts","../src/shared/lib/deploy-paths.ts","../src/shared/lib/file-validation.ts","../src/shared/lib/security.ts","../src/node/core/node-files.ts","../src/index.ts","../src/shared/base-ship.ts","../src/shared/api/http.ts","../src/shared/events.ts","../src/shared/lib/validation.ts","../src/shared/core/config.ts","../src/shared/resources.ts","../src/shared/lib/spa.ts","../src/node/index.ts","../src/node/core/config.ts","../src/shared/core/credential-schema.ts","../src/node/core/deploy-body.ts","../src/shared/index.ts","../src/shared/lib/text.ts"],"sourcesContent":["/**\n * @file Shared TypeScript types, constants, and utilities for the ShipStatic platform.\n * This package is the single source of truth for all shared data structures.\n */\n// =============================================================================\n// I. CORE ENTITIES\n// =============================================================================\n/**\n * Deployment status constants\n */\nexport const DeploymentStatus = {\n PENDING: 'pending',\n SUCCESS: 'success',\n FAILED: 'failed',\n DELETING: 'deleting'\n};\n// =============================================================================\n// DOMAIN TYPES\n// =============================================================================\n/**\n * Domain status constants\n *\n * - PENDING: DNS not configured\n * - PARTIAL: DNS partially configured\n * - SUCCESS: DNS fully verified\n * - PAUSED: Domain paused due to plan enforcement (billing)\n */\nexport const DomainStatus = {\n PENDING: 'pending',\n PARTIAL: 'partial',\n SUCCESS: 'success',\n PAUSED: 'paused'\n};\n// =============================================================================\n// ACCOUNT TYPES\n// =============================================================================\n/**\n * Account plan constants\n */\nexport const AccountPlan = {\n FREE: 'free',\n STANDARD: 'standard',\n SPONSORED: 'sponsored',\n ENTERPRISE: 'enterprise',\n SUSPENDED: 'suspended',\n TERMINATING: 'terminating',\n TERMINATED: 'terminated'\n};\n// =============================================================================\n// ERROR SYSTEM\n// =============================================================================\n/**\n * All possible error types in the ShipStatic platform.\n *\n * Developer-friendly key names map to stable wire-format string values.\n * Both the value and the type are exported under the same name so callers\n * can use `ErrorType.Validation` (value comparison) and `: ErrorType` (type\n * annotation) without ceremony — matching the pattern other status objects\n * (`DeploymentStatus`, `DomainStatus`, `AccountPlan`, `AuthMethod`) follow.\n */\nexport const ErrorType = {\n /** Validation failed (400) */\n Validation: 'validation_failed',\n /** Resource not found (404) */\n NotFound: 'not_found',\n /** Rate limit exceeded (429) */\n RateLimit: 'rate_limit_exceeded',\n /** Authentication required (401) */\n Authentication: 'authentication_failed',\n /** Business logic error (400) */\n Business: 'business_logic_error',\n /** API server error (500) */\n Api: 'internal_server_error',\n /** Network/connection error. Client-side only — set by HTTP clients on fetch failure; never produced server-side. */\n Network: 'network_error',\n /** Operation was cancelled. Client-side only — set on `AbortSignal` abort; never produced server-side. */\n Cancelled: 'operation_cancelled',\n /** File operation error */\n File: 'file_error',\n /** Configuration error */\n Config: 'config_error',\n};\n/**\n * Categorizes error types for the `isClientError` / `isNetworkError` /\n * `isAuthError` helpers. Each `Set` is typed against the wider `ErrorType`\n * union so `.has(error.type)` accepts any value from the union.\n */\nconst ERROR_CATEGORIES = {\n client: new Set([ErrorType.Business, ErrorType.Config, ErrorType.File, ErrorType.Validation]),\n network: new Set([ErrorType.Network]),\n auth: new Set([ErrorType.Authentication]),\n};\n/**\n * Lookup set of error types that legitimately appear on the wire — i.e.\n * server-thrown types. Used by `ShipError.fromHttpResponse` to validate the\n * body's `error` field before trusting it as the `ShipError.type`.\n *\n * Excludes `Network` and `Cancelled`, which are client-side-only by design:\n * they originate on the client (fetch failure, abort) and should never be\n * reconstructed from a server response, even if a misbehaving server were\n * to send them. A defensive omission, not a theoretical concern.\n */\nconst SERVER_PRODUCIBLE_ERROR_TYPES = new Set(Object.values(ErrorType).filter(t => t !== ErrorType.Network && t !== ErrorType.Cancelled));\n/**\n * Simple unified error class for both API and SDK\n */\nexport class ShipError extends Error {\n type;\n status;\n details;\n constructor(type, message, status, details) {\n super(message);\n this.type = type;\n this.status = status;\n this.details = details;\n this.name = 'ShipError';\n }\n /** Convert to wire format */\n toResponse() {\n // For security, exclude internal details from authentication errors in API responses\n const details = this.type === ErrorType.Authentication && this.details?.internal\n ? undefined\n : this.details;\n return {\n error: this.type,\n message: this.message,\n status: this.status,\n details\n };\n }\n /**\n * Construct a `ShipError` from an HTTP error response.\n *\n * Best-effort body parse for `{ message, error?, details? }`. Message\n * resolution: `body.message` → `body.error` → `fallbackMessage` →\n * `Request failed with status N`.\n *\n * Type resolution: trusts `body.error` when it's a known `ErrorType`\n * (preserves the wire's intent — server's `ShipError.validation(...)`\n * round-trips back to `ErrorType.Validation` on the client). Falls back to\n * status-derived (401 → Authentication, 429 → RateLimit, else → Api) for\n * non-API responses (CDN errors, intermediaries) or malformed bodies.\n *\n * Async because it reads the response body. Returns rather than throws so\n * callers can compose; most will `throw await ShipError.fromHttpResponse(...)`.\n */\n static async fromHttpResponse(response, fallbackMessage) {\n let message;\n let details;\n let bodyType;\n try {\n const contentType = response.headers.get('content-type');\n if (contentType?.includes('application/json')) {\n const json = await response.json();\n if (json && typeof json === 'object') {\n const obj = json;\n if (typeof obj.message === 'string')\n message = obj.message;\n else if (typeof obj.error === 'string')\n message = obj.error;\n details = obj.details;\n if (typeof obj.error === 'string' && SERVER_PRODUCIBLE_ERROR_TYPES.has(obj.error)) {\n bodyType = obj.error;\n }\n }\n }\n else {\n const text = await response.text();\n if (text)\n message = text;\n }\n }\n catch {\n // Body unreadable; fall through to fallback.\n }\n message = message || fallbackMessage || `Request failed with status ${response.status}`;\n const type = bodyType ?? (response.status === 401 ? ErrorType.Authentication :\n response.status === 429 ? ErrorType.RateLimit :\n ErrorType.Api);\n return new ShipError(type, message, response.status, details);\n }\n /**\n * Construct a `ShipError` from an error caught around a `fetch()` call.\n *\n * The mirror of `fromHttpResponse` for the *other* side of the HTTP error\n * story — the network layer failing (offline, CORS, abort) rather than the\n * server returning a non-OK response.\n *\n * Routing:\n * - Already a `ShipError` → returned as-is (caller's intent preserved)\n * - `AbortError` → `ShipError.cancelled(...)`\n * - `TypeError` whose message mentions \"fetch\" → `ShipError.network(...)`\n * - Any other `Error` → `ShipError(Api, ...)` (no HTTP status — fetch never reached the server)\n * - Anything else (string, undefined, etc.) → `ShipError(Api, ...)`\n *\n * The optional `operationName` is composed into the message for context:\n * `\"Get account was cancelled\"`, `\"Get account failed: ...\"`. Defaults to\n * `\"Request\"` when omitted.\n */\n static fromFetchError(cause, operationName) {\n if (isShipError(cause))\n return cause;\n const op = operationName || 'Request';\n if (cause instanceof Error) {\n if (cause.name === 'AbortError') {\n return ShipError.cancelled(`${op} was cancelled`);\n }\n if (cause instanceof TypeError && cause.message.includes('fetch')) {\n return ShipError.network(`${op} failed: ${cause.message}`, cause);\n }\n return new ShipError(ErrorType.Api, `${op} failed: ${cause.message}`);\n }\n return new ShipError(ErrorType.Api, `${op} failed: Unknown error`);\n }\n // Factory methods for common errors\n static validation(message, details) {\n return new ShipError(ErrorType.Validation, message, 400, details);\n }\n static notFound(resource, id) {\n const message = id ? `${resource} ${id} not found` : `${resource} not found`;\n return new ShipError(ErrorType.NotFound, message, 404);\n }\n static rateLimit(message = \"Too many requests\") {\n return new ShipError(ErrorType.RateLimit, message, 429);\n }\n static authentication(message = \"Authentication required\", details) {\n return new ShipError(ErrorType.Authentication, message, 401, details);\n }\n static business(message, status = 400) {\n return new ShipError(ErrorType.Business, message, status);\n }\n static network(message, cause) {\n return new ShipError(ErrorType.Network, message, undefined, { cause });\n }\n static cancelled(message) {\n return new ShipError(ErrorType.Cancelled, message);\n }\n static file(message, filePath) {\n return new ShipError(ErrorType.File, message, undefined, { filePath });\n }\n static config(message, details) {\n return new ShipError(ErrorType.Config, message, undefined, details);\n }\n static api(message, status = 500) {\n return new ShipError(ErrorType.Api, message, status);\n }\n // Helper getter for accessing file path from details\n get filePath() {\n return this.details?.filePath;\n }\n // Helper methods for error type checking using categorization\n isClientError() {\n return ERROR_CATEGORIES.client.has(this.type);\n }\n isNetworkError() {\n return ERROR_CATEGORIES.network.has(this.type);\n }\n isAuthError() {\n return ERROR_CATEGORIES.auth.has(this.type);\n }\n isValidationError() {\n return this.type === ErrorType.Validation;\n }\n isFileError() {\n return this.type === ErrorType.File;\n }\n isConfigError() {\n return this.type === ErrorType.Config;\n }\n // Generic type checker\n isType(errorType) {\n return this.type === errorType;\n }\n}\n/**\n * Type guard to check if an unknown value is a ShipError.\n *\n * Uses structural checking instead of instanceof to handle module duplication\n * in bundled applications where multiple copies of the ShipError class may exist.\n *\n * @example\n * if (isShipError(error)) {\n * console.log(error.status, error.message);\n * }\n */\nexport function isShipError(error) {\n return (error !== null &&\n typeof error === 'object' &&\n 'name' in error &&\n error.name === 'ShipError' &&\n 'status' in error);\n}\n// =============================================================================\n// EXTENSION BLOCKLIST\n// =============================================================================\n/**\n * Blocked file extensions — files that cannot be uploaded.\n *\n * We accept any file type by default and derive Content-Type from the\n * extension at serve time (via mime-db in the API worker). Unknown extensions\n * are served as `application/octet-stream` with `X-Content-Type-Options: nosniff`.\n *\n * The blocklist targets file types that pose direct security risks when hosted:\n * executables, disk images, malware vectors, dangerous scripts, and shortcuts.\n */\nexport const BLOCKED_EXTENSIONS = new Set([\n // Executables\n 'exe', 'msi', 'dll', 'scr', 'bat', 'cmd', 'com', 'pif', 'app', 'deb', 'rpm',\n // Installers\n 'pkg', 'mpkg',\n // Disk images\n 'dmg', 'iso', 'img',\n // Malware vectors\n 'cab', 'cpl', 'chm',\n // Dangerous scripts\n 'ps1', 'vbs', 'vbe', 'ws', 'wsf', 'wsc', 'wsh', 'reg',\n // Java\n 'jar', 'jnlp',\n // Mobile/browser packages\n 'apk', 'crx',\n // Shortcut/link\n 'lnk', 'inf', 'hta',\n]);\n/**\n * Check if a filename has a blocked extension.\n * Extracts the extension from the filename and checks against the blocklist.\n * Case-insensitive. Returns false for files without extensions.\n *\n * @example\n * isBlockedExtension('virus.exe') // true\n * isBlockedExtension('app.dmg') // true\n * isBlockedExtension('style.css') // false\n * isBlockedExtension('data.custom') // false\n * isBlockedExtension('README') // false\n */\nexport function isBlockedExtension(filename) {\n const dotIndex = filename.lastIndexOf('.');\n if (dotIndex === -1 || dotIndex === filename.length - 1)\n return false;\n const ext = filename.slice(dotIndex + 1).toLowerCase();\n return BLOCKED_EXTENSIONS.has(ext);\n}\n// =============================================================================\n// FILENAME CHARACTER VALIDATION\n// =============================================================================\n/**\n * Characters that are unsafe in filenames for static hosting.\n *\n * Blocks only characters that genuinely break the upload→serve round-trip:\n * - # ? % URL round-trip breakers (fragment, query, encoding ambiguity)\n * - \\ Path separator confusion (upload splits on backslash)\n * - < > \" XSS vectors with zero legitimate use in filenames\n * - \\x00-\\x1f \\x7f Control characters (header injection, display corruption)\n *\n * Everything else is allowed — browser percent-encodes, Worker decodes, R2 matches.\n */\nexport const UNSAFE_FILENAME_CHARS = /[\\x00-\\x1f\\x7f#?%\\\\<>\"]/;\n/**\n * Check if a filename contains unsafe characters.\n *\n * @example\n * hasUnsafeChars('saved_resource(1).html') // false — parentheses are safe\n * hasUnsafeChars('page[slug].js') // false — brackets are safe\n * hasUnsafeChars('file#anchor.html') // true — # breaks URL resolution\n * hasUnsafeChars('file<tag>.html') // true — < is an XSS vector\n */\nexport function hasUnsafeChars(filename) {\n return UNSAFE_FILENAME_CHARS.test(filename);\n}\n// =============================================================================\n// UNBUILT PROJECT MARKERS\n// =============================================================================\n/**\n * Path segment names that indicate an unbuilt project was uploaded instead of build output.\n * Used for early detection in CLI, browser, and server validation.\n */\nexport const UNBUILT_PROJECT_MARKERS = new Set([\n 'node_modules',\n 'package.json',\n]);\n/**\n * Check if a file path contains an unbuilt project marker.\n *\n * @example\n * hasUnbuiltMarker('node_modules/react/index.js') // true\n * hasUnbuiltMarker('package.json') // true\n * hasUnbuiltMarker('dist/index.html') // false\n */\nexport function hasUnbuiltMarker(filePath) {\n const segments = filePath.replace(/\\\\/g, '/').split('/').filter(Boolean);\n return segments.some(s => UNBUILT_PROJECT_MARKERS.has(s));\n}\n/**\n * Shape constants for API keys (`ship-{64 hex chars}`).\n * Single source of truth used by validation utilities and auth middleware.\n */\nexport const API_KEY = {\n /** Prefix that identifies an API key. */\n PREFIX: 'ship-',\n /** Number of hex characters following the prefix. */\n HEX_LENGTH: 64,\n /** Total length of an API key including prefix (`PREFIX.length + HEX_LENGTH = 69`). */\n TOTAL_LENGTH: 69,\n /** Number of trailing characters used to display a redacted hint (e.g. last 4). */\n HINT_LENGTH: 4,\n};\n/**\n * Shape constants for deploy tokens (`token-{64 hex chars}`).\n * Single source of truth used by validation utilities and auth middleware.\n */\nexport const DEPLOY_TOKEN = {\n /** Prefix that identifies a deploy token. */\n PREFIX: 'token-',\n /** Number of hex characters following the prefix. */\n HEX_LENGTH: 64,\n /** Total length of a deploy token including prefix (`PREFIX.length + HEX_LENGTH = 70`). */\n TOTAL_LENGTH: 70,\n};\n// Authentication Method Constants\nexport const AuthMethod = {\n JWT: 'jwt',\n API_KEY: 'apiKey',\n TOKEN: 'token',\n WEBHOOK: 'webhook',\n SYSTEM: 'system'\n};\n// Deployment Configuration\nexport const DEPLOYMENT_CONFIG_FILENAME = 'ship.json';\n/** Default ship.json config for SPA routing. Single source of truth — used by both API and SDK. */\nexport const SPA_DEFAULT_CONFIG = { rewrites: [{ source: '/(.*)', destination: '/index.html' }] };\n// =============================================================================\n// VALIDATION UTILITIES\n// =============================================================================\n/**\n * Validate API key format\n */\nexport function validateApiKey(apiKey) {\n if (!apiKey.startsWith(API_KEY.PREFIX)) {\n throw ShipError.validation(`API key must start with \"${API_KEY.PREFIX}\"`);\n }\n if (apiKey.length !== API_KEY.TOTAL_LENGTH) {\n throw ShipError.validation(`API key must be ${API_KEY.TOTAL_LENGTH} characters total (${API_KEY.PREFIX} + ${API_KEY.HEX_LENGTH} hex chars)`);\n }\n const hexPart = apiKey.slice(API_KEY.PREFIX.length);\n if (!/^[a-f0-9]{64}$/i.test(hexPart)) {\n throw ShipError.validation(`API key must contain ${API_KEY.HEX_LENGTH} hexadecimal characters after \"${API_KEY.PREFIX}\" prefix`);\n }\n}\n/**\n * Validate deploy token format\n */\nexport function validateDeployToken(deployToken) {\n if (!deployToken.startsWith(DEPLOY_TOKEN.PREFIX)) {\n throw ShipError.validation(`Deploy token must start with \"${DEPLOY_TOKEN.PREFIX}\"`);\n }\n if (deployToken.length !== DEPLOY_TOKEN.TOTAL_LENGTH) {\n throw ShipError.validation(`Deploy token must be ${DEPLOY_TOKEN.TOTAL_LENGTH} characters total (${DEPLOY_TOKEN.PREFIX} + ${DEPLOY_TOKEN.HEX_LENGTH} hex chars)`);\n }\n const hexPart = deployToken.slice(DEPLOY_TOKEN.PREFIX.length);\n if (!/^[a-f0-9]{64}$/i.test(hexPart)) {\n throw ShipError.validation(`Deploy token must contain ${DEPLOY_TOKEN.HEX_LENGTH} hexadecimal characters after \"${DEPLOY_TOKEN.PREFIX}\" prefix`);\n }\n}\n/**\n * Validate API URL format\n */\nexport function validateApiUrl(apiUrl) {\n try {\n const url = new URL(apiUrl);\n if (!['http:', 'https:'].includes(url.protocol)) {\n throw ShipError.validation('API URL must use http:// or https:// protocol');\n }\n if (url.pathname !== '/' && url.pathname !== '') {\n throw ShipError.validation('API URL must not contain a path');\n }\n if (url.search || url.hash) {\n throw ShipError.validation('API URL must not contain query parameters or fragments');\n }\n }\n catch (error) {\n if (isShipError(error)) {\n throw error;\n }\n throw ShipError.validation('API URL must be a valid URL');\n }\n}\n/**\n * Check if a string matches the deployment identifier pattern (word-word-alphanumeric7).\n * Example: \"happy-cat-abc1234.shipstatic.com\"\n */\nexport function isDeployment(input) {\n return /^[a-z]+-[a-z]+-[a-z0-9]{7}(\\.[a-z0-9.-]+)?$/i.test(input);\n}\n// =============================================================================\n// PLATFORM CONSTANTS\n// =============================================================================\n/** Default API URL if not otherwise configured. */\nexport const DEFAULT_API = 'https://api.shipstatic.com';\n// =============================================================================\n// FILE UPLOAD TYPES\n// =============================================================================\n/**\n * File status constants for validation state tracking\n */\nexport const FileValidationStatus = {\n /** File is pending validation */\n PENDING: 'pending',\n /** File failed during processing (before validation) */\n PROCESSING_ERROR: 'processing_error',\n /** File was excluded by validation warning (not an error) */\n EXCLUDED: 'excluded',\n /** File failed validation (blocks deployment) */\n VALIDATION_FAILED: 'validation_failed',\n /** File passed validation and is ready for deployment */\n READY: 'ready',\n};\n// =============================================================================\n// DOMAIN UTILITIES\n// =============================================================================\n/**\n * Check if a domain is a platform domain (subdomain of our platform).\n * Platform domains are free and don't require DNS verification.\n *\n * @example isPlatformDomain(\"www.shipstatic.com\", \"shipstatic.com\") → true\n * @example isPlatformDomain(\"example.com\", \"shipstatic.com\") → false\n */\nexport function isPlatformDomain(domain, platformDomain) {\n return domain.endsWith(`.${platformDomain}`);\n}\n/**\n * Check if a domain is a custom domain (not a platform subdomain).\n * Custom domains are billable and require DNS verification.\n *\n * @example isCustomDomain(\"example.com\", \"shipstatic.com\") → true\n * @example isCustomDomain(\"www.shipstatic.com\", \"shipstatic.com\") → false\n */\nexport function isCustomDomain(domain, platformDomain) {\n return !isPlatformDomain(domain, platformDomain);\n}\n/**\n * Extract subdomain from a platform domain.\n * Returns null if not a platform domain.\n *\n * @example extractSubdomain(\"www.shipstatic.com\", \"shipstatic.com\") → \"www\"\n * @example extractSubdomain(\"example.com\", \"shipstatic.com\") → null\n */\nexport function extractSubdomain(domain, platformDomain) {\n if (!isPlatformDomain(domain, platformDomain)) {\n return null;\n }\n return domain.slice(0, -(platformDomain.length + 1)); // +1 for the dot\n}\n/**\n * Generate HTTPS URL for a deployment hostname.\n */\nexport function generateDeploymentUrl(deployment) {\n return `https://${deployment}`;\n}\n/**\n * Generate HTTPS URL for a domain.\n */\nexport function generateDomainUrl(domain) {\n return `https://${domain}`;\n}\n// =============================================================================\n// LABEL UTILITIES\n// =============================================================================\n/**\n * Label validation constraints shared across UI and API.\n * These rules define the single source of truth for label validation.\n */\nexport const LABEL_CONSTRAINTS = {\n /** Minimum label length in characters */\n MIN_LENGTH: 3,\n /** Maximum label length in characters (concise labels, matches Stack Overflow's original limit) */\n MAX_LENGTH: 25,\n /** Maximum number of labels allowed per resource */\n MAX_COUNT: 10,\n /** Allowed separator characters between label segments */\n SEPARATORS: '._-',\n};\n/**\n * Label validation pattern.\n * Must start and end with alphanumeric (a-z, 0-9).\n * Can contain separators (. _ -) between segments, but not consecutive.\n *\n * Valid examples: 'production', 'v1.2.3', 'api_v2', 'us-east-1'\n * Invalid examples: 'ab' (too short), '-prod' (starts with separator), 'foo--bar' (consecutive separators)\n */\nexport const LABEL_PATTERN = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;\n/**\n * Serialize labels array to JSON string for database storage.\n * Returns null for empty or undefined arrays.\n *\n * @example serializeLabels(['web', 'production']) → '[\"web\",\"production\"]'\n * @example serializeLabels([]) → null\n * @example serializeLabels(undefined) → null\n */\nexport function serializeLabels(labels) {\n if (!labels || labels.length === 0)\n return null;\n return JSON.stringify(labels);\n}\n/**\n * Deserialize labels from JSON string to array.\n * Always returns an array — empty array for null/empty/invalid input.\n *\n * @example deserializeLabels('[\"web\",\"production\"]') → ['web', 'production']\n * @example deserializeLabels(null) → []\n * @example deserializeLabels('') → []\n */\nexport function deserializeLabels(labelsJson) {\n if (!labelsJson)\n return [];\n try {\n const parsed = JSON.parse(labelsJson);\n return Array.isArray(parsed) ? parsed : [];\n }\n catch {\n return [];\n }\n}\n// =============================================================================\n// PASSWORD UTILITIES\n// =============================================================================\n/**\n * Length constraints for the optional deployment password\n * (`DeploymentUploadOptions.password`). Single source of truth shared across\n * platform consumers.\n */\nexport const PASSWORD_CONSTRAINTS = {\n /** Minimum password length in characters */\n MIN_LENGTH: 6,\n /** Maximum password length in characters */\n MAX_LENGTH: 128,\n};\n","/**\n * @file Environment detection utilities for the Ship SDK.\n * Helps in determining whether the SDK is running in a Node.js, browser, or unknown environment.\n */\n\n/**\n * Represents the detected or simulated JavaScript execution environment.\n */\nexport type ExecutionEnvironment = 'browser' | 'node' | 'unknown';\n\n/** @internal Environment override for testing. */\nlet _testEnvironment: ExecutionEnvironment | null = null;\n\n/**\n * **FOR TESTING PURPOSES ONLY.**\n *\n * Allows tests to override the detected environment, forcing the SDK to behave\n * as if it's running in the specified environment.\n *\n * @param env - The environment to simulate ('node', 'browser', 'unknown'),\n * or `null` to clear the override and revert to actual environment detection.\n * @internal\n */\nexport function __setTestEnvironment(env: ExecutionEnvironment | null): void {\n _testEnvironment = env;\n}\n\n/**\n * Detects the actual JavaScript execution environment (Node.js, browser, or unknown)\n * by checking for characteristic global objects.\n * @returns The detected environment as {@link ExecutionEnvironment}.\n * @internal\n */\nfunction detectEnvironment(): ExecutionEnvironment {\n // Check for Node.js environment\n if (typeof process !== 'undefined' && process.versions && process.versions.node) {\n return 'node';\n }\n\n // Check for Browser environment (including Web Workers)\n if (typeof window !== 'undefined' || typeof self !== 'undefined') {\n return 'browser';\n }\n\n return 'unknown';\n}\n\n/**\n * Gets the current effective execution environment.\n *\n * This function first checks if a test environment override is active via {@link __setTestEnvironment}.\n * If not, it detects the actual environment (Node.js, browser, or unknown).\n *\n * @returns The current execution environment: 'browser', 'node', or 'unknown'.\n * @public\n */\nexport function getENV(): ExecutionEnvironment {\n // Return test override if set\n if (_testEnvironment) {\n return _testEnvironment;\n }\n \n // Detect actual environment\n return detectEnvironment();\n}\n","/**\n * @file Simplified MD5 calculation utility with separate environment handlers.\n */\nimport { getENV } from './env.js';\nimport { ShipError } from '@shipstatic/types';\n\nexport interface MD5Result {\n md5: string;\n}\n\n/**\n * Browser-specific MD5 calculation for Blob/File objects\n */\nasync function calculateMD5Browser(blob: Blob): Promise<MD5Result> {\n const SparkMD5 = (await import('spark-md5')).default;\n \n return new Promise((resolve, reject) => {\n const chunkSize = 2097152; // 2MB chunks\n const chunks = Math.ceil(blob.size / chunkSize);\n let currentChunk = 0;\n const spark = new SparkMD5.ArrayBuffer();\n const fileReader = new FileReader();\n\n const loadNext = () => {\n const start = currentChunk * chunkSize;\n const end = Math.min(start + chunkSize, blob.size);\n fileReader.readAsArrayBuffer(blob.slice(start, end));\n };\n\n fileReader.onload = (e) => {\n const result = e.target?.result as ArrayBuffer;\n if (!result) {\n reject(ShipError.business('Failed to read file chunk'));\n return;\n }\n \n spark.append(result);\n currentChunk++;\n \n if (currentChunk < chunks) {\n loadNext();\n } else {\n resolve({ md5: spark.end() });\n }\n };\n\n fileReader.onerror = () => {\n reject(ShipError.business('Failed to calculate MD5: FileReader error'));\n };\n\n loadNext();\n });\n}\n\n/**\n * Node.js-specific MD5 calculation for Buffer or file path\n */\nasync function calculateMD5Node(input: Buffer | string): Promise<MD5Result> {\n const crypto = await import('crypto');\n \n if (Buffer.isBuffer(input)) {\n const hash = crypto.createHash('md5');\n hash.update(input);\n return { md5: hash.digest('hex') };\n }\n \n // Handle file path\n const fs = await import('fs');\n return new Promise((resolve, reject) => {\n const hash = crypto.createHash('md5');\n const stream = fs.createReadStream(input);\n \n stream.on('error', err => \n reject(ShipError.business(`Failed to read file for MD5: ${err.message}`))\n );\n stream.on('data', chunk => hash.update(chunk));\n stream.on('end', () => resolve({ md5: hash.digest('hex') }));\n });\n}\n\n/**\n * Unified MD5 calculation that delegates to environment-specific handlers\n */\nexport async function calculateMD5(input: Blob | Buffer | string): Promise<MD5Result> {\n const env = getENV();\n \n if (env === 'browser') {\n if (!(input instanceof Blob)) {\n throw ShipError.business('Invalid input for browser MD5 calculation: Expected Blob or File.');\n }\n return calculateMD5Browser(input);\n }\n \n if (env === 'node') {\n if (!(Buffer.isBuffer(input) || typeof input === 'string')) {\n throw ShipError.business('Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.');\n }\n return calculateMD5Node(input);\n }\n \n throw ShipError.business('Unknown or unsupported execution environment for MD5 calculation.');\n}\n","/**\n * @file Utility for filtering out junk files and directories from file paths\n * \n * This module provides functionality to filter out common system junk files and directories\n * from a list of file paths. It uses the 'junk' package to identify junk filenames and\n * a custom list to filter out common junk directories.\n */\nimport { isJunk } from 'junk';\nimport { ShipError, hasUnbuiltMarker } from '@shipstatic/types';\n\n/**\n * List of directory names considered as junk\n * \n * Files within these directories (at any level in the path hierarchy) will be excluded.\n * The comparison is case-insensitive for cross-platform compatibility.\n * \n * @internal\n */\nexport const JUNK_DIRECTORIES = [\n '__MACOSX',\n '.Trashes',\n '.fseventsd',\n '.Spotlight-V100',\n] as const;\n\n/**\n * Filters an array of file paths, removing those considered junk\n *\n * Throws if any path contains an unbuilt project marker (e.g. `node_modules`, `package.json`).\n * This check runs first because the dot-file filter below would strip paths like\n * `node_modules/.pnpm/...`, destroying the evidence.\n *\n * A path is filtered out if any of these conditions are met:\n * 1. The basename is identified as junk by the 'junk' package (e.g., .DS_Store, Thumbs.db)\n * 2. Any path segment starts with a dot (e.g., .env, .git, .htaccess)\n * Exception: `.well-known` is allowed (RFC 8615 — ACME, security.txt, app links)\n * 3. Any path segment exceeds 255 characters (filesystem limit)\n * 4. Any directory segment in the path matches an entry in JUNK_DIRECTORIES (case-insensitive)\n *\n * All path separators are normalized to forward slashes for consistent cross-platform behavior.\n *\n * Dot files are filtered for security — they typically contain sensitive configuration\n * (.env, .git) or are not meant to be served publicly. This matches server-side filtering.\n *\n * @param filePaths - An array of file path strings to filter\n * @param options - Optional settings\n * @param options.allowUnbuilt - When true, skip the unbuilt project marker check (for server-processed uploads)\n * @returns A new array containing only non-junk file paths\n * @throws {ShipError} If any path contains an unbuilt project marker (unless allowUnbuilt is true)\n *\n * @example\n * ```typescript\n * import { filterJunk } from '@shipstatic/ship';\n *\n * // Filter an array of file paths\n * const paths = ['index.html', '.DS_Store', '.gitattributes', '__MACOSX/file.txt', 'app.js'];\n * const clean = filterJunk(paths);\n * // Result: ['index.html', 'app.js']\n * ```\n *\n * @example\n * ```typescript\n * // Use with browser File objects\n * import { filterJunk } from '@shipstatic/ship';\n *\n * const files: File[] = [...]; // From input or drag-drop\n *\n * // Extract paths from File objects\n * const filePaths = files.map(f => f.webkitRelativePath || f.name);\n *\n * // Filter out junk paths\n * const validPaths = new Set(filterJunk(filePaths));\n *\n * // Filter the original File array\n * const validFiles = files.filter(f =>\n * validPaths.has(f.webkitRelativePath || f.name)\n * );\n * ```\n */\nexport function filterJunk(\n filePaths: string[],\n options?: { allowUnbuilt?: boolean }\n): string[] {\n if (!filePaths || filePaths.length === 0) {\n return [];\n }\n\n // Reject unbuilt projects before the dot-file filter removes evidence.\n // pnpm stores files under node_modules/.pnpm/ — the dot-file filter below\n // strips .pnpm/ paths, destroying the only signal that this is an unbuilt project.\n if (!options?.allowUnbuilt) {\n const marker = filePaths.find(p => p && hasUnbuiltMarker(p));\n if (marker) {\n throw ShipError.business(\n 'Unbuilt project detected — deploy your build output (dist/, build/, out/), not the project folder'\n );\n }\n }\n\n return filePaths.filter(filePath => {\n if (!filePath) {\n return false; // Exclude null or undefined paths\n }\n\n // Normalize path separators to forward slashes and split into segments\n const parts = filePath.replace(/\\\\/g, '/').split('/').filter(Boolean);\n if (parts.length === 0) return true;\n\n // Check if the basename is a junk file (using junk package)\n const basename = parts[parts.length - 1];\n if (isJunk(basename)) {\n return false;\n }\n\n // Filter out dot files and directories (security: prevents .env, .git, etc.)\n // .well-known is not junk — it's a standard directory (RFC 8615)\n // Path position constraints enforced at upload (buildFileKey) and serving (isBlockedDotFile)\n for (const part of parts) {\n if (part === '.well-known') continue;\n if (part.startsWith('.') || part.length > 255) {\n return false;\n }\n }\n\n // Check if any directory segment is in our junk directories list\n const directorySegments = parts.slice(0, -1);\n for (const segment of directorySegments) {\n if (JUNK_DIRECTORIES.some(junkDir =>\n segment.toLowerCase() === junkDir.toLowerCase())) {\n return false;\n }\n }\n\n return true;\n });\n}\n","/**\n * @file Path helper utilities that work in both browser and Node.js environments.\n * Provides environment-agnostic path manipulation functions.\n */\n\n/**\n * Finds the common parent directory from an array of directory paths.\n * Simple, unified implementation for flattenDirs functionality.\n * \n * @param dirPaths - Array of directory paths (not file paths - directories containing the files)\n * @returns The common parent directory path, or empty string if none found\n */\nexport function findCommonParent(dirPaths: string[]): string {\n if (!dirPaths || dirPaths.length === 0) return '';\n \n const normalizedPaths = dirPaths\n .filter(p => p && typeof p === 'string')\n .map(p => p.replace(/\\\\/g, '/'));\n \n if (normalizedPaths.length === 0) return '';\n if (normalizedPaths.length === 1) return normalizedPaths[0];\n\n const pathSegments = normalizedPaths.map(p => p.split('/').filter(Boolean));\n const commonSegments = [];\n const minLength = Math.min(...pathSegments.map(p => p.length));\n \n for (let i = 0; i < minLength; i++) {\n const segment = pathSegments[0][i];\n if (pathSegments.every(segments => segments[i] === segment)) {\n commonSegments.push(segment);\n } else {\n break;\n }\n }\n \n return commonSegments.join('/');\n}\n\n\n\n/**\n * Converts backslashes to forward slashes for cross-platform compatibility.\n * Does not remove leading slashes (preserves absolute paths).\n * @param path - The path to normalize\n * @returns Path with forward slashes\n */\nexport function normalizeSlashes(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n\n/**\n * Normalizes a path for web usage by converting backslashes to forward slashes\n * and removing leading slashes.\n * @param path - The path to normalize\n * @returns Normalized path suitable for web deployment\n */\nexport function normalizeWebPath(path: string): string {\n return path.replace(/\\\\/g, '/').replace(/\\/+/g, '/').replace(/^\\/+/, '');\n}\n\n","/**\n * @file Deploy path optimization - the core logic that makes Ship deployments clean and intuitive.\n * Automatically strips common parent directories to create clean deployment URLs.\n */\n\nimport { normalizeWebPath } from './path.js';\n\n/**\n * Represents a file ready for deployment with its optimized path\n */\nexport interface DeployFile {\n /** The clean deployment path (e.g., \"assets/style.css\") */\n path: string;\n /** Original filename */\n name: string;\n}\n\n/**\n * Core path optimization logic.\n * Transforms messy local paths into clean deployment paths.\n * \n * @example\n * Input: [\"dist/index.html\", \"dist/assets/app.js\"]\n * Output: [\"index.html\", \"assets/app.js\"]\n * \n * @param filePaths - Raw file paths from the local filesystem\n * @param options - Path processing options\n */\nexport function optimizeDeployPaths(\n filePaths: string[], \n options: { flatten?: boolean } = {}\n): DeployFile[] {\n // When flattening is disabled, keep original structure\n if (options.flatten === false) {\n return filePaths.map(path => ({\n path: normalizeWebPath(path),\n name: extractFileName(path)\n }));\n }\n\n // Find the common directory prefix to strip\n const commonPrefix = findCommonDirectory(filePaths);\n \n return filePaths.map(filePath => {\n let deployPath = normalizeWebPath(filePath);\n \n // Strip the common prefix to create clean deployment paths\n if (commonPrefix) {\n const prefixToRemove = commonPrefix.endsWith('/') ? commonPrefix : `${commonPrefix}/`;\n if (deployPath.startsWith(prefixToRemove)) {\n deployPath = deployPath.substring(prefixToRemove.length);\n }\n }\n \n // Fallback to filename if path becomes empty\n if (!deployPath) {\n deployPath = extractFileName(filePath);\n }\n \n return {\n path: deployPath,\n name: extractFileName(filePath)\n };\n });\n}\n\n/**\n * Finds the common directory shared by all file paths.\n * This is what gets stripped to create clean deployment URLs.\n * \n * @example\n * [\"dist/index.html\", \"dist/assets/app.js\"] → \"dist\"\n * [\"src/components/A.tsx\", \"src/utils/B.ts\"] → \"src\"\n * [\"file1.txt\", \"file2.txt\", \"subdir/file3.txt\"] → \"\" (no common directory)\n */\nfunction findCommonDirectory(filePaths: string[]): string {\n if (!filePaths.length) return '';\n \n // Normalize all paths first\n const normalizedPaths = filePaths.map(path => normalizeWebPath(path));\n \n // Find the common prefix among all file paths (not just directories)\n const pathSegments = normalizedPaths.map(path => path.split('/'));\n const commonSegments: string[] = [];\n const minLength = Math.min(...pathSegments.map(segments => segments.length));\n \n // Check each segment level to find the longest common prefix\n for (let i = 0; i < minLength - 1; i++) { // -1 because we don't want to include the filename\n const segment = pathSegments[0][i];\n if (pathSegments.every(segments => segments[i] === segment)) {\n commonSegments.push(segment);\n } else {\n break;\n }\n }\n \n return commonSegments.join('/');\n}\n\n/**\n * Extracts just the filename from a file path\n */\nfunction extractFileName(path: string): string {\n return path.split(/[/\\\\]/).pop() || path;\n}","/**\n * @file File validation utilities for Ship SDK\n * Provides client-side validation for file uploads before deployment\n */\n\nimport type {\n PlatformLimits,\n FileValidationResult,\n ValidatableFile,\n ValidationIssue,\n FileValidationStatusType\n} from '@shipstatic/types';\nimport {\n FileValidationStatus as FILE_VALIDATION_STATUS,\n isBlockedExtension,\n hasUnbuiltMarker,\n hasUnsafeChars,\n} from '@shipstatic/types';\n\nexport { FILE_VALIDATION_STATUS };\n\n/**\n * Format file size to human-readable string\n */\nexport function formatFileSize(bytes: number, decimals: number = 1): string {\n if (bytes === 0) return '0 Bytes';\n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + ' ' + sizes[i];\n}\n\n/**\n * Validate filename for deployment safety\n *\n * Blocks only characters that genuinely break the upload→serve round-trip:\n * - # ? % URL round-trip breakers (fragment, query, encoding ambiguity)\n * - \\ Path separator confusion (buildFileKey splits on backslash)\n * - < > \" XSS vectors with zero legitimate use in filenames\n * - \\x00-\\x1f \\x7f Control characters (header injection, display corruption)\n *\n * Everything else is allowed — browser percent-encodes, Worker decodes, R2 matches.\n *\n * Additional checks: path traversal, reserved names, leading/trailing dots or spaces.\n */\nexport function validateFileName(filename: string): { valid: boolean; reason?: string } {\n if (hasUnsafeChars(filename)) {\n return { valid: false, reason: 'File name contains unsafe characters' };\n }\n\n if (filename.startsWith(' ') || filename.endsWith(' ')) {\n return { valid: false, reason: 'File name cannot start/end with spaces' };\n }\n\n if (filename.endsWith('.')) {\n return { valid: false, reason: 'File name cannot end with dots' };\n }\n\n const reservedNames = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\\.|$)/i;\n const nameWithoutPath = filename.split('/').pop() || filename;\n if (reservedNames.test(nameWithoutPath)) {\n return { valid: false, reason: 'File name uses a reserved system name' };\n }\n\n if (filename.includes('..')) {\n return { valid: false, reason: 'File name contains path traversal pattern' };\n }\n\n return { valid: true };\n}\n\n/**\n * Validate files against configuration limits with severity-based reporting\n *\n * Validation categorizes issues by severity:\n * - **Errors**: Block deployment (file too large, blocked extension, etc.)\n * - **Warnings**: Exclude files but allow deployment (empty files, etc.)\n *\n * @param files - Array of files to validate\n * @param config - Validation configuration from ship.getLimits()\n * @returns Validation result with errors and warnings\n *\n * @example\n * ```typescript\n * const config = await ship.getLimits();\n * const result = validateFiles(files, config);\n *\n * if (!result.canDeploy) {\n * // Has errors - deployment blocked\n * console.error('Deployment blocked:', result.errors);\n * } else if (result.warnings.length > 0) {\n * // Has warnings - deployment proceeds, some files excluded\n * console.warn('Files excluded:', result.warnings);\n * await ship.deploy(result.validFiles);\n * } else {\n * // All files valid\n * await ship.deploy(result.validFiles);\n * }\n * ```\n */\nexport function validateFiles<T extends ValidatableFile>(\n files: T[],\n config: PlatformLimits\n): FileValidationResult<T> {\n const errors: ValidationIssue[] = [];\n const warnings: ValidationIssue[] = [];\n let fileStatuses: T[] = []; // Use 'let' for atomic enforcement later\n\n // Check at least 1 file required\n if (files.length === 0) {\n const issue: ValidationIssue = {\n file: '(no files)',\n message: 'At least one file must be provided'\n };\n errors.push(issue);\n\n return {\n files: [],\n validFiles: [],\n errors,\n warnings: [],\n canDeploy: false,\n };\n }\n\n // Check for unbuilt project markers (node_modules/, etc.)\n for (const file of files) {\n if (hasUnbuiltMarker(file.name)) {\n errors.push({\n file: file.name,\n message: `Unbuilt project detected — deploy your build output (dist/, build/, out/), not the project folder`\n });\n return {\n files: files.map(f => ({\n ...f,\n status: FILE_VALIDATION_STATUS.VALIDATION_FAILED,\n statusMessage: 'Unbuilt project detected'\n })),\n validFiles: [],\n errors,\n warnings: [],\n canDeploy: false\n };\n }\n }\n\n // Check file count limit\n if (files.length > config.maxFilesCount) {\n const issue: ValidationIssue = {\n file: `(${files.length} files)`,\n message: `File count (${files.length}) exceeds limit of ${config.maxFilesCount}`\n };\n errors.push(issue);\n\n return {\n files: files.map(f => ({\n ...f,\n status: FILE_VALIDATION_STATUS.VALIDATION_FAILED,\n statusMessage: issue.message,\n })),\n validFiles: [],\n errors,\n warnings: [],\n canDeploy: false,\n };\n }\n\n // Validate each file\n let totalSize = 0;\n\n for (const file of files) {\n let fileStatus: FileValidationStatusType = FILE_VALIDATION_STATUS.READY;\n let statusMessage = 'Ready for upload';\n\n // Pre-compute filename validation\n const nameValidation = file.name ? validateFileName(file.name) : { valid: false, reason: 'File name cannot be empty' };\n\n // Check for processing errors\n if (file.status === FILE_VALIDATION_STATUS.PROCESSING_ERROR) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = file.statusMessage || 'File failed during processing';\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n\n // EMPTY FILE - Warning (not error)\n else if (file.size === 0) {\n fileStatus = FILE_VALIDATION_STATUS.EXCLUDED;\n statusMessage = 'File is empty (0 bytes) and cannot be deployed due to storage limitations';\n warnings.push({\n file: file.name,\n message: statusMessage\n });\n // Skip other validations for excluded files\n fileStatuses.push({\n ...file,\n status: fileStatus,\n statusMessage,\n });\n continue;\n }\n\n // Negative file size - Error\n else if (file.size < 0) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = 'File size must be positive';\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n\n // File name validation\n else if (!file.name || file.name.trim().length === 0) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = 'File name cannot be empty';\n errors.push({\n file: file.name || '(empty)',\n message: statusMessage\n });\n }\n else if (file.name.includes('\\0')) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = 'File name contains invalid characters (null byte)';\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n else if (!nameValidation.valid) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = nameValidation.reason || 'Invalid file name';\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n\n // Blocked extension check\n else if (isBlockedExtension(file.name)) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = `File extension not allowed: \"${file.name}\"`;\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n\n // File size validation\n else if (file.size > config.maxFileSize) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = `File size (${formatFileSize(file.size)}) exceeds limit of ${formatFileSize(config.maxFileSize)}`;\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n\n // Total size validation\n else {\n totalSize += file.size;\n if (totalSize > config.maxTotalSize) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = `Total size would exceed limit of ${formatFileSize(config.maxTotalSize)}`;\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n }\n\n fileStatuses.push({\n ...file,\n status: fileStatus,\n statusMessage,\n });\n }\n\n // ATOMIC ENFORCEMENT: Two-phase validation for optimal UX + atomic semantics\n // Phase 1 (above): Validate files individually to collect ALL errors\n // Phase 2 (below): Mark all files as failed if any errors exist\n //\n // Why two phases? We validate individually for better UX (users see all problems\n // at once and can fix everything in one pass), then enforce atomicity to maintain\n // deployment transaction semantics (all-or-nothing).\n if (errors.length > 0) {\n fileStatuses = fileStatuses.map(file => {\n // Keep EXCLUDED files as-is (they're warnings, not errors)\n if (file.status === FILE_VALIDATION_STATUS.EXCLUDED) {\n return file;\n }\n\n // Mark ALL other files as VALIDATION_FAILED (atomic deployment)\n return {\n ...file,\n status: FILE_VALIDATION_STATUS.VALIDATION_FAILED,\n statusMessage: file.status === FILE_VALIDATION_STATUS.VALIDATION_FAILED\n ? file.statusMessage // Keep original error message for the file that actually failed\n : 'Deployment failed due to validation errors in bundle'\n };\n });\n }\n\n // Build atomic result\n // validFiles is empty if ANY errors exist (all-or-nothing)\n const validFiles = errors.length === 0\n ? fileStatuses.filter(f => f.status === FILE_VALIDATION_STATUS.READY)\n : [];\n const canDeploy = errors.length === 0;\n\n return {\n files: fileStatuses,\n validFiles,\n errors,\n warnings,\n canDeploy,\n };\n}\n\n/**\n * Get only the valid files from validation results\n */\nexport function getValidFiles<T extends ValidatableFile>(files: T[]): T[] {\n return files.filter(f => f.status === FILE_VALIDATION_STATUS.READY);\n}\n\n/**\n * Check if all valid files have required properties for upload\n * (Can be extended to check for MD5, etc.)\n */\nexport function allValidFilesReady<T extends ValidatableFile>(files: T[]): boolean {\n const validFiles = getValidFiles(files);\n return validFiles.length > 0;\n}\n","/**\n * @file Shared security validation for the deploy pipeline.\n * Used by both Node.js and browser file processing pipelines.\n */\nimport { ShipError, isBlockedExtension } from '@shipstatic/types';\nimport { validateFileName } from './file-validation.js';\n\n/**\n * Validate a deploy path for security concerns.\n * Rejects paths containing path traversal patterns or null bytes.\n *\n * Checks for:\n * - Null bytes (\\0) — path injection\n * - /../ — directory traversal within path\n * - ../ at start — upward traversal\n * - /.. at end — trailing traversal\n *\n * Does NOT reject double dots in filenames (e.g., \"foo..bar.txt\" is safe).\n *\n * @param deployPath - The deployment path to validate\n * @param sourceIdentifier - Human-readable identifier for error messages\n * @throws {ShipError} If the path contains unsafe patterns\n */\nexport function validateDeployPath(deployPath: string, sourceIdentifier: string): void {\n if (\n deployPath.includes('\\0') ||\n deployPath.includes('/../') ||\n deployPath.startsWith('../') ||\n deployPath.endsWith('/..')\n ) {\n throw ShipError.business(`Security error: Unsafe file path \"${deployPath}\" for file: ${sourceIdentifier}`);\n }\n}\n\n/**\n * Validate a deploy file's name and extension.\n * Rejects unsafe filenames (shell/URL-dangerous chars, reserved names)\n * and blocked file extensions (.exe, .msi, .dll, etc.).\n *\n * @param deployPath - The deployment path to validate\n * @param sourceIdentifier - Human-readable identifier for error messages\n * @throws {ShipError} If the filename is unsafe or extension is blocked\n */\nexport function validateDeployFile(deployPath: string, sourceIdentifier: string): void {\n const nameCheck = validateFileName(deployPath);\n if (!nameCheck.valid) {\n throw ShipError.business(nameCheck.reason || 'Invalid file name');\n }\n\n if (isBlockedExtension(deployPath)) {\n throw ShipError.business(`File extension not allowed: \"${sourceIdentifier}\"`);\n }\n}\n","/**\n * @file Node.js-specific file utilities for the Ship SDK.\n * Provides helpers for recursively discovering, filtering, and preparing files for deploy in Node.js.\n */\nimport { getENV } from '../../shared/lib/env.js';\nimport type { PlatformLimits } from '@shipstatic/types';\nimport type { StaticFile, DeploymentOptions } from '../../shared/types.js';\nimport { calculateMD5 } from '../../shared/lib/md5.js';\nimport { filterJunk } from '../../shared/lib/junk.js';\nimport { validateDeployPath, validateDeployFile } from '../../shared/lib/security.js';\nimport { ShipError, isShipError, UNBUILT_PROJECT_MARKERS } from '@shipstatic/types';\nimport { optimizeDeployPaths } from '../../shared/lib/deploy-paths.js';\nimport { findCommonParent } from '../../shared/lib/path.js';\n\nimport * as fs from 'fs';\nimport * as path from 'path';\n\n\n/**\n * Recursive function to walk directory and return all file paths.\n * Includes symlink loop protection to prevent infinite recursion.\n * @param dirPath - Directory path to traverse\n * @param visited - Set of already visited real paths (for cycle detection)\n * @returns Array of absolute file paths in the directory\n */\nfunction findAllFilePaths(dirPath: string, visited: Set<string> = new Set()): string[] {\n const results: string[] = [];\n\n // Resolve the real path to detect symlink cycles\n const realPath = fs.realpathSync(dirPath);\n if (visited.has(realPath)) {\n // Already visited this directory (symlink cycle) - skip to prevent infinite loop\n return results;\n }\n visited.add(realPath);\n\n const entries = fs.readdirSync(dirPath);\n\n for (const entry of entries) {\n const fullPath = path.join(dirPath, entry);\n const stats = fs.statSync(fullPath);\n\n if (stats.isDirectory()) {\n const subFiles = findAllFilePaths(fullPath, visited);\n results.push(...subFiles);\n } else if (stats.isFile()) {\n results.push(fullPath);\n }\n }\n\n return results;\n}\n\n/**\n * Processes Node.js file and directory paths into an array of StaticFile objects ready for deploy.\n * Computes content paths relative to the upload root before filtering, so only the deployed\n * directory structure is evaluated — not the user's filesystem above it.\n * \n * @param paths - File or directory paths to scan and process.\n * @param options - Processing options (pathDetect, etc.).\n * @param platformLimits - Per-instance platform limits (file-size / count /\n * total-size caps) from the originating Ship's `GET /config` fetch. Passed\n * in rather than read from a module global so concurrent Ships against\n * different API URLs cannot clobber each other's caps.\n * @returns Promise resolving to an array of StaticFile objects.\n * @throws {ShipClientError} If called outside Node.js or if fs/path modules fail.\n */\nexport async function processFilesForNode(\n paths: string[],\n options: DeploymentOptions = {},\n platformLimits?: PlatformLimits\n): Promise<StaticFile[]> {\n if (getENV() !== 'node') {\n throw ShipError.business('processFilesForNode can only be called in Node.js environment.');\n }\n\n // Check input directories for unbuilt project markers before recursive walk\n for (const p of paths) {\n const absPath = path.resolve(p);\n try {\n if (fs.statSync(absPath).isDirectory()) {\n const marker = fs.readdirSync(absPath).find(e => UNBUILT_PROJECT_MARKERS.has(e));\n if (marker) {\n throw ShipError.business(`\"${marker}\" detected — deploy your build output (dist/, build/, out/), not the project folder`);\n }\n }\n } catch (e) {\n if (isShipError(e)) throw e;\n // Path errors handled in the existing flatMap below\n }\n }\n\n // 1. Discover all unique, absolute file paths from the input list\n const absolutePaths = paths.flatMap(p => {\n const absPath = path.resolve(p);\n try {\n const stats = fs.statSync(absPath);\n return stats.isDirectory() ? findAllFilePaths(absPath) : [absPath];\n } catch (error) {\n throw ShipError.file(`Path does not exist: ${p}`, p);\n }\n });\n const uniquePaths = [...new Set(absolutePaths)];\n\n // 2. Determine base path for content paths (from INPUT paths, not discovered files)\n const inputAbsolutePaths = paths.map(p => path.resolve(p));\n const inputBasePath = findCommonParent(inputAbsolutePaths.map(p => {\n try {\n const stats = fs.statSync(p);\n return stats.isDirectory() ? p : path.dirname(p);\n } catch {\n return path.dirname(p);\n }\n }));\n\n // 3. Compute content paths (relative to upload root)\n const contentPaths = uniquePaths.map(absPath => {\n if (inputBasePath && inputBasePath.length > 0) {\n const rel = path.relative(inputBasePath, absPath);\n if (rel && typeof rel === 'string' && !rel.startsWith('..')) {\n return rel.replace(/\\\\/g, '/');\n }\n }\n return path.basename(absPath);\n });\n\n // 4. Optimize paths for deployment (strip common root, flatten)\n const deployFiles = optimizeDeployPaths(contentPaths, {\n flatten: options.pathDetect !== false\n });\n const deployPaths = deployFiles.map(f => f.path);\n\n // 5. Filter junk from deploy paths\n const filteredSet = new Set(filterJunk(deployPaths));\n if (filteredSet.size === 0) {\n return [];\n }\n\n // 6. Collect valid file pairs (absolute path for reading, deploy path for output)\n const validAbsPaths: string[] = [];\n const validDeployPaths: string[] = [];\n for (let i = 0; i < uniquePaths.length; i++) {\n if (filteredSet.has(deployPaths[i])) {\n validAbsPaths.push(uniquePaths[i]);\n validDeployPaths.push(deployPaths[i]);\n }\n }\n\n // 7. Process files into StaticFile objects\n const results: StaticFile[] = [];\n let totalSize = 0;\n if (!platformLimits) {\n throw ShipError.config(\n 'Platform limits not provided. processFilesForNode requires the limits ' +\n 'argument — pass `ship.getLimits()` result.'\n );\n }\n\n for (let i = 0; i < validAbsPaths.length; i++) {\n const filePath = validAbsPaths[i];\n const deployPath = validDeployPaths[i];\n \n try {\n // Security validation (shared with browser) — fail fast before any I/O\n validateDeployPath(deployPath, filePath);\n\n const stats = fs.statSync(filePath);\n\n // Skip empty files — R2 cannot store zero-byte objects\n if (stats.size === 0) {\n continue;\n }\n\n // Filename and extension validation (shared with browser)\n validateDeployFile(deployPath, filePath);\n\n // Validate file sizes\n if (stats.size > platformLimits.maxFileSize) {\n throw ShipError.business(`File ${filePath} is too large. Maximum allowed size is ${platformLimits.maxFileSize / (1024 * 1024)}MB.`);\n }\n totalSize += stats.size;\n if (totalSize > platformLimits.maxTotalSize) {\n throw ShipError.business(`Total deploy size is too large. Maximum allowed is ${platformLimits.maxTotalSize / (1024 * 1024)}MB.`);\n }\n\n const content = fs.readFileSync(filePath);\n const { md5 } = await calculateMD5(content);\n\n results.push({\n path: deployPath,\n content,\n size: content.length,\n md5,\n });\n } catch (error) {\n // Re-throw ShipError instances directly\n if (isShipError(error)) {\n throw error;\n }\n // Convert file system errors to ShipError with clear message\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw ShipError.file(`Failed to read file \"${filePath}\": ${errorMessage}`, filePath);\n }\n }\n\n // Final validation\n if (results.length > platformLimits.maxFilesCount) {\n throw ShipError.business(`Too many files to deploy. Maximum allowed is ${platformLimits.maxFilesCount} files.`);\n }\n \n return results;\n}","/**\n * @file Main entry point for the Ship SDK.\n * \n * This is the primary entry point for Node.js environments, providing\n * full file system support and configuration loading capabilities.\n * \n * For browser environments, import from '@shipstatic/ship/browser' instead.\n */\n\n// Re-export everything from the Node.js index, including both named and default exports\nexport * from './node/index.js';\nexport { default } from './node/index.js';\n","/**\n * @file Base Ship SDK class — shared functionality across environments.\n *\n * The constructor is fully synchronous: an `ApiHttp` instance is built immediately\n * with whatever credentials the caller supplied (and, in Node, env vars merged in\n * by the subclass before `super()`). The only deferred work is the one-shot\n * `GET /config` fetch that hydrates platform limits — that's lazy and runs on\n * first API call via `ensureInitialized()`.\n *\n * Subclasses only override what genuinely differs per environment:\n * - `processInput()` — Node reads paths from disk; Browser handles `File[]`\n * - `getDeployBodyCreator()` — Node streams Buffers; Browser builds Blobs\n *\n * Everything else (auth state, resources, events, lazy platform-limits) lives here.\n */\n\nimport { ShipError } from '@shipstatic/types';\nimport type {\n Deployment,\n PlatformLimits,\n DeploymentResource,\n DomainResource,\n AccountResource,\n TokenResource,\n StaticFile,\n} from '@shipstatic/types';\n\nimport { ApiHttp } from './api/http.js';\nimport { resolveConfig } from './core/config.js';\nimport {\n createDeploymentResource,\n createDomainResource,\n createAccountResource,\n createTokenResource,\n type DeployInput,\n} from './resources.js';\nimport type {\n ShipClientOptions,\n ShipEvents,\n DeploymentOptions,\n DeployBodyCreator,\n} from './types.js';\n\n/**\n * Authentication state for the Ship instance.\n * Discriminated union ensures only one auth method is active at a time.\n */\ntype AuthState =\n | { type: 'token'; value: string }\n | { type: 'apiKey'; value: string }\n | null;\n\n/**\n * Abstract base class for Ship SDK implementations.\n */\nexport abstract class Ship {\n // Resource handles, created once at construction. Each is a thin facade\n // bound to `this.http` plus the lazy-init callback.\n public readonly deployments: DeploymentResource;\n public readonly domains: DomainResource;\n public readonly account: AccountResource;\n public readonly tokens: TokenResource;\n\n // The HTTP client and merged options are private — subclasses interact\n // with the base class through the abstract methods below, never by\n // reaching into these fields. Tests bypass via `(ship as any).http = ...`.\n private readonly http: ApiHttp;\n private readonly clientOptions: ShipClientOptions;\n\n // Lazy-init plumbing for the one-shot `GET /config` fetch.\n // `platformLimits` is INSTANCE state (not a module-level singleton): two\n // Ships against different `apiUrl`s — staging + prod, multi-tenant\n // orchestrators, n8n with multiple credentials — must not clobber each\n // other's limits. Each instance owns its hydrated copy.\n // `protected` so subclasses' `processInput` can pass it down to the\n // platform-specific file-validation utilities.\n private initPromise: Promise<void> | null = null;\n protected platformLimits: PlatformLimits | null = null;\n\n // Auth state — consulted dynamically on every request through `getAuthHeaders`.\n private auth: AuthState = null;\n\n constructor(options: ShipClientOptions = {}) {\n // SDK-boundary normalization: empty-string credentials are never valid,\n // and storing them would pollute `mergeDeployOptions` (which checks\n // `=== undefined`, not falsy) and silently suppress per-call defaults\n // — turning what should have been an authenticated deploy into an\n // anonymous PUBLIC_ACCOUNT deploy via the agent-token fallback.\n //\n // Empty strings reach here from shell-expansion of unset CI variables,\n // empty form fields in browser apps, and any other path that produces\n // `''` instead of `undefined`. Normalizing once at the SDK boundary\n // covers every entry point: CLI, Browser SDK, Node SDK, embedded\n // consumers, and direct base-class use in tests.\n options = {\n ...options,\n apiUrl: options.apiUrl || undefined,\n apiKey: options.apiKey || undefined,\n deployToken: options.deployToken || undefined,\n };\n this.clientOptions = options;\n\n // Initialize auth state from constructor options.\n // Deploy token outranks API key when both are provided.\n if (options.deployToken) {\n this.auth = { type: 'token', value: options.deployToken };\n } else if (options.apiKey) {\n this.auth = { type: 'apiKey', value: options.apiKey };\n }\n\n // Build the HTTP client once. The `getAuthHeaders` callback reads `this.auth`\n // dynamically on every request, so `setApiKey()` / `setDeployToken()` take\n // effect immediately without needing to rebuild the client.\n this.http = new ApiHttp({\n ...options,\n ...resolveConfig(options),\n getAuthHeaders: () => this.getAuthHeaders(),\n createDeployBody: this.getDeployBodyCreator(),\n });\n\n const ctx = {\n getApi: () => this.http,\n ensureInit: () => this.ensureInitialized(),\n };\n\n this.deployments = createDeploymentResource({\n ...ctx,\n processInput: (input, opts) => this.processInput(input, opts),\n clientDefaults: this.clientOptions,\n hasAuth: () => this.hasAuth(),\n });\n this.domains = createDomainResource(ctx);\n this.account = createAccountResource(ctx);\n this.tokens = createTokenResource(ctx);\n }\n\n // Environment-specific behavior.\n protected abstract processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;\n protected abstract getDeployBodyCreator(): DeployBodyCreator;\n\n /**\n * Lazy initialization — fetches platform limits (file size / count caps) once,\n * on the first API call. Subsequent calls reuse the resolved promise.\n */\n protected async ensureInitialized(): Promise<void> {\n if (!this.initPromise) {\n this.initPromise = this.fetchPlatformLimits();\n }\n return this.initPromise;\n }\n\n private async fetchPlatformLimits(): Promise<void> {\n try {\n this.platformLimits = await this.http.getLimits();\n } catch (error) {\n // Reset so the next API call can retry initialization.\n this.initPromise = null;\n throw error;\n }\n }\n\n /**\n * Ping the API server to check connectivity.\n */\n async ping(): Promise<boolean> {\n await this.ensureInitialized();\n return this.http.ping();\n }\n\n /**\n * Deploy project (convenience shortcut to `ship.deployments.upload()`).\n */\n async deploy(input: DeployInput, options?: DeploymentOptions): Promise<Deployment> {\n return this.deployments.upload(input, options);\n }\n\n /**\n * Get current account information (convenience shortcut to `ship.account.get()`).\n */\n async whoami() {\n return this.account.get();\n }\n\n /**\n * Get platform limits (max file size, file count, total size).\n * Reuses the response fetched during initialization. Per-instance state —\n * does not leak between concurrent Ships against different API URLs.\n */\n async getLimits(): Promise<PlatformLimits> {\n if (this.platformLimits) return this.platformLimits;\n await this.ensureInitialized();\n return this.platformLimits!;\n }\n\n on<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n this.http.on(event, handler);\n }\n\n off<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n this.http.off(event, handler);\n }\n\n /**\n * Set global headers included in every request.\n * Useful for injecting custom headers (e.g. for admin impersonation).\n */\n setHeaders(headers: Record<string, string>): void {\n this.http.setGlobalHeaders(headers);\n }\n\n /**\n * Clear all custom global headers.\n */\n clearHeaders(): void {\n this.http.setGlobalHeaders({});\n }\n\n /**\n * Sets the deploy token for authentication.\n * Overrides any previously set API key or deploy token.\n * @param token Deploy token (format: `token-<64-char-hex>`)\n */\n public setDeployToken(token: string): void {\n if (!token || typeof token !== 'string') {\n throw ShipError.business('Invalid deploy token provided. Deploy token must be a non-empty string.');\n }\n this.auth = { type: 'token', value: token };\n }\n\n /**\n * Sets the API key for authentication.\n * Overrides any previously set API key or deploy token.\n * @param key API key (format: `ship-<64-char-hex>`)\n */\n public setApiKey(key: string): void {\n if (!key || typeof key !== 'string') {\n throw ShipError.business('Invalid API key provided. API key must be a non-empty string.');\n }\n this.auth = { type: 'apiKey', value: key };\n }\n\n private getAuthHeaders(): Record<string, string> {\n if (!this.auth) return {};\n return { Authorization: `Bearer ${this.auth.value}` };\n }\n\n /**\n * Check whether authentication credentials are configured.\n * Used by resources to fail fast (or trigger the agent-token fallback) when\n * auth is required.\n */\n private hasAuth(): boolean {\n // useCredentials means cookies are used for auth — no explicit token needed.\n if (this.clientOptions.useCredentials) return true;\n return this.auth !== null;\n }\n}\n","/**\n * @file HTTP client for Ship API.\n */\nimport type {\n Deployment,\n DeploymentCreateResponse,\n DeploymentListResponse,\n PingResponse,\n PlatformLimits,\n Domain,\n DomainListResponse,\n DomainDnsResponse,\n DomainRecordsResponse,\n DomainValidateResponse,\n Account,\n SPACheckRequest,\n SPACheckResponse,\n StaticFile,\n TokenCreateResponse,\n TokenListResponse\n} from '@shipstatic/types';\nimport type { ApiDeployOptions, DeployBodyCreator, DomainSetResult, ShipClientOptions } from '../types.js';\nimport { ShipError, DEFAULT_API } from '@shipstatic/types';\nimport { SimpleEvents } from '../events.js';\nimport { validateLabels, validatePassword } from '../lib/validation.js';\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\nconst ENDPOINTS = {\n DEPLOYMENTS: '/deployments',\n DOMAINS: '/domains',\n TOKENS: '/tokens',\n ACCOUNT: '/account',\n LIMITS: '/limits',\n PING: '/ping',\n SPA_CHECK: '/spa-check'\n} as const;\n\nconst DEFAULT_REQUEST_TIMEOUT = 30000;\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\nexport interface ApiHttpOptions extends ShipClientOptions {\n getAuthHeaders: () => Record<string, string>;\n createDeployBody: DeployBodyCreator;\n}\n\ninterface RequestResult<T> {\n data: T;\n status: number;\n}\n\n// =============================================================================\n// HTTP CLIENT\n// =============================================================================\n\nexport class ApiHttp extends SimpleEvents {\n private readonly apiUrl: string;\n private readonly getAuthHeadersCallback: () => Record<string, string>;\n private readonly useCredentials: boolean;\n private readonly timeout: number;\n private readonly createDeployBody: DeployBodyCreator;\n private readonly deployEndpoint: string;\n private globalHeaders: Record<string, string> = {};\n\n constructor(options: ApiHttpOptions) {\n super();\n this.apiUrl = options.apiUrl || DEFAULT_API;\n this.getAuthHeadersCallback = options.getAuthHeaders;\n this.useCredentials = options.useCredentials ?? false;\n this.timeout = options.timeout ?? DEFAULT_REQUEST_TIMEOUT;\n this.createDeployBody = options.createDeployBody;\n this.deployEndpoint = options.deployEndpoint || ENDPOINTS.DEPLOYMENTS;\n }\n\n /**\n * Set global headers included in every request.\n * Priority: globalHeaders (lowest) < instance auth < per-request headers (highest)\n */\n setGlobalHeaders(headers: Record<string, string>): void {\n this.globalHeaders = headers;\n }\n\n // ===========================================================================\n // CORE REQUEST INFRASTRUCTURE\n // ===========================================================================\n\n /**\n * Execute HTTP request with timeout, events, and error handling\n */\n private async executeRequest<T>(\n url: string,\n options: RequestInit,\n operationName: string\n ): Promise<RequestResult<T>> {\n const headers = this.mergeHeaders(options.headers as Record<string, string>);\n const { signal, cleanup } = this.createTimeoutSignal(options.signal);\n\n const fetchOptions: RequestInit = {\n ...options,\n headers,\n credentials: this.useCredentials && !headers.Authorization ? 'include' : undefined,\n signal,\n };\n\n this.emit('request', url, fetchOptions);\n\n try {\n const response = await fetch(url, fetchOptions);\n cleanup();\n\n if (!response.ok) {\n throw await ShipError.fromHttpResponse(response, `${operationName} failed`);\n }\n\n this.emit('response', this.safeClone(response), url);\n const data = await this.parseResponse<T>(this.safeClone(response));\n return { data, status: response.status };\n } catch (error) {\n cleanup();\n // Normalize anything thrown above (fetch failure, abort, response error) into a ShipError.\n // fromFetchError passes existing ShipErrors through unchanged.\n const shipError = ShipError.fromFetchError(error, operationName);\n this.emit('error', shipError, url);\n throw shipError;\n }\n }\n\n /**\n * Simple request - returns data only\n */\n private async request<T>(url: string, options: RequestInit, operationName: string): Promise<T> {\n const { data } = await this.executeRequest<T>(url, options, operationName);\n return data;\n }\n\n /**\n * Request with status - returns data and HTTP status code\n */\n private async requestWithStatus<T>(url: string, options: RequestInit, operationName: string): Promise<RequestResult<T>> {\n return this.executeRequest<T>(url, options, operationName);\n }\n\n // ===========================================================================\n // REQUEST HELPERS\n // ===========================================================================\n\n private mergeHeaders(customHeaders: Record<string, string> = {}): Record<string, string> {\n return { ...this.globalHeaders, ...this.getAuthHeadersCallback(), ...customHeaders };\n }\n\n private createTimeoutSignal(existingSignal?: AbortSignal | null): { signal: AbortSignal; cleanup: () => void } {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n if (existingSignal) {\n const abort = () => controller.abort();\n existingSignal.addEventListener('abort', abort);\n if (existingSignal.aborted) controller.abort();\n }\n\n return {\n signal: controller.signal,\n cleanup: () => clearTimeout(timeoutId)\n };\n }\n\n private safeClone(response: Response): Response {\n try {\n return response.clone();\n } catch {\n return response;\n }\n }\n\n private async parseResponse<T>(response: Response): Promise<T> {\n if (response.headers.get('Content-Length') === '0' || response.status === 204) {\n return undefined as T;\n }\n return response.json() as Promise<T>;\n }\n\n // ===========================================================================\n // PUBLIC API - DEPLOYMENTS\n // ===========================================================================\n\n async deploy(files: StaticFile[], options: ApiDeployOptions = {}): Promise<DeploymentCreateResponse> {\n if (!files.length) {\n throw ShipError.business('No files to deploy');\n }\n for (const file of files) {\n if (!file.md5) {\n throw ShipError.file(`MD5 checksum missing for file: ${file.path}`, file.path);\n }\n }\n\n // Fast-fail on definitely-invalid input before constructing a multipart body.\n validatePassword(options.password);\n const labels = validateLabels(options.labels);\n\n const flags = (options.build || options.prerender || options.spa)\n ? { build: options.build, prerender: options.prerender, spa: options.spa }\n : undefined;\n const { body, headers: bodyHeaders } = await this.createDeployBody(files, {\n labels,\n via: options.via,\n password: options.password,\n flags,\n });\n\n const authHeaders: Record<string, string> = {};\n if (options.deployToken) {\n authHeaders['Authorization'] = `Bearer ${options.deployToken}`;\n } else if (options.apiKey) {\n authHeaders['Authorization'] = `Bearer ${options.apiKey}`;\n }\n if (options.caller) {\n authHeaders['X-Caller'] = options.caller;\n }\n\n return this.request<DeploymentCreateResponse>(\n `${options.apiUrl || this.apiUrl}${this.deployEndpoint}`,\n { method: 'POST', body, headers: { ...bodyHeaders, ...authHeaders }, signal: options.signal || null },\n 'Deploy'\n );\n }\n\n async listDeployments(): Promise<DeploymentListResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}`, { method: 'GET' }, 'List deployments');\n }\n\n async getDeployment(id: string): Promise<Deployment> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}/${encodeURIComponent(id)}`, { method: 'GET' }, 'Get deployment');\n }\n\n async updateDeploymentLabels(id: string, labels: string[]): Promise<Deployment> {\n const normalized = validateLabels(labels);\n return this.request(\n `${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}/${encodeURIComponent(id)}`,\n { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ labels: normalized }) },\n 'Update deployment labels'\n );\n }\n\n async removeDeployment(id: string): Promise<void> {\n await this.request<void>(\n `${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}/${encodeURIComponent(id)}`,\n { method: 'DELETE' },\n 'Remove deployment'\n );\n }\n\n // ===========================================================================\n // PUBLIC API - DOMAINS\n // ===========================================================================\n // All domain methods accept FQDN (Fully Qualified Domain Name) as the `name` parameter.\n // The SDK does not validate or normalize - the API handles all domain semantics.\n\n async setDomain(name: string, deployment?: string, labels?: string[]): Promise<DomainSetResult> {\n const normalized = validateLabels(labels);\n const body: { deployment?: string; labels?: string[] } = {};\n if (deployment) body.deployment = deployment;\n if (normalized !== undefined) body.labels = normalized;\n\n const { data, status } = await this.requestWithStatus<Domain>(\n `${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}`,\n { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) },\n 'Set domain'\n );\n\n return { ...data, isCreate: status === 201 };\n }\n\n async listDomains(): Promise<DomainListResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}`, { method: 'GET' }, 'List domains');\n }\n\n async getDomain(name: string): Promise<Domain> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}`, { method: 'GET' }, 'Get domain');\n }\n\n async removeDomain(name: string): Promise<void> {\n await this.request<void>(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}`, { method: 'DELETE' }, 'Remove domain');\n }\n\n async verifyDomain(name: string): Promise<{ message: string }> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/verify`, { method: 'POST' }, 'Verify domain');\n }\n\n async getDomainDns(name: string): Promise<DomainDnsResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/dns`, { method: 'GET' }, 'Get domain DNS');\n }\n\n async getDomainRecords(name: string): Promise<DomainRecordsResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/records`, { method: 'GET' }, 'Get domain records');\n }\n\n async getDomainShare(name: string): Promise<{ domain: string; hash: string }> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/share`, { method: 'GET' }, 'Get domain share');\n }\n\n async validateDomain(name: string): Promise<DomainValidateResponse> {\n return this.request(\n `${this.apiUrl}${ENDPOINTS.DOMAINS}/validate`,\n { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ domain: name }) },\n 'Validate domain'\n );\n }\n\n // ===========================================================================\n // PUBLIC API - TOKENS\n // ===========================================================================\n\n async createToken(ttl?: number, labels?: string[]): Promise<TokenCreateResponse> {\n const normalized = validateLabels(labels);\n const body: { ttl?: number; labels?: string[] } = {};\n if (ttl !== undefined) body.ttl = ttl;\n if (normalized !== undefined) body.labels = normalized;\n\n return this.request(\n `${this.apiUrl}${ENDPOINTS.TOKENS}`,\n { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) },\n 'Create token'\n );\n }\n\n async listTokens(): Promise<TokenListResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.TOKENS}`, { method: 'GET' }, 'List tokens');\n }\n\n async removeToken(token: string): Promise<void> {\n await this.request<void>(`${this.apiUrl}${ENDPOINTS.TOKENS}/${encodeURIComponent(token)}`, { method: 'DELETE' }, 'Remove token');\n }\n\n async fetchAgentToken(): Promise<TokenCreateResponse> {\n return this.request<TokenCreateResponse>(\n `${this.apiUrl}${ENDPOINTS.TOKENS}/agent`,\n { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}) },\n 'Fetch agent token'\n );\n }\n\n // ===========================================================================\n // PUBLIC API - ACCOUNT & CONFIG\n // ===========================================================================\n\n async getAccount(): Promise<Account> {\n return this.request(`${this.apiUrl}${ENDPOINTS.ACCOUNT}`, { method: 'GET' }, 'Get account');\n }\n\n async getLimits(): Promise<PlatformLimits> {\n return this.request(`${this.apiUrl}${ENDPOINTS.LIMITS}`, { method: 'GET' }, 'Get limits');\n }\n\n async ping(): Promise<boolean> {\n const data = await this.request<PingResponse>(`${this.apiUrl}${ENDPOINTS.PING}`, { method: 'GET' }, 'Ping');\n return data?.success || false;\n }\n\n // ===========================================================================\n // PUBLIC API - SPA CHECK\n // ===========================================================================\n\n async checkSPA(files: StaticFile[], options: ApiDeployOptions = {}): Promise<boolean> {\n const indexFile = files.find(f => f.path === 'index.html' || f.path === '/index.html');\n if (!indexFile || indexFile.size > 100 * 1024) {\n return false;\n }\n\n let indexContent: string;\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(indexFile.content)) {\n indexContent = indexFile.content.toString('utf-8');\n } else if (typeof Blob !== 'undefined' && indexFile.content instanceof Blob) {\n indexContent = await indexFile.content.text();\n } else if (typeof File !== 'undefined' && indexFile.content instanceof File) {\n indexContent = await indexFile.content.text();\n } else {\n return false;\n }\n\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (options.deployToken) {\n headers['Authorization'] = `Bearer ${options.deployToken}`;\n } else if (options.apiKey) {\n headers['Authorization'] = `Bearer ${options.apiKey}`;\n }\n\n const body: SPACheckRequest = { files: files.map(f => f.path), index: indexContent };\n const response = await this.request<SPACheckResponse>(\n `${this.apiUrl}${ENDPOINTS.SPA_CHECK}`,\n { method: 'POST', headers, body: JSON.stringify(body) },\n 'SPA check'\n );\n\n return response.isSPA;\n }\n}\n","/**\n * Event system for Ship SDK\n * Lightweight, reliable event handling with proper error boundaries\n */\n\nimport type { ShipEvents } from './types.js';\n\n/**\n * Lightweight typed event emitter.\n *\n * Public API: `on()` / `off()`. `emit()` is internal — only the SDK\n * publishes events. Throwing handlers are evicted automatically and\n * surfaced as `error` events on the next tick.\n */\nexport class SimpleEvents {\n private handlers = new Map<string, Set<Function>>();\n\n /**\n * Add event handler\n */\n on<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n if (!this.handlers.has(event as string)) {\n this.handlers.set(event as string, new Set());\n }\n this.handlers.get(event as string)!.add(handler);\n }\n\n /**\n * Remove event handler \n */\n off<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n const eventHandlers = this.handlers.get(event as string);\n if (eventHandlers) {\n eventHandlers.delete(handler);\n if (eventHandlers.size === 0) {\n this.handlers.delete(event as string);\n }\n }\n }\n\n /**\n * Emit event (internal use only)\n * @internal\n */\n emit<K extends keyof ShipEvents>(event: K, ...args: ShipEvents[K]): void {\n const eventHandlers = this.handlers.get(event as string);\n if (!eventHandlers) return;\n\n // Snapshot handlers so a handler that mutates the set during iteration\n // (e.g. by removing itself) doesn't skip or duplicate calls.\n const handlerArray = Array.from(eventHandlers);\n\n for (const handler of handlerArray) {\n try {\n handler(...args);\n } catch (error) {\n // A throwing handler is treated as broken — drop it so we don't\n // repeatedly invoke it and re-emit the failure as an `error` event\n // for observability. Defer the re-emit so the next tick has a clean\n // call stack and we can't recurse if the error handler also throws.\n eventHandlers.delete(handler);\n\n if (event !== 'error') {\n setTimeout(() => {\n const err = error instanceof Error ? error : new Error(String(error));\n this.emit('error', err, String(event));\n }, 0);\n }\n }\n }\n }\n}","/**\n * @file Client-side input validation for SDK request boundaries.\n *\n * These validators run before request construction. Constants come from\n * `@shipstatic/types` (`PASSWORD_CONSTRAINTS`, `LABEL_CONSTRAINTS`,\n * `LABEL_PATTERN`) so the SDK and API agree on the rules.\n */\n\nimport {\n LABEL_CONSTRAINTS,\n LABEL_PATTERN,\n PASSWORD_CONSTRAINTS,\n ShipError,\n} from '@shipstatic/types';\n\n/**\n * Validate an optional deployment password.\n *\n * Absent → no-op (an unprotected deployment is a valid choice). Present →\n * must be a string within `PASSWORD_CONSTRAINTS` length bounds. Whitespace\n * is preserved verbatim — significant.\n */\nexport function validatePassword(value: unknown): void {\n if (value === undefined || value === null) return;\n if (typeof value !== 'string') {\n throw ShipError.validation('Password must be a string');\n }\n if (\n value.length < PASSWORD_CONSTRAINTS.MIN_LENGTH ||\n value.length > PASSWORD_CONSTRAINTS.MAX_LENGTH\n ) {\n throw ShipError.validation(\n `Password must be between ${PASSWORD_CONSTRAINTS.MIN_LENGTH} and ${PASSWORD_CONSTRAINTS.MAX_LENGTH} characters`,\n );\n }\n}\n\n/**\n * Validate and normalize an array of labels.\n *\n * Lowercases and trims each entry, enforces per-label length and pattern\n * (`LABEL_CONSTRAINTS` / `LABEL_PATTERN`), count cap, and uniqueness after\n * normalization. Returns the normalized array. An empty array is valid and\n * signals \"clear all labels\" on label-update operations.\n */\nexport function validateLabels(labels: string[]): string[];\nexport function validateLabels(labels: string[] | undefined | null): string[] | undefined;\nexport function validateLabels(labels: string[] | undefined | null): string[] | undefined {\n if (labels === undefined || labels === null) return undefined;\n if (labels.length === 0) return labels;\n\n if (labels.length > LABEL_CONSTRAINTS.MAX_COUNT) {\n throw ShipError.validation(\n `Maximum ${LABEL_CONSTRAINTS.MAX_COUNT} labels allowed`,\n );\n }\n\n const normalized = labels.map((label, i) => {\n if (typeof label !== 'string') {\n throw ShipError.validation(`Label at index ${i} must be a string`);\n }\n const cleaned = label.trim().toLowerCase();\n if (cleaned.length < LABEL_CONSTRAINTS.MIN_LENGTH) {\n throw ShipError.validation(\n `Labels must be at least ${LABEL_CONSTRAINTS.MIN_LENGTH} characters long`,\n );\n }\n if (cleaned.length > LABEL_CONSTRAINTS.MAX_LENGTH) {\n throw ShipError.validation(\n `Labels must be no more than ${LABEL_CONSTRAINTS.MAX_LENGTH} characters long`,\n );\n }\n if (!LABEL_PATTERN.test(cleaned)) {\n throw ShipError.validation(\n `Labels must start and end with alphanumeric characters, with optional separators (${LABEL_CONSTRAINTS.SEPARATORS}) between segments`,\n );\n }\n return cleaned;\n });\n\n const unique = [...new Set(normalized)];\n if (unique.length !== normalized.length) {\n throw ShipError.validation('Duplicate labels are not allowed');\n }\n\n return unique;\n}\n","/**\n * @file Cross-platform configuration helpers.\n *\n * Two pure helpers used by both Node and Browser:\n *\n * - `resolveConfig(options)` — applies the API-URL default. The Node Ship\n * calls this after merging env vars under the user's options; the Browser\n * Ship calls it directly (no ambient sources).\n * - `mergeDeployOptions(perCallOptions, clientDefaults)` — overlays\n * instance-level defaults under per-call overrides for a single deploy.\n *\n * Credential precedence is owned by callers, not this file:\n *\n * - SDK (Node): constructor args > `SHIP_*` env vars (see `node/index.ts`)\n * - SDK (Browser): constructor args only\n * - CLI: `--flag` > env > `.shiprc` / `package.json` (see `cli/create-client.ts`)\n */\n\nimport { DEFAULT_API, type ResolvedConfig } from '@shipstatic/types';\nimport type { ShipClientOptions, DeploymentOptions } from '../types.js';\n\nexport type { ResolvedConfig } from '@shipstatic/types';\n\n/**\n * Apply the API-URL default and project the credential triplet into a\n * `ResolvedConfig` shape. Optional fields are omitted (rather than set to\n * `undefined`) so spread merges downstream behave predictably.\n */\nexport function resolveConfig(options: ShipClientOptions = {}): ResolvedConfig {\n const result: ResolvedConfig = {\n apiUrl: options.apiUrl || DEFAULT_API,\n };\n if (options.apiKey !== undefined) result.apiKey = options.apiKey;\n if (options.deployToken !== undefined) result.deployToken = options.deployToken;\n return result;\n}\n\n/**\n * Overlay client-level defaults under per-call deploy options.\n *\n * Per-call options always win — they're the explicit override for a single\n * `deployments.upload()`. Defaults fill in only when the per-call option is\n * `undefined` (an explicit `null` / empty value passes through).\n */\nexport function mergeDeployOptions(\n options: DeploymentOptions,\n clientDefaults: ShipClientOptions,\n): DeploymentOptions {\n const result: DeploymentOptions = { ...options };\n\n if (result.apiUrl === undefined && clientDefaults.apiUrl !== undefined) {\n result.apiUrl = clientDefaults.apiUrl;\n }\n if (result.apiKey === undefined && clientDefaults.apiKey !== undefined) {\n result.apiKey = clientDefaults.apiKey;\n }\n if (result.deployToken === undefined && clientDefaults.deployToken !== undefined) {\n result.deployToken = clientDefaults.deployToken;\n }\n if (result.timeout === undefined && clientDefaults.timeout !== undefined) {\n result.timeout = clientDefaults.timeout;\n }\n if (result.maxConcurrency === undefined && clientDefaults.maxConcurrency !== undefined) {\n result.maxConcurrency = clientDefaults.maxConcurrency;\n }\n if (result.onProgress === undefined && clientDefaults.onProgress !== undefined) {\n result.onProgress = clientDefaults.onProgress;\n }\n if (result.caller === undefined && clientDefaults.caller !== undefined) {\n result.caller = clientDefaults.caller;\n }\n\n return result;\n}\n","/**\n * Ship SDK resource factory functions.\n */\nimport {\n ShipError,\n isShipError,\n ErrorType,\n type StaticFile,\n type DeployInput,\n type DeploymentResource,\n type DomainResource,\n type AccountResource,\n type TokenResource\n} from '@shipstatic/types';\n\nexport type {\n StaticFile,\n DeployInput,\n DeploymentResource,\n DomainResource,\n AccountResource,\n TokenResource\n};\nimport type { ApiHttp } from './api/http.js';\nimport type { ShipClientOptions, DeploymentOptions } from './types.js';\nimport { mergeDeployOptions } from './core/config.js';\nimport { detectAndConfigureSPA } from './lib/spa.js';\n\n/**\n * Shared context for all resource factories.\n */\nexport interface ResourceContext {\n getApi: () => ApiHttp;\n ensureInit: () => Promise<void>;\n}\n\n/**\n * Extended context for deployment resource.\n */\nexport interface DeploymentResourceContext extends ResourceContext {\n processInput: (input: DeployInput, options: DeploymentOptions) => Promise<StaticFile[]>;\n clientDefaults?: ShipClientOptions;\n hasAuth?: () => boolean;\n}\n\n/**\n * Upload deployment resource with all CRUD operations.\n */\nexport function createDeploymentResource(ctx: DeploymentResourceContext): DeploymentResource {\n const { getApi, ensureInit, processInput, clientDefaults, hasAuth } = ctx;\n\n return {\n upload: async (input: DeployInput, options: DeploymentOptions = {}) => {\n await ensureInit();\n\n const mergedOptions = clientDefaults\n ? mergeDeployOptions(options, clientDefaults)\n : options;\n\n // No credentials — deploy publicly via agent token (short-lived, IP-locked, under PUBLIC_ACCOUNT)\n if (hasAuth && !hasAuth() && !mergedOptions.deployToken && !mergedOptions.apiKey) {\n try {\n const api = getApi();\n const { secret } = await api.fetchAgentToken();\n mergedOptions.deployToken = secret;\n } catch (err) {\n if (isShipError(err) && err.type === ErrorType.RateLimit) {\n throw ShipError.rateLimit(\n 'public deploy rate limit exceeded, try again later or run \\'ship config\\' for a free account with higher limits'\n );\n }\n throw err;\n }\n }\n\n if (!processInput) {\n throw ShipError.config('processInput function is not provided.');\n }\n\n const apiClient = getApi();\n let staticFiles = await processInput(input, mergedOptions);\n staticFiles = await detectAndConfigureSPA(staticFiles, apiClient, mergedOptions);\n\n return apiClient.deploy(staticFiles, mergedOptions);\n },\n\n list: async () => {\n await ensureInit();\n return getApi().listDeployments();\n },\n\n get: async (id: string) => {\n await ensureInit();\n return getApi().getDeployment(id);\n },\n\n set: async (id: string, options: { labels: string[] }) => {\n await ensureInit();\n return getApi().updateDeploymentLabels(id, options.labels);\n },\n\n remove: async (id: string) => {\n await ensureInit();\n await getApi().removeDeployment(id);\n }\n };\n}\n\n/**\n * Create domain resource with all CRUD operations.\n *\n * @remarks\n * The `name` parameter in all methods is an FQDN (Fully Qualified Domain Name).\n * The SDK does not validate or normalize domain names - the API handles all domain semantics.\n */\nexport function createDomainResource(ctx: ResourceContext): DomainResource {\n const { getApi, ensureInit } = ctx;\n\n return {\n // INTENTIONAL DESIGN: The API does NOT support unlinking domains (setting deployment to null).\n // Once a domain is linked to a deployment, it must always have a deployment.\n // Supported: reserve (omit deployment), link, switch deployments atomically, delete entirely.\n // Not supported: unlink after linking (creates ambiguous state with no clear use case).\n // See npm/ship/CLAUDE.md \"Domain Write Semantics\" for full rationale.\n set: async (name: string, options: { deployment?: string; labels?: string[] } = {}) => {\n await ensureInit();\n return getApi().setDomain(name, options.deployment, options.labels);\n },\n\n list: async () => {\n await ensureInit();\n return getApi().listDomains();\n },\n\n get: async (name: string) => {\n await ensureInit();\n return getApi().getDomain(name);\n },\n\n remove: async (name: string) => {\n await ensureInit();\n await getApi().removeDomain(name);\n },\n\n verify: async (name: string) => {\n await ensureInit();\n return getApi().verifyDomain(name);\n },\n\n validate: async (name: string) => {\n await ensureInit();\n return getApi().validateDomain(name);\n },\n\n dns: async (name: string) => {\n await ensureInit();\n return getApi().getDomainDns(name);\n },\n\n records: async (name: string) => {\n await ensureInit();\n return getApi().getDomainRecords(name);\n },\n\n share: async (name: string) => {\n await ensureInit();\n return getApi().getDomainShare(name);\n }\n };\n}\n\n/**\n * Create account resource (whoami functionality).\n */\nexport function createAccountResource(ctx: ResourceContext): AccountResource {\n const { getApi, ensureInit } = ctx;\n\n return {\n get: async () => {\n await ensureInit();\n return getApi().getAccount();\n }\n };\n}\n\n/**\n * Create token resource for managing deploy tokens.\n */\nexport function createTokenResource(ctx: ResourceContext): TokenResource {\n const { getApi, ensureInit } = ctx;\n\n return {\n create: async (options: { ttl?: number; labels?: string[] } = {}) => {\n await ensureInit();\n return getApi().createToken(options.ttl, options.labels);\n },\n\n list: async () => {\n await ensureInit();\n return getApi().listTokens();\n },\n\n remove: async (token: string) => {\n await ensureInit();\n await getApi().removeToken(token);\n }\n };\n}\n","/**\n * @file SPA detection and auto-configuration utilities.\n *\n * Provides SPA detection and ship.json generation functionality\n * that can be used by both Node.js and browser environments.\n */\n\nimport { DEPLOYMENT_CONFIG_FILENAME, SPA_DEFAULT_CONFIG } from '@shipstatic/types';\nimport { calculateMD5 } from './md5.js';\nimport type { StaticFile, DeploymentOptions } from '../types.js';\nimport type { ApiHttp } from '../api/http.js';\n\n/**\n * Creates ship.json configuration for SPA projects.\n * @returns Promise resolving to StaticFile with SPA configuration\n */\nexport async function createSPAConfig(): Promise<StaticFile> {\n const configString = JSON.stringify(SPA_DEFAULT_CONFIG, null, 2);\n\n // Create content that works in both browser and Node.js environments\n let content: Buffer | Blob;\n if (typeof Buffer !== 'undefined') {\n // Node.js environment\n content = Buffer.from(configString, 'utf-8');\n } else {\n // Browser environment\n content = new Blob([configString], { type: 'application/json' });\n }\n\n const { md5 } = await calculateMD5(content);\n\n return {\n path: DEPLOYMENT_CONFIG_FILENAME,\n content,\n size: configString.length,\n md5\n };\n}\n\n/**\n * Detects SPA projects and auto-generates configuration.\n * This function can be used by both Node.js and browser environments.\n *\n * @param files - Array of StaticFiles to analyze\n * @param apiClient - HTTP client for API communication\n * @param options - Deployment options containing SPA detection settings\n * @returns Promise resolving to files array with optional SPA config added\n */\nexport async function detectAndConfigureSPA(\n files: StaticFile[],\n apiClient: ApiHttp,\n options: DeploymentOptions\n): Promise<StaticFile[]> {\n // Skip if disabled, config already exists, or server will handle detection\n if (options.spaDetect === false || options.spa || options.build || options.prerender || files.some(f => f.path === DEPLOYMENT_CONFIG_FILENAME)) {\n return files;\n }\n\n try {\n const isSPA = await apiClient.checkSPA(files, options);\n\n if (isSPA) {\n const spaConfig = await createSPAConfig();\n return [...files, spaConfig];\n }\n } catch (error) {\n // SPA detection failed, continue silently without auto-config\n }\n\n return files;\n}\n","/**\n * @file Ship SDK for Node.js environments.\n *\n * The Node-side `Ship` adds two things on top of the base class:\n * 1. Environment detection — refuses to construct outside Node.\n * 2. `SHIP_*` env-var resolution as the universal \"process boundary\" credential\n * source, mirroring the OpenAI / Anthropic SDK convention. Constructor\n * arguments win over env vars.\n *\n * The SDK does NOT read `~/.shiprc` or `package.json` `\"ship\"` keys — that's\n * the CLI's job (see `cli/shiprc.ts`). Keeping file resolution out of the SDK\n * is what lets embedded consumers (MCP, n8n, GitHub Action) safely write\n * `new Ship({})` for anonymous public deployments without inheriting the host\n * developer's personal credentials.\n */\n\nimport { Ship as BaseShip } from '../shared/base-ship.js';\nimport { ShipError } from '@shipstatic/types';\nimport { getENV } from '../shared/lib/env.js';\nimport { readEnvConfig } from './core/config.js';\nimport type {\n ShipClientOptions,\n Deployment,\n DeployInput,\n DeploymentOptions,\n StaticFile,\n DeployBodyCreator,\n} from '../shared/types.js';\nimport { createDeployBody } from './core/deploy-body.js';\n\n// Export all shared functionality\nexport * from '../shared/index.js';\n\n/**\n * Ship SDK Client for Node.js environments.\n *\n * @example\n * ```typescript\n * // Authenticated — explicit API key\n * const ship = new Ship({ apiKey: 'ship-xxxx' });\n *\n * // Authenticated — picks up SHIP_API_KEY from env\n * const ship = new Ship({});\n *\n * // Anonymous public deploy — works when neither constructor nor env provides creds\n * const ship = new Ship({});\n * await ship.deploy('./dist');\n * ```\n */\nexport class Ship extends BaseShip {\n constructor(options: ShipClientOptions = {}) {\n if (getENV() !== 'node') {\n throw ShipError.business('Node.js Ship class can only be used in Node.js environment.');\n }\n\n // Layer env vars under constructor options. The merged result is what the\n // base class sees, so auth state and the HTTP client are fully formed by\n // the time the constructor returns — no async config phase needed.\n //\n // `||` (not `??`) is deliberate: empty strings on `options` fall through\n // to env, matching the CLI's `mergeCliConfig` behavior and preventing the\n // surprising case where a caller passing `apiKey: ''` (e.g. from an\n // unset variable) silently suppresses a perfectly good `SHIP_API_KEY`.\n const env = readEnvConfig();\n super({\n ...options,\n apiUrl: options.apiUrl || env.apiUrl,\n apiKey: options.apiKey || env.apiKey,\n deployToken: options.deployToken || env.deployToken,\n });\n }\n\n /**\n * Deploy file or directory paths to ShipStatic. Convenience shortcut for\n * `ship.deployments.upload()`.\n *\n * Wrong-platform inputs (e.g. `File[]`) fail at compile time. For\n * platform-neutral code, use `ship.deployments.upload()`, which accepts\n * the wider `DeployInput` and validates at runtime — that asymmetry is\n * intentional: the convenience shortcut narrows; the resource-layer\n * contract stays platform-neutral.\n */\n async deploy(input: string | string[], options?: DeploymentOptions): Promise<Deployment> {\n return super.deploy(input, options);\n }\n\n protected async processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]> {\n // Normalize string to string[] and validate.\n const paths = typeof input === 'string' ? [input] : input;\n\n if (!Array.isArray(paths) || !paths.every(p => typeof p === 'string')) {\n throw ShipError.business('Invalid input type for Node.js environment. Expected string or string[].');\n }\n\n if (paths.length === 0) {\n throw ShipError.business('No files to deploy.');\n }\n\n const { processFilesForNode } = await import('./core/node-files.js');\n return processFilesForNode(paths, options, this.platformLimits ?? undefined);\n }\n\n protected getDeployBodyCreator(): DeployBodyCreator {\n return createDeployBody;\n }\n}\n\n// Default export (for `import Ship from '@shipstatic/ship'`)\nexport default Ship;\n\n// Node-only utilities (path-walking + MD5 over the local filesystem)\nexport { processFilesForNode } from './core/node-files.js';\n","/**\n * @file Environment variable resolution for the Node.js Ship SDK.\n *\n * The SDK has exactly one ambient credential source: process environment variables.\n * `SHIP_API_KEY`, `SHIP_DEPLOY_TOKEN`, and `SHIP_API_URL` are honored as the\n * universal \"process boundary\" — the same idiom used by the OpenAI and Anthropic\n * SDKs. Constructor arguments always win over env vars.\n *\n * File-based config (`~/.shiprc`, `package.json` `\"ship\"` key) is the CLI's\n * responsibility — see `src/node/cli/shiprc.ts`. The SDK does not read files,\n * which is what lets embedded consumers (MCP, n8n, GitHub Action) construct\n * `new Ship({})` for anonymous deployments without leaking the host developer's\n * personal credentials.\n */\n\nimport { z } from 'zod';\nimport type { ShipClientOptions } from '../../shared/types.js';\nimport { ShipError } from '@shipstatic/types';\nimport { getENV } from '../../shared/lib/env.js';\nimport { CREDENTIAL_FIELDS } from '../../shared/core/credential-schema.js';\n\n// `.strict()` matches the file-config schema. The `raw` object below is\n// constructed from a fixed set of keys, so .strict() doesn't catch user\n// typos here (env vars we don't read are simply never put into `raw` in\n// the first place). What it does catch is a *contributor* error — adding\n// a new env-var read without updating `CREDENTIAL_FIELDS` produces a clear\n// validation failure rather than a silently-stripped value. Nearly free\n// (one method call), and keeps both schemas reading the same.\nconst EnvConfigSchema = z.object(CREDENTIAL_FIELDS).strict();\n\n/**\n * Map a `ShipClientOptions` field name (camelCase) back to the env var that\n * supplied it (SCREAMING_SNAKE_CASE), so validation errors point users at\n * the actual variable they need to fix. Kept as an explicit table rather\n * than a regex because the set is small, fixed, and unambiguous.\n */\nconst ENV_VAR_BY_FIELD: Record<string, string> = {\n apiUrl: 'SHIP_API_URL',\n apiKey: 'SHIP_API_KEY',\n deployToken: 'SHIP_DEPLOY_TOKEN',\n};\n\n/**\n * Read `SHIP_*` environment variables and validate the result.\n *\n * Empty strings (CI/Docker often sets env vars to `\"\"` instead of unsetting them)\n * are normalized to `undefined` before validation, so they don't trigger zod's\n * \"min length 1\" check or accidentally override a valid constructor argument.\n *\n * Returns an empty object outside Node.js — browser/edge runtimes have no\n * `process.env` we should reach into.\n */\nexport function readEnvConfig(): Partial<ShipClientOptions> {\n if (getENV() !== 'node') return {};\n\n const raw = {\n apiUrl: process.env.SHIP_API_URL || undefined,\n apiKey: process.env.SHIP_API_KEY || undefined,\n deployToken: process.env.SHIP_DEPLOY_TOKEN || undefined,\n };\n\n try {\n return EnvConfigSchema.parse(raw);\n } catch (error) {\n if (error instanceof z.ZodError) {\n const issue = error.issues[0];\n const field = issue.path[0] as string | undefined;\n const envVar = (field && ENV_VAR_BY_FIELD[field]) ?? 'SHIP environment configuration';\n throw ShipError.config(`Invalid ${envVar}: ${issue.message}`);\n }\n throw ShipError.config('Invalid environment configuration');\n }\n}\n","/**\n * @file Single source of truth for credential field validation.\n *\n * Both the SDK env reader (`node/core/config.ts`) and the CLI file loader\n * (`node/cli/shiprc.ts`) import these — if we tighten or relax a rule\n * (e.g. enforcing the `ship-` prefix), both layers update together.\n *\n * Lives in its own file (not alongside `resolveConfig`) because it's a pure\n * data constant: tests that mock the runtime behavior of `resolveConfig` /\n * `mergeDeployOptions` shouldn't have to forward this through their mocks.\n */\n\nimport { z } from 'zod';\n\nexport const CREDENTIAL_FIELDS = {\n apiUrl: z.string().url().optional(),\n apiKey: z.string().min(1).optional(),\n deployToken: z.string().min(1).optional(),\n};\n","/**\n * Node.js-specific deploy body creation.\n */\nimport { ShipError } from '@shipstatic/types';\nimport type { StaticFile, DeployBody, DeployBodyContext } from '../../shared/types.js';\n\nexport async function createDeployBody(\n files: StaticFile[],\n context: DeployBodyContext = {},\n): Promise<DeployBody> {\n const { FormData, File } = await import('formdata-node');\n const { FormDataEncoder } = await import('form-data-encoder');\n\n const { labels, via, password, flags } = context;\n const formData = new FormData();\n const checksums: string[] = [];\n\n for (const file of files) {\n // 1. Validate content type\n if (!Buffer.isBuffer(file.content) && !(typeof Blob !== 'undefined' && file.content instanceof Blob)) {\n throw ShipError.file(`Unsupported file.content type for Node.js: ${file.path}`, file.path);\n }\n\n // 2. Validate md5\n if (!file.md5) {\n throw ShipError.file(`File missing md5 checksum: ${file.path}`, file.path);\n }\n\n // 3. Create File and append — API derives Content-Type from extension\n const fileInstance = new File([file.content], file.path, { type: 'application/octet-stream' });\n formData.append('files[]', fileInstance);\n checksums.push(file.md5);\n }\n\n formData.append('checksums', JSON.stringify(checksums));\n\n if (labels && labels.length > 0) formData.append('labels', JSON.stringify(labels));\n if (via) formData.append('via', via);\n if (password) formData.append('password', password);\n if (flags?.build) formData.append('build', 'true');\n if (flags?.prerender) formData.append('prerender', 'true');\n if (flags?.spa) formData.append('spa', 'true');\n\n const encoder = new FormDataEncoder(formData);\n const chunks = [];\n for await (const chunk of encoder.encode()) {\n chunks.push(Buffer.from(chunk));\n }\n const body = Buffer.concat(chunks);\n\n return {\n body: body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength) as ArrayBuffer,\n headers: {\n 'Content-Type': encoder.contentType,\n 'Content-Length': Buffer.byteLength(body).toString()\n }\n };\n}\n","/**\n * @file Shared SDK exports - environment agnostic.\n */\n\n// Core functionality\nexport * from './resources.js';\nexport * from './types.js';\nexport * from './api/http.js';\nexport * from './core/constants.js';\nexport * from './core/config.js';\nexport { Ship } from './base-ship.js';\n\n// Shared utilities\nexport * from './lib/md5.js';\nexport * from './lib/text.js';\nexport * from './lib/junk.js';\nexport * from './lib/deploy-paths.js';\nexport * from './lib/env.js';\nexport * from './lib/file-validation.js';\nexport * from './lib/security.js';\n\n// Re-export types from @shipstatic/types\nexport { ShipError, ErrorType } from '@shipstatic/types';\nexport type { PingResponse, Deployment, Domain, Account } from '@shipstatic/types';","/**\n * Utility functions for string manipulation.\n */\n\n/**\n * Simple utility to pluralize a word based on a count.\n * @param count The number to determine pluralization.\n * @param singular The singular form of the word.\n * @param plural The plural form of the word.\n * @param includeCount Whether to include the count in the returned string. Defaults to true.\n * @returns A string with the count and the correctly pluralized word.\n */\nexport function pluralize(\n count: number,\n singular: string,\n plural: string,\n includeCount: boolean = true\n): string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AAII,CAAI,GAAKA,CAC7C,CDLAC,KACAC,KACAC,IACAC,KACAC,KAGAC,IJyFAC,KA9DO,IAAMC,EAAN,cAAmBA,CAAS,CACjC,YAAYC,EAA6B,CAAC,EAAG,CAC3C,GAAIC,EAAO,IAAM,OACf,MAAMC,EAAU,SAAS,6DAA6D,EAWxF,IAAMC,EAAMC,GAAc,EAC1B,MAAM,CACJ,GAAGJ,EACH,OAAQA,EAAQ,QAAUG,EAAI,OAC9B,OAAQH,EAAQ,QAAUG,EAAI,OAC9B,YAAaH,EAAQ,aAAeG,EAAI,WAC1C,CAAC,CACH,CAYA,MAAM,OAAOE,EAA0BL,EAAkD,CACvF,OAAO,MAAM,OAAOK,EAAOL,CAAO,CACpC,CAEA,MAAgB,aAAaK,EAAoBL,EAAmD,CAElG,IAAMM,EAAQ,OAAOD,GAAU,SAAW,CAACA,CAAK,EAAIA,EAEpD,GAAI,CAAC,MAAM,QAAQC,CAAK,GAAK,CAACA,EAAM,MAAMC,GAAK,OAAOA,GAAM,QAAQ,EAClE,MAAML,EAAU,SAAS,0EAA0E,EAGrG,GAAII,EAAM,SAAW,EACnB,MAAMJ,EAAU,SAAS,qBAAqB,EAGhD,GAAM,CAAE,oBAAAM,CAAoB,EAAI,KAAM,uCACtC,OAAOA,EAAoBF,EAAON,EAAS,KAAK,gBAAkB,MAAS,CAC7E,CAEU,sBAA0C,CAClD,OAAOS,EACT,CACF,EAGOC,GAAQX","names":["isShipError","error","isBlockedExtension","filename","dotIndex","ext","BLOCKED_EXTENSIONS","hasUnsafeChars","UNSAFE_FILENAME_CHARS","hasUnbuiltMarker","filePath","s","UNBUILT_PROJECT_MARKERS","validateApiKey","apiKey","API_KEY","ShipError","hexPart","validateDeployToken","deployToken","DEPLOY_TOKEN","validateApiUrl","apiUrl","url","isDeployment","input","isPlatformDomain","domain","platformDomain","isCustomDomain","extractSubdomain","generateDeploymentUrl","deployment","generateDomainUrl","serializeLabels","labels","deserializeLabels","labelsJson","parsed","DeploymentStatus","DomainStatus","AccountPlan","ErrorType","ERROR_CATEGORIES","SERVER_PRODUCIBLE_ERROR_TYPES","AuthMethod","DEPLOYMENT_CONFIG_FILENAME","SPA_DEFAULT_CONFIG","DEFAULT_API","FileValidationStatus","LABEL_CONSTRAINTS","LABEL_PATTERN","PASSWORD_CONSTRAINTS","init_dist","__esmMin","t","_ShipError","type","message","status","details","response","fallbackMessage","bodyType","json","obj","text","cause","operationName","op","resource","id","errorType","__setTestEnvironment","env","_testEnvironment","detectEnvironment","getENV","init_env","__esmMin","calculateMD5Browser","blob","SparkMD5","resolve","reject","chunks","currentChunk","spark","fileReader","loadNext","start","end","e","result","ShipError","calculateMD5Node","input","crypto","hash","fs","stream","err","chunk","calculateMD5","env","getENV","init_md5","__esmMin","init_env","init_dist","filterJunk","filePaths","options","p","hasUnbuiltMarker","ShipError","filePath","parts","basename","part","directorySegments","segment","JUNK_DIRECTORIES","junkDir","import_junk","init_junk","__esmMin","init_dist","findCommonParent","dirPaths","normalizedPaths","p","pathSegments","commonSegments","minLength","i","segment","segments","normalizeWebPath","path","init_path","__esmMin","optimizeDeployPaths","filePaths","options","path","normalizeWebPath","extractFileName","commonPrefix","findCommonDirectory","filePath","deployPath","prefixToRemove","pathSegments","commonSegments","minLength","segments","i","segment","init_deploy_paths","__esmMin","init_path","formatFileSize","bytes","decimals","k","sizes","i","validateFileName","filename","hasUnsafeChars","reservedNames","nameWithoutPath","validateFiles","files","config","errors","warnings","fileStatuses","issue","file","hasUnbuiltMarker","f","FileValidationStatus","totalSize","fileStatus","statusMessage","nameValidation","isBlockedExtension","validFiles","canDeploy","getValidFiles","allValidFilesReady","init_file_validation","__esmMin","init_dist","validateDeployPath","deployPath","sourceIdentifier","ShipError","validateDeployFile","nameCheck","validateFileName","isBlockedExtension","init_security","__esmMin","init_dist","init_file_validation","node_files_exports","__export","processFilesForNode","findAllFilePaths","dirPath","visited","results","realPath","entries","entry","fullPath","stats","subFiles","paths","options","platformLimits","getENV","ShipError","p","absPath","marker","e","UNBUILT_PROJECT_MARKERS","isShipError","absolutePaths","uniquePaths","inputAbsolutePaths","inputBasePath","findCommonParent","contentPaths","rel","deployPaths","optimizeDeployPaths","f","filteredSet","filterJunk","validAbsPaths","validDeployPaths","i","totalSize","filePath","deployPath","validateDeployPath","validateDeployFile","content","md5","calculateMD5","error","errorMessage","fs","path","init_node_files","__esmMin","init_env","init_md5","init_junk","init_security","init_dist","init_deploy_paths","init_path","src_exports","__export","API_KEY","AccountPlan","ApiHttp","AuthMethod","BLOCKED_EXTENSIONS","DEFAULT_API","DEPLOYMENT_CONFIG_FILENAME","DEPLOY_TOKEN","DeploymentStatus","DomainStatus","ErrorType","FileValidationStatus","JUNK_DIRECTORIES","LABEL_CONSTRAINTS","LABEL_PATTERN","PASSWORD_CONSTRAINTS","SPA_DEFAULT_CONFIG","Ship","ShipError","UNBUILT_PROJECT_MARKERS","UNSAFE_FILENAME_CHARS","__setTestEnvironment","allValidFilesReady","calculateMD5","createAccountResource","createDeploymentResource","createDomainResource","createTokenResource","node_default","deserializeLabels","extractSubdomain","filterJunk","formatFileSize","generateDeploymentUrl","generateDomainUrl","getENV","getValidFiles","hasUnbuiltMarker","hasUnsafeChars","isBlockedExtension","isCustomDomain","isDeployment","isPlatformDomain","isShipError","mergeDeployOptions","optimizeDeployPaths","pluralize","processFilesForNode","resolveConfig","serializeLabels","validateApiKey","validateApiUrl","validateDeployFile","validateDeployPath","validateDeployToken","validateFileName","validateFiles","__toCommonJS","init_dist","init_dist","SimpleEvents","event","handler","eventHandlers","args","handlerArray","error","err","init_dist","validatePassword","value","ShipError","PASSWORD_CONSTRAINTS","validateLabels","labels","LABEL_CONSTRAINTS","normalized","label","i","cleaned","LABEL_PATTERN","unique","ENDPOINTS","DEFAULT_REQUEST_TIMEOUT","ApiHttp","SimpleEvents","options","DEFAULT_API","headers","url","operationName","signal","cleanup","fetchOptions","response","ShipError","error","shipError","data","customHeaders","existingSignal","controller","timeoutId","abort","files","file","validatePassword","labels","validateLabels","flags","body","bodyHeaders","authHeaders","id","normalized","name","deployment","status","ttl","token","indexFile","f","indexContent","init_dist","resolveConfig","options","result","DEFAULT_API","mergeDeployOptions","clientDefaults","init_dist","init_dist","init_md5","createSPAConfig","configString","SPA_DEFAULT_CONFIG","content","md5","calculateMD5","DEPLOYMENT_CONFIG_FILENAME","detectAndConfigureSPA","files","apiClient","options","f","spaConfig","createDeploymentResource","ctx","getApi","ensureInit","processInput","clientDefaults","hasAuth","input","options","mergedOptions","mergeDeployOptions","api","secret","err","isShipError","ErrorType","ShipError","apiClient","staticFiles","detectAndConfigureSPA","id","createDomainResource","name","createAccountResource","createTokenResource","token","Ship","options","ApiHttp","resolveConfig","ctx","createDeploymentResource","input","opts","createDomainResource","createAccountResource","createTokenResource","error","event","handler","headers","token","ShipError","key","init_dist","init_env","import_zod","init_dist","init_env","import_zod","CREDENTIAL_FIELDS","EnvConfigSchema","CREDENTIAL_FIELDS","ENV_VAR_BY_FIELD","readEnvConfig","getENV","raw","error","issue","field","envVar","ShipError","init_dist","createDeployBody","files","context","FormData","File","FormDataEncoder","labels","via","password","flags","formData","checksums","file","ShipError","fileInstance","encoder","chunks","chunk","body","init_md5","pluralize","count","singular","plural","includeCount","word","init_junk","init_deploy_paths","init_env","init_file_validation","init_security","init_dist","init_node_files","Ship","options","getENV","ShipError","env","readEnvConfig","input","paths","p","processFilesForNode","createDeployBody","node_default"]}
|
|
1
|
+
{"version":3,"sources":["../node_modules/.pnpm/@shipstatic+types@0.9.8/node_modules/@shipstatic/types/dist/index.js","../src/shared/lib/env.ts","../src/shared/lib/md5.ts","../src/shared/lib/junk.ts","../src/shared/lib/path.ts","../src/shared/lib/deploy-paths.ts","../src/shared/lib/file-validation.ts","../src/shared/lib/security.ts","../src/node/core/node-files.ts","../src/index.ts","../src/shared/base-ship.ts","../src/shared/api/http.ts","../src/shared/events.ts","../src/shared/lib/validation.ts","../src/shared/core/config.ts","../src/shared/resources.ts","../src/shared/lib/spa.ts","../src/node/index.ts","../src/node/core/config.ts","../src/shared/core/credential-schema.ts","../src/node/core/deploy-body.ts","../src/shared/index.ts","../src/shared/lib/text.ts"],"sourcesContent":["/**\n * @file Shared TypeScript types, constants, and utilities for the ShipStatic platform.\n * This package is the single source of truth for all shared data structures.\n */\n// =============================================================================\n// I. CORE ENTITIES\n// =============================================================================\n/**\n * Deployment status constants\n */\nexport const DeploymentStatus = {\n PENDING: 'pending',\n SUCCESS: 'success',\n FAILED: 'failed',\n DELETING: 'deleting'\n};\n// =============================================================================\n// DOMAIN TYPES\n// =============================================================================\n/**\n * Domain status constants\n *\n * - PENDING: DNS not configured\n * - PARTIAL: DNS partially configured\n * - SUCCESS: DNS fully verified\n * - PAUSED: Domain paused due to plan enforcement (billing)\n */\nexport const DomainStatus = {\n PENDING: 'pending',\n PARTIAL: 'partial',\n SUCCESS: 'success',\n PAUSED: 'paused'\n};\n// =============================================================================\n// ACCOUNT TYPES\n// =============================================================================\n/**\n * Account plan constants\n */\nexport const AccountPlan = {\n FREE: 'free',\n STANDARD: 'standard',\n SPONSORED: 'sponsored',\n ENTERPRISE: 'enterprise',\n SUSPENDED: 'suspended',\n TERMINATING: 'terminating',\n TERMINATED: 'terminated'\n};\n// =============================================================================\n// ERROR SYSTEM\n// =============================================================================\n/**\n * All possible error types in the ShipStatic platform.\n *\n * Developer-friendly key names map to stable wire-format string values.\n * Both the value and the type are exported under the same name so callers\n * can use `ErrorType.Validation` (value comparison) and `: ErrorType` (type\n * annotation) without ceremony — matching the pattern other status objects\n * (`DeploymentStatus`, `DomainStatus`, `AccountPlan`, `AuthMethod`) follow.\n */\nexport const ErrorType = {\n /** Validation failed (400). Input shape is wrong. */\n Validation: 'validation_failed',\n /** Resource not found (404). */\n NotFound: 'not_found',\n /** Authenticated but not allowed (403). User lacks permission for this action. */\n Forbidden: 'forbidden',\n /** Rate limit exceeded (429). */\n RateLimit: 'rate_limit_exceeded',\n /** Authentication required or failed (401). Missing/invalid credentials. */\n Authentication: 'authentication_failed',\n /** Business rule violation. Catch-all for 4xx state-rule errors that aren't more specific. */\n Business: 'business_logic_error',\n /** API server error (500). Generic server-side fault. */\n Api: 'internal_server_error',\n /** Network/connection error. Client-side only — set by HTTP clients on fetch failure; never produced server-side. */\n Network: 'network_error',\n /** Operation was cancelled. Client-side only — set on `AbortSignal` abort; never produced server-side. */\n Cancelled: 'operation_cancelled',\n /** File operation error. Client-side only — set by SDK during local file processing; never produced server-side. */\n File: 'file_error',\n /** Configuration error. Client-side only — set by SDK during config parsing/validation; never produced server-side. */\n Config: 'config_error',\n};\n/**\n * Error types that originate exclusively on the client (HTTP clients, SDK\n * file processing, local config parsing). These never appear on the wire\n * from the server, so `fromHttpResponse` will not trust them even if a\n * misbehaving server claims one in `body.error`.\n */\nconst CLIENT_ONLY_ERROR_TYPES = new Set([\n ErrorType.Network,\n ErrorType.Cancelled,\n ErrorType.File,\n ErrorType.Config,\n]);\n/**\n * Categorizes error types for the `isClientError` / `isNetworkError` /\n * `isAuthError` helpers. Each `Set` is typed against the wider `ErrorType`\n * union so `.has(error.type)` accepts any value from the union.\n */\nconst ERROR_CATEGORIES = {\n client: new Set([ErrorType.Business, ErrorType.Config, ErrorType.File, ErrorType.Forbidden, ErrorType.Validation]),\n network: new Set([ErrorType.Network]),\n auth: new Set([ErrorType.Authentication]),\n};\n/**\n * Error types the server can legitimately produce on the wire. Used by\n * `ShipError.fromHttpResponse` to validate the body's `error` field before\n * trusting it as `ShipError.type`. Derived by exclusion from\n * `CLIENT_ONLY_ERROR_TYPES` so adding a new server-producible type to\n * `ErrorType` is automatically picked up.\n */\nconst SERVER_PRODUCIBLE_ERROR_TYPES = new Set(Object.values(ErrorType).filter(t => !CLIENT_ONLY_ERROR_TYPES.has(t)));\n/**\n * Simple unified error class for both API and SDK\n */\nexport class ShipError extends Error {\n type;\n status;\n details;\n constructor(type, message, status, details) {\n super(message);\n this.type = type;\n this.status = status;\n this.details = details;\n this.name = 'ShipError';\n }\n /** Convert to wire format */\n toResponse() {\n // Strip authentication details when they carry an `internal` telemetry\n // tag (see `ShipError.authentication` JSDoc) — these are server-side\n // diagnostics like 'jwt_missing_subject' that must not leak to clients.\n const authDetails = this.details;\n const details = this.type === ErrorType.Authentication && authDetails?.internal\n ? undefined\n : this.details;\n return {\n error: this.type,\n message: this.message,\n status: this.status,\n details\n };\n }\n /**\n * Construct a `ShipError` from an HTTP error response.\n *\n * Best-effort body parse for `{ message, error?, details? }`. Message\n * resolution: `body.message` → `body.error` → `\"<operationName> failed with\n * status <N>\"`.\n *\n * Type resolution: trusts `body.error` when it's a known server-producible\n * `ErrorType` (preserves the wire's intent — server's\n * `ShipError.validation(...)` round-trips back to `ErrorType.Validation`\n * on the client). Falls back to status-derived (401 → Authentication,\n * 403 → Forbidden, 429 → RateLimit, else → Api) for non-API responses\n * (CDN errors, intermediaries) or malformed bodies. Client-only types\n * (`Network`, `Cancelled`, `File`, `Config`) are filtered out of the\n * trusted set — a misbehaving server claiming one of those is ignored.\n *\n * `operationName` (e.g. `\"Get account\"`) is used to compose the fallback\n * message. Defaults to `\"Request\"`. Same convention as `fromFetchError`.\n *\n * Async because it reads the response body. Returns rather than throws so\n * callers can compose; most will `throw await ShipError.fromHttpResponse(...)`.\n */\n static async fromHttpResponse(response, operationName) {\n let message;\n let details;\n let bodyType;\n try {\n const contentType = response.headers.get('content-type');\n if (contentType?.includes('application/json')) {\n const json = await response.json();\n if (json && typeof json === 'object') {\n const obj = json;\n if (typeof obj.message === 'string')\n message = obj.message;\n else if (typeof obj.error === 'string')\n message = obj.error;\n details = obj.details;\n if (typeof obj.error === 'string' && SERVER_PRODUCIBLE_ERROR_TYPES.has(obj.error)) {\n bodyType = obj.error;\n }\n }\n }\n else {\n const text = await response.text();\n if (text)\n message = text;\n }\n }\n catch {\n // Body unreadable; fall through to operationName-derived message.\n }\n message = message || `${operationName || 'Request'} failed with status ${response.status}`;\n const type = bodyType ?? (response.status === 401 ? ErrorType.Authentication :\n response.status === 403 ? ErrorType.Forbidden :\n response.status === 429 ? ErrorType.RateLimit :\n ErrorType.Api);\n return new ShipError(type, message, response.status, details);\n }\n /**\n * Construct a `ShipError` from an error caught around a `fetch()` call.\n *\n * The mirror of `fromHttpResponse` for the *other* side of the HTTP error\n * story — the network layer failing (offline, CORS, abort) rather than the\n * server returning a non-OK response.\n *\n * Routing:\n * - Already a `ShipError` → returned as-is (caller's intent preserved)\n * - `AbortError` → `ShipError.cancelled(...)`\n * - `TypeError` whose message mentions \"fetch\" → `ShipError.network(...)`\n * - Any other `Error` → `ShipError(Api, ...)` (no HTTP status — fetch never reached the server)\n * - Anything else (string, undefined, etc.) → `ShipError(Api, ...)`\n *\n * The optional `operationName` is composed into the message for context:\n * `\"Get account was cancelled\"`, `\"Get account failed: ...\"`. Defaults to\n * `\"Request\"` when omitted.\n */\n static fromFetchError(cause, operationName) {\n if (isShipError(cause))\n return cause;\n const op = operationName || 'Request';\n if (cause instanceof Error) {\n if (cause.name === 'AbortError') {\n return ShipError.cancelled(`${op} was cancelled`);\n }\n if (cause instanceof TypeError && cause.message.includes('fetch')) {\n return ShipError.network(`${op} failed: ${cause.message}`, { cause });\n }\n return new ShipError(ErrorType.Api, `${op} failed: ${cause.message}`);\n }\n return new ShipError(ErrorType.Api, `${op} failed: Unknown error`);\n }\n // Factory methods. Uniform shape `(message, details?)` with two principled\n // exceptions: `notFound` composes its message from (resource, id?), and\n // `business` / `api` accept an optional status because they're the\n // multi-status fallbacks.\n static validation(message, details) {\n return new ShipError(ErrorType.Validation, message, 400, details);\n }\n static notFound(resource, id) {\n const message = id ? `${resource} ${id} not found` : `${resource} not found`;\n return new ShipError(ErrorType.NotFound, message, 404);\n }\n static forbidden(message, details) {\n return new ShipError(ErrorType.Forbidden, message, 403, details);\n }\n static rateLimit(message = \"Too many requests\", details) {\n return new ShipError(ErrorType.RateLimit, message, 429, details);\n }\n /**\n * Construct an Authentication (401) error.\n *\n * **Telemetry pattern — `details: { internal: '<tag>' }`.** When the\n * server creates an auth error with an `internal` key in `details`\n * (e.g. `{ internal: 'jwt_missing_subject' }`), `toResponse()` strips the\n * entire `details` object before serialization. This keeps the wire\n * response a clean \"Authentication failed\" while preserving granular\n * server-side telemetry (which strategy/check failed) for logs and tests.\n *\n * Use this pattern in API auth code; do not put client-visible info under\n * `internal`. Other `details` keys round-trip normally.\n */\n static authentication(message = \"Authentication required\", details) {\n return new ShipError(ErrorType.Authentication, message, 401, details);\n }\n static business(message, status = 400, details) {\n return new ShipError(ErrorType.Business, message, status, details);\n }\n static network(message, details) {\n return new ShipError(ErrorType.Network, message, undefined, details);\n }\n static cancelled(message, details) {\n return new ShipError(ErrorType.Cancelled, message, undefined, details);\n }\n static file(message, details) {\n return new ShipError(ErrorType.File, message, undefined, details);\n }\n static config(message, details) {\n return new ShipError(ErrorType.Config, message, undefined, details);\n }\n static api(message, status = 500, details) {\n return new ShipError(ErrorType.Api, message, status, details);\n }\n // Semantic-category type guards. For specific-type checks, use\n // `error.type === ErrorType.X` directly or the generic `isType(t)`.\n isClientError() {\n return ERROR_CATEGORIES.client.has(this.type);\n }\n isNetworkError() {\n return ERROR_CATEGORIES.network.has(this.type);\n }\n isAuthError() {\n return ERROR_CATEGORIES.auth.has(this.type);\n }\n isType(errorType) {\n return this.type === errorType;\n }\n}\n/**\n * Type guard to check if an unknown value is a ShipError.\n *\n * Uses structural checking instead of instanceof to handle module duplication\n * in bundled applications where multiple copies of the ShipError class may exist.\n *\n * @example\n * if (isShipError(error)) {\n * console.log(error.status, error.message);\n * }\n */\nexport function isShipError(error) {\n return (error !== null &&\n typeof error === 'object' &&\n 'name' in error &&\n error.name === 'ShipError' &&\n 'status' in error);\n}\n// =============================================================================\n// EXTENSION BLOCKLIST\n// =============================================================================\n/**\n * Blocked file extensions — files that cannot be uploaded.\n *\n * We accept any file type by default and derive Content-Type from the\n * extension at serve time (via mime-db in the API worker). Unknown extensions\n * are served as `application/octet-stream` with `X-Content-Type-Options: nosniff`.\n *\n * The blocklist targets file types that pose direct security risks when hosted:\n * executables, disk images, malware vectors, dangerous scripts, and shortcuts.\n */\nexport const BLOCKED_EXTENSIONS = new Set([\n // Executables\n 'exe', 'msi', 'dll', 'scr', 'bat', 'cmd', 'com', 'pif', 'app', 'deb', 'rpm',\n // Installers\n 'pkg', 'mpkg',\n // Disk images\n 'dmg', 'iso', 'img',\n // Malware vectors\n 'cab', 'cpl', 'chm',\n // Dangerous scripts\n 'ps1', 'vbs', 'vbe', 'ws', 'wsf', 'wsc', 'wsh', 'reg',\n // Java\n 'jar', 'jnlp',\n // Mobile/browser packages\n 'apk', 'crx',\n // Shortcut/link\n 'lnk', 'inf', 'hta',\n]);\n/**\n * Check if a filename has a blocked extension.\n * Extracts the extension from the filename and checks against the blocklist.\n * Case-insensitive. Returns false for files without extensions.\n *\n * @example\n * isBlockedExtension('virus.exe') // true\n * isBlockedExtension('app.dmg') // true\n * isBlockedExtension('style.css') // false\n * isBlockedExtension('data.custom') // false\n * isBlockedExtension('README') // false\n */\nexport function isBlockedExtension(filename) {\n const dotIndex = filename.lastIndexOf('.');\n if (dotIndex === -1 || dotIndex === filename.length - 1)\n return false;\n const ext = filename.slice(dotIndex + 1).toLowerCase();\n return BLOCKED_EXTENSIONS.has(ext);\n}\n// =============================================================================\n// FILENAME CHARACTER VALIDATION\n// =============================================================================\n/**\n * Characters that are unsafe in filenames for static hosting.\n *\n * Blocks only characters that genuinely break the upload→serve round-trip:\n * - # ? % URL round-trip breakers (fragment, query, encoding ambiguity)\n * - \\ Path separator confusion (upload splits on backslash)\n * - < > \" XSS vectors with zero legitimate use in filenames\n * - \\x00-\\x1f \\x7f Control characters (header injection, display corruption)\n *\n * Everything else is allowed — browser percent-encodes, Worker decodes, R2 matches.\n */\nexport const UNSAFE_FILENAME_CHARS = /[\\x00-\\x1f\\x7f#?%\\\\<>\"]/;\n/**\n * Check if a filename contains unsafe characters.\n *\n * @example\n * hasUnsafeChars('saved_resource(1).html') // false — parentheses are safe\n * hasUnsafeChars('page[slug].js') // false — brackets are safe\n * hasUnsafeChars('file#anchor.html') // true — # breaks URL resolution\n * hasUnsafeChars('file<tag>.html') // true — < is an XSS vector\n */\nexport function hasUnsafeChars(filename) {\n return UNSAFE_FILENAME_CHARS.test(filename);\n}\n// =============================================================================\n// UNBUILT PROJECT MARKERS\n// =============================================================================\n/**\n * Path segment names that indicate an unbuilt project was uploaded instead of build output.\n * Used for early detection in CLI, browser, and server validation.\n */\nexport const UNBUILT_PROJECT_MARKERS = new Set([\n 'node_modules',\n 'package.json',\n]);\n/**\n * Check if a file path contains an unbuilt project marker.\n *\n * @example\n * hasUnbuiltMarker('node_modules/react/index.js') // true\n * hasUnbuiltMarker('package.json') // true\n * hasUnbuiltMarker('dist/index.html') // false\n */\nexport function hasUnbuiltMarker(filePath) {\n const segments = filePath.replace(/\\\\/g, '/').split('/').filter(Boolean);\n return segments.some(s => UNBUILT_PROJECT_MARKERS.has(s));\n}\n/**\n * Shape constants for API keys (`ship-{64 hex chars}`).\n * Single source of truth used by validation utilities and auth middleware.\n */\nexport const API_KEY = {\n /** Prefix that identifies an API key. */\n PREFIX: 'ship-',\n /** Number of hex characters following the prefix. */\n HEX_LENGTH: 64,\n /** Total length of an API key including prefix (`PREFIX.length + HEX_LENGTH = 69`). */\n TOTAL_LENGTH: 69,\n /** Number of trailing characters used to display a redacted hint (e.g. last 4). */\n HINT_LENGTH: 4,\n};\n/**\n * Shape constants for deploy tokens (`token-{64 hex chars}`).\n * Single source of truth used by validation utilities and auth middleware.\n */\nexport const DEPLOY_TOKEN = {\n /** Prefix that identifies a deploy token. */\n PREFIX: 'token-',\n /** Number of hex characters following the prefix. */\n HEX_LENGTH: 64,\n /** Total length of a deploy token including prefix (`PREFIX.length + HEX_LENGTH = 70`). */\n TOTAL_LENGTH: 70,\n};\n// Authentication Method Constants\nexport const AuthMethod = {\n JWT: 'jwt',\n API_KEY: 'apiKey',\n TOKEN: 'token',\n WEBHOOK: 'webhook',\n SYSTEM: 'system'\n};\n// Deployment Configuration\nexport const DEPLOYMENT_CONFIG_FILENAME = 'ship.json';\n/** Default ship.json config for SPA routing. Single source of truth — used by both API and SDK. */\nexport const SPA_DEFAULT_CONFIG = { rewrites: [{ source: '/(.*)', destination: '/index.html' }] };\n// =============================================================================\n// VALIDATION UTILITIES\n// =============================================================================\n/**\n * Validate API key format\n */\nexport function validateApiKey(apiKey) {\n if (!apiKey.startsWith(API_KEY.PREFIX)) {\n throw ShipError.validation(`API key must start with \"${API_KEY.PREFIX}\"`);\n }\n if (apiKey.length !== API_KEY.TOTAL_LENGTH) {\n throw ShipError.validation(`API key must be ${API_KEY.TOTAL_LENGTH} characters total (${API_KEY.PREFIX} + ${API_KEY.HEX_LENGTH} hex chars)`);\n }\n const hexPart = apiKey.slice(API_KEY.PREFIX.length);\n if (!/^[a-f0-9]{64}$/i.test(hexPart)) {\n throw ShipError.validation(`API key must contain ${API_KEY.HEX_LENGTH} hexadecimal characters after \"${API_KEY.PREFIX}\" prefix`);\n }\n}\n/**\n * Validate deploy token format\n */\nexport function validateDeployToken(deployToken) {\n if (!deployToken.startsWith(DEPLOY_TOKEN.PREFIX)) {\n throw ShipError.validation(`Deploy token must start with \"${DEPLOY_TOKEN.PREFIX}\"`);\n }\n if (deployToken.length !== DEPLOY_TOKEN.TOTAL_LENGTH) {\n throw ShipError.validation(`Deploy token must be ${DEPLOY_TOKEN.TOTAL_LENGTH} characters total (${DEPLOY_TOKEN.PREFIX} + ${DEPLOY_TOKEN.HEX_LENGTH} hex chars)`);\n }\n const hexPart = deployToken.slice(DEPLOY_TOKEN.PREFIX.length);\n if (!/^[a-f0-9]{64}$/i.test(hexPart)) {\n throw ShipError.validation(`Deploy token must contain ${DEPLOY_TOKEN.HEX_LENGTH} hexadecimal characters after \"${DEPLOY_TOKEN.PREFIX}\" prefix`);\n }\n}\n/**\n * Validate API URL format\n */\nexport function validateApiUrl(apiUrl) {\n try {\n const url = new URL(apiUrl);\n if (!['http:', 'https:'].includes(url.protocol)) {\n throw ShipError.validation('API URL must use http:// or https:// protocol');\n }\n if (url.pathname !== '/' && url.pathname !== '') {\n throw ShipError.validation('API URL must not contain a path');\n }\n if (url.search || url.hash) {\n throw ShipError.validation('API URL must not contain query parameters or fragments');\n }\n }\n catch (error) {\n if (isShipError(error)) {\n throw error;\n }\n throw ShipError.validation('API URL must be a valid URL');\n }\n}\n/**\n * Check if a string matches the deployment identifier pattern (word-word-alphanumeric7).\n * Example: \"happy-cat-abc1234.shipstatic.com\"\n */\nexport function isDeployment(input) {\n return /^[a-z]+-[a-z]+-[a-z0-9]{7}(\\.[a-z0-9.-]+)?$/i.test(input);\n}\n// =============================================================================\n// PLATFORM CONSTANTS\n// =============================================================================\n/** Default API URL if not otherwise configured. */\nexport const DEFAULT_API = 'https://api.shipstatic.com';\n// =============================================================================\n// FILE UPLOAD TYPES\n// =============================================================================\n/**\n * File status constants for validation state tracking\n */\nexport const FileValidationStatus = {\n /** File is pending validation */\n PENDING: 'pending',\n /** File failed during processing (before validation) */\n PROCESSING_ERROR: 'processing_error',\n /** File was excluded by validation warning (not an error) */\n EXCLUDED: 'excluded',\n /** File failed validation (blocks deployment) */\n VALIDATION_FAILED: 'validation_failed',\n /** File passed validation and is ready for deployment */\n READY: 'ready',\n};\n// =============================================================================\n// DOMAIN UTILITIES\n// =============================================================================\n/**\n * Check if a domain is a platform domain (subdomain of our platform).\n * Platform domains are free and don't require DNS verification.\n *\n * @example isPlatformDomain(\"www.shipstatic.com\", \"shipstatic.com\") → true\n * @example isPlatformDomain(\"example.com\", \"shipstatic.com\") → false\n */\nexport function isPlatformDomain(domain, platformDomain) {\n return domain.endsWith(`.${platformDomain}`);\n}\n/**\n * Check if a domain is a custom domain (not a platform subdomain).\n * Custom domains are billable and require DNS verification.\n *\n * @example isCustomDomain(\"example.com\", \"shipstatic.com\") → true\n * @example isCustomDomain(\"www.shipstatic.com\", \"shipstatic.com\") → false\n */\nexport function isCustomDomain(domain, platformDomain) {\n return !isPlatformDomain(domain, platformDomain);\n}\n/**\n * Extract subdomain from a platform domain.\n * Returns null if not a platform domain.\n *\n * @example extractSubdomain(\"www.shipstatic.com\", \"shipstatic.com\") → \"www\"\n * @example extractSubdomain(\"example.com\", \"shipstatic.com\") → null\n */\nexport function extractSubdomain(domain, platformDomain) {\n if (!isPlatformDomain(domain, platformDomain)) {\n return null;\n }\n return domain.slice(0, -(platformDomain.length + 1)); // +1 for the dot\n}\n/**\n * Generate HTTPS URL for a deployment hostname.\n */\nexport function generateDeploymentUrl(deployment) {\n return `https://${deployment}`;\n}\n/**\n * Generate HTTPS URL for a domain.\n */\nexport function generateDomainUrl(domain) {\n return `https://${domain}`;\n}\n// =============================================================================\n// LABEL UTILITIES\n// =============================================================================\n/**\n * Label validation constraints shared across UI and API.\n * These rules define the single source of truth for label validation.\n */\nexport const LABEL_CONSTRAINTS = {\n /** Minimum label length in characters */\n MIN_LENGTH: 3,\n /** Maximum label length in characters (concise labels, matches Stack Overflow's original limit) */\n MAX_LENGTH: 25,\n /** Maximum number of labels allowed per resource */\n MAX_COUNT: 10,\n /** Allowed separator characters between label segments */\n SEPARATORS: '._-',\n};\n/**\n * Label validation pattern.\n * Must start and end with alphanumeric (a-z, 0-9).\n * Can contain separators (. _ -) between segments, but not consecutive.\n *\n * Valid examples: 'production', 'v1.2.3', 'api_v2', 'us-east-1'\n * Invalid examples: 'ab' (too short), '-prod' (starts with separator), 'foo--bar' (consecutive separators)\n */\nexport const LABEL_PATTERN = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;\n/**\n * Serialize labels array to JSON string for database storage.\n * Returns null for empty or undefined arrays.\n *\n * @example serializeLabels(['web', 'production']) → '[\"web\",\"production\"]'\n * @example serializeLabels([]) → null\n * @example serializeLabels(undefined) → null\n */\nexport function serializeLabels(labels) {\n if (!labels || labels.length === 0)\n return null;\n return JSON.stringify(labels);\n}\n/**\n * Deserialize labels from JSON string to array.\n * Always returns an array — empty array for null/empty/invalid input.\n *\n * @example deserializeLabels('[\"web\",\"production\"]') → ['web', 'production']\n * @example deserializeLabels(null) → []\n * @example deserializeLabels('') → []\n */\nexport function deserializeLabels(labelsJson) {\n if (!labelsJson)\n return [];\n try {\n const parsed = JSON.parse(labelsJson);\n return Array.isArray(parsed) ? parsed : [];\n }\n catch {\n return [];\n }\n}\n// =============================================================================\n// PASSWORD UTILITIES\n// =============================================================================\n/**\n * Length constraints for the optional deployment password\n * (`DeploymentUploadOptions.password`). Single source of truth shared across\n * platform consumers.\n */\nexport const PASSWORD_CONSTRAINTS = {\n /** Minimum password length in characters */\n MIN_LENGTH: 6,\n /** Maximum password length in characters */\n MAX_LENGTH: 128,\n};\n","/**\n * @file Environment detection utilities for the Ship SDK.\n * Helps in determining whether the SDK is running in a Node.js, browser, or unknown environment.\n */\n\n/**\n * Represents the detected or simulated JavaScript execution environment.\n */\nexport type ExecutionEnvironment = 'browser' | 'node' | 'unknown';\n\n/** @internal Environment override for testing. */\nlet _testEnvironment: ExecutionEnvironment | null = null;\n\n/**\n * **FOR TESTING PURPOSES ONLY.**\n *\n * Allows tests to override the detected environment, forcing the SDK to behave\n * as if it's running in the specified environment.\n *\n * @param env - The environment to simulate ('node', 'browser', 'unknown'),\n * or `null` to clear the override and revert to actual environment detection.\n * @internal\n */\nexport function __setTestEnvironment(env: ExecutionEnvironment | null): void {\n _testEnvironment = env;\n}\n\n/**\n * Detects the actual JavaScript execution environment (Node.js, browser, or unknown)\n * by checking for characteristic global objects.\n * @returns The detected environment as {@link ExecutionEnvironment}.\n * @internal\n */\nfunction detectEnvironment(): ExecutionEnvironment {\n // Check for Node.js environment\n if (typeof process !== 'undefined' && process.versions && process.versions.node) {\n return 'node';\n }\n\n // Check for Browser environment (including Web Workers)\n if (typeof window !== 'undefined' || typeof self !== 'undefined') {\n return 'browser';\n }\n\n return 'unknown';\n}\n\n/**\n * Gets the current effective execution environment.\n *\n * This function first checks if a test environment override is active via {@link __setTestEnvironment}.\n * If not, it detects the actual environment (Node.js, browser, or unknown).\n *\n * @returns The current execution environment: 'browser', 'node', or 'unknown'.\n * @public\n */\nexport function getENV(): ExecutionEnvironment {\n // Return test override if set\n if (_testEnvironment) {\n return _testEnvironment;\n }\n \n // Detect actual environment\n return detectEnvironment();\n}\n","/**\n * @file Simplified MD5 calculation utility with separate environment handlers.\n */\nimport { getENV } from './env.js';\nimport { ShipError } from '@shipstatic/types';\n\nexport interface MD5Result {\n md5: string;\n}\n\n/**\n * Browser-specific MD5 calculation for Blob/File objects\n */\nasync function calculateMD5Browser(blob: Blob): Promise<MD5Result> {\n const SparkMD5 = (await import('spark-md5')).default;\n \n return new Promise((resolve, reject) => {\n const chunkSize = 2097152; // 2MB chunks\n const chunks = Math.ceil(blob.size / chunkSize);\n let currentChunk = 0;\n const spark = new SparkMD5.ArrayBuffer();\n const fileReader = new FileReader();\n\n const loadNext = () => {\n const start = currentChunk * chunkSize;\n const end = Math.min(start + chunkSize, blob.size);\n fileReader.readAsArrayBuffer(blob.slice(start, end));\n };\n\n fileReader.onload = (e) => {\n const result = e.target?.result as ArrayBuffer;\n if (!result) {\n reject(ShipError.business('Failed to read file chunk'));\n return;\n }\n \n spark.append(result);\n currentChunk++;\n \n if (currentChunk < chunks) {\n loadNext();\n } else {\n resolve({ md5: spark.end() });\n }\n };\n\n fileReader.onerror = () => {\n reject(ShipError.business('Failed to calculate MD5: FileReader error'));\n };\n\n loadNext();\n });\n}\n\n/**\n * Node.js-specific MD5 calculation for Buffer or file path\n */\nasync function calculateMD5Node(input: Buffer | string): Promise<MD5Result> {\n const crypto = await import('crypto');\n \n if (Buffer.isBuffer(input)) {\n const hash = crypto.createHash('md5');\n hash.update(input);\n return { md5: hash.digest('hex') };\n }\n \n // Handle file path\n const fs = await import('fs');\n return new Promise((resolve, reject) => {\n const hash = crypto.createHash('md5');\n const stream = fs.createReadStream(input);\n \n stream.on('error', err => \n reject(ShipError.business(`Failed to read file for MD5: ${err.message}`))\n );\n stream.on('data', chunk => hash.update(chunk));\n stream.on('end', () => resolve({ md5: hash.digest('hex') }));\n });\n}\n\n/**\n * Unified MD5 calculation that delegates to environment-specific handlers\n */\nexport async function calculateMD5(input: Blob | Buffer | string): Promise<MD5Result> {\n const env = getENV();\n \n if (env === 'browser') {\n if (!(input instanceof Blob)) {\n throw ShipError.business('Invalid input for browser MD5 calculation: Expected Blob or File.');\n }\n return calculateMD5Browser(input);\n }\n \n if (env === 'node') {\n if (!(Buffer.isBuffer(input) || typeof input === 'string')) {\n throw ShipError.business('Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.');\n }\n return calculateMD5Node(input);\n }\n \n throw ShipError.business('Unknown or unsupported execution environment for MD5 calculation.');\n}\n","/**\n * @file Utility for filtering out junk files and directories from file paths\n * \n * This module provides functionality to filter out common system junk files and directories\n * from a list of file paths. It uses the 'junk' package to identify junk filenames and\n * a custom list to filter out common junk directories.\n */\nimport { isJunk } from 'junk';\nimport { ShipError, hasUnbuiltMarker } from '@shipstatic/types';\n\n/**\n * List of directory names considered as junk\n * \n * Files within these directories (at any level in the path hierarchy) will be excluded.\n * The comparison is case-insensitive for cross-platform compatibility.\n * \n * @internal\n */\nexport const JUNK_DIRECTORIES = [\n '__MACOSX',\n '.Trashes',\n '.fseventsd',\n '.Spotlight-V100',\n] as const;\n\n/**\n * Filters an array of file paths, removing those considered junk\n *\n * Throws if any path contains an unbuilt project marker (e.g. `node_modules`, `package.json`).\n * This check runs first because the dot-file filter below would strip paths like\n * `node_modules/.pnpm/...`, destroying the evidence.\n *\n * A path is filtered out if any of these conditions are met:\n * 1. The basename is identified as junk by the 'junk' package (e.g., .DS_Store, Thumbs.db)\n * 2. Any path segment starts with a dot (e.g., .env, .git, .htaccess)\n * Exception: `.well-known` is allowed (RFC 8615 — ACME, security.txt, app links)\n * 3. Any path segment exceeds 255 characters (filesystem limit)\n * 4. Any directory segment in the path matches an entry in JUNK_DIRECTORIES (case-insensitive)\n *\n * All path separators are normalized to forward slashes for consistent cross-platform behavior.\n *\n * Dot files are filtered for security — they typically contain sensitive configuration\n * (.env, .git) or are not meant to be served publicly. This matches server-side filtering.\n *\n * @param filePaths - An array of file path strings to filter\n * @param options - Optional settings\n * @param options.allowUnbuilt - When true, skip the unbuilt project marker check (for server-processed uploads)\n * @returns A new array containing only non-junk file paths\n * @throws {ShipError} If any path contains an unbuilt project marker (unless allowUnbuilt is true)\n *\n * @example\n * ```typescript\n * import { filterJunk } from '@shipstatic/ship';\n *\n * // Filter an array of file paths\n * const paths = ['index.html', '.DS_Store', '.gitattributes', '__MACOSX/file.txt', 'app.js'];\n * const clean = filterJunk(paths);\n * // Result: ['index.html', 'app.js']\n * ```\n *\n * @example\n * ```typescript\n * // Use with browser File objects\n * import { filterJunk } from '@shipstatic/ship';\n *\n * const files: File[] = [...]; // From input or drag-drop\n *\n * // Extract paths from File objects\n * const filePaths = files.map(f => f.webkitRelativePath || f.name);\n *\n * // Filter out junk paths\n * const validPaths = new Set(filterJunk(filePaths));\n *\n * // Filter the original File array\n * const validFiles = files.filter(f =>\n * validPaths.has(f.webkitRelativePath || f.name)\n * );\n * ```\n */\nexport function filterJunk(\n filePaths: string[],\n options?: { allowUnbuilt?: boolean }\n): string[] {\n if (!filePaths || filePaths.length === 0) {\n return [];\n }\n\n // Reject unbuilt projects before the dot-file filter removes evidence.\n // pnpm stores files under node_modules/.pnpm/ — the dot-file filter below\n // strips .pnpm/ paths, destroying the only signal that this is an unbuilt project.\n if (!options?.allowUnbuilt) {\n const marker = filePaths.find(p => p && hasUnbuiltMarker(p));\n if (marker) {\n throw ShipError.business(\n 'Unbuilt project detected — deploy your build output (dist/, build/, out/), not the project folder'\n );\n }\n }\n\n return filePaths.filter(filePath => {\n if (!filePath) {\n return false; // Exclude null or undefined paths\n }\n\n // Normalize path separators to forward slashes and split into segments\n const parts = filePath.replace(/\\\\/g, '/').split('/').filter(Boolean);\n if (parts.length === 0) return true;\n\n // Check if the basename is a junk file (using junk package)\n const basename = parts[parts.length - 1];\n if (isJunk(basename)) {\n return false;\n }\n\n // Filter out dot files and directories (security: prevents .env, .git, etc.)\n // .well-known is not junk — it's a standard directory (RFC 8615)\n // Path position constraints enforced at upload (buildFileKey) and serving (isBlockedDotFile)\n for (const part of parts) {\n if (part === '.well-known') continue;\n if (part.startsWith('.') || part.length > 255) {\n return false;\n }\n }\n\n // Check if any directory segment is in our junk directories list\n const directorySegments = parts.slice(0, -1);\n for (const segment of directorySegments) {\n if (JUNK_DIRECTORIES.some(junkDir =>\n segment.toLowerCase() === junkDir.toLowerCase())) {\n return false;\n }\n }\n\n return true;\n });\n}\n","/**\n * @file Path helper utilities that work in both browser and Node.js environments.\n * Provides environment-agnostic path manipulation functions.\n */\n\n/**\n * Finds the common parent directory from an array of directory paths.\n * Simple, unified implementation for flattenDirs functionality.\n * \n * @param dirPaths - Array of directory paths (not file paths - directories containing the files)\n * @returns The common parent directory path, or empty string if none found\n */\nexport function findCommonParent(dirPaths: string[]): string {\n if (!dirPaths || dirPaths.length === 0) return '';\n \n const normalizedPaths = dirPaths\n .filter(p => p && typeof p === 'string')\n .map(p => p.replace(/\\\\/g, '/'));\n \n if (normalizedPaths.length === 0) return '';\n if (normalizedPaths.length === 1) return normalizedPaths[0];\n\n const pathSegments = normalizedPaths.map(p => p.split('/').filter(Boolean));\n const commonSegments = [];\n const minLength = Math.min(...pathSegments.map(p => p.length));\n \n for (let i = 0; i < minLength; i++) {\n const segment = pathSegments[0][i];\n if (pathSegments.every(segments => segments[i] === segment)) {\n commonSegments.push(segment);\n } else {\n break;\n }\n }\n \n return commonSegments.join('/');\n}\n\n\n\n/**\n * Converts backslashes to forward slashes for cross-platform compatibility.\n * Does not remove leading slashes (preserves absolute paths).\n * @param path - The path to normalize\n * @returns Path with forward slashes\n */\nexport function normalizeSlashes(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n\n/**\n * Normalizes a path for web usage by converting backslashes to forward slashes\n * and removing leading slashes.\n * @param path - The path to normalize\n * @returns Normalized path suitable for web deployment\n */\nexport function normalizeWebPath(path: string): string {\n return path.replace(/\\\\/g, '/').replace(/\\/+/g, '/').replace(/^\\/+/, '');\n}\n\n","/**\n * @file Deploy path optimization - the core logic that makes Ship deployments clean and intuitive.\n * Automatically strips common parent directories to create clean deployment URLs.\n */\n\nimport { normalizeWebPath } from './path.js';\n\n/**\n * Represents a file ready for deployment with its optimized path\n */\nexport interface DeployFile {\n /** The clean deployment path (e.g., \"assets/style.css\") */\n path: string;\n /** Original filename */\n name: string;\n}\n\n/**\n * Core path optimization logic.\n * Transforms messy local paths into clean deployment paths.\n * \n * @example\n * Input: [\"dist/index.html\", \"dist/assets/app.js\"]\n * Output: [\"index.html\", \"assets/app.js\"]\n * \n * @param filePaths - Raw file paths from the local filesystem\n * @param options - Path processing options\n */\nexport function optimizeDeployPaths(\n filePaths: string[], \n options: { flatten?: boolean } = {}\n): DeployFile[] {\n // When flattening is disabled, keep original structure\n if (options.flatten === false) {\n return filePaths.map(path => ({\n path: normalizeWebPath(path),\n name: extractFileName(path)\n }));\n }\n\n // Find the common directory prefix to strip\n const commonPrefix = findCommonDirectory(filePaths);\n \n return filePaths.map(filePath => {\n let deployPath = normalizeWebPath(filePath);\n \n // Strip the common prefix to create clean deployment paths\n if (commonPrefix) {\n const prefixToRemove = commonPrefix.endsWith('/') ? commonPrefix : `${commonPrefix}/`;\n if (deployPath.startsWith(prefixToRemove)) {\n deployPath = deployPath.substring(prefixToRemove.length);\n }\n }\n \n // Fallback to filename if path becomes empty\n if (!deployPath) {\n deployPath = extractFileName(filePath);\n }\n \n return {\n path: deployPath,\n name: extractFileName(filePath)\n };\n });\n}\n\n/**\n * Finds the common directory shared by all file paths.\n * This is what gets stripped to create clean deployment URLs.\n * \n * @example\n * [\"dist/index.html\", \"dist/assets/app.js\"] → \"dist\"\n * [\"src/components/A.tsx\", \"src/utils/B.ts\"] → \"src\"\n * [\"file1.txt\", \"file2.txt\", \"subdir/file3.txt\"] → \"\" (no common directory)\n */\nfunction findCommonDirectory(filePaths: string[]): string {\n if (!filePaths.length) return '';\n \n // Normalize all paths first\n const normalizedPaths = filePaths.map(path => normalizeWebPath(path));\n \n // Find the common prefix among all file paths (not just directories)\n const pathSegments = normalizedPaths.map(path => path.split('/'));\n const commonSegments: string[] = [];\n const minLength = Math.min(...pathSegments.map(segments => segments.length));\n \n // Check each segment level to find the longest common prefix\n for (let i = 0; i < minLength - 1; i++) { // -1 because we don't want to include the filename\n const segment = pathSegments[0][i];\n if (pathSegments.every(segments => segments[i] === segment)) {\n commonSegments.push(segment);\n } else {\n break;\n }\n }\n \n return commonSegments.join('/');\n}\n\n/**\n * Extracts just the filename from a file path\n */\nfunction extractFileName(path: string): string {\n return path.split(/[/\\\\]/).pop() || path;\n}","/**\n * @file File validation utilities for Ship SDK\n * Provides client-side validation for file uploads before deployment\n */\n\nimport type {\n PlatformLimits,\n FileValidationResult,\n ValidatableFile,\n ValidationIssue,\n FileValidationStatusType\n} from '@shipstatic/types';\nimport {\n FileValidationStatus as FILE_VALIDATION_STATUS,\n isBlockedExtension,\n hasUnbuiltMarker,\n hasUnsafeChars,\n} from '@shipstatic/types';\n\nexport { FILE_VALIDATION_STATUS };\n\n/**\n * Format file size to human-readable string\n */\nexport function formatFileSize(bytes: number, decimals: number = 1): string {\n if (bytes === 0) return '0 Bytes';\n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + ' ' + sizes[i];\n}\n\n/**\n * Validate filename for deployment safety\n *\n * Blocks only characters that genuinely break the upload→serve round-trip:\n * - # ? % URL round-trip breakers (fragment, query, encoding ambiguity)\n * - \\ Path separator confusion (buildFileKey splits on backslash)\n * - < > \" XSS vectors with zero legitimate use in filenames\n * - \\x00-\\x1f \\x7f Control characters (header injection, display corruption)\n *\n * Everything else is allowed — browser percent-encodes, Worker decodes, R2 matches.\n *\n * Additional checks: path traversal, reserved names, leading/trailing dots or spaces.\n */\nexport function validateFileName(filename: string): { valid: boolean; reason?: string } {\n if (hasUnsafeChars(filename)) {\n return { valid: false, reason: 'File name contains unsafe characters' };\n }\n\n if (filename.startsWith(' ') || filename.endsWith(' ')) {\n return { valid: false, reason: 'File name cannot start/end with spaces' };\n }\n\n if (filename.endsWith('.')) {\n return { valid: false, reason: 'File name cannot end with dots' };\n }\n\n const reservedNames = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\\.|$)/i;\n const nameWithoutPath = filename.split('/').pop() || filename;\n if (reservedNames.test(nameWithoutPath)) {\n return { valid: false, reason: 'File name uses a reserved system name' };\n }\n\n if (filename.includes('..')) {\n return { valid: false, reason: 'File name contains path traversal pattern' };\n }\n\n return { valid: true };\n}\n\n/**\n * Validate files against configuration limits with severity-based reporting\n *\n * Validation categorizes issues by severity:\n * - **Errors**: Block deployment (file too large, blocked extension, etc.)\n * - **Warnings**: Exclude files but allow deployment (empty files, etc.)\n *\n * @param files - Array of files to validate\n * @param config - Validation configuration from ship.getLimits()\n * @returns Validation result with errors and warnings\n *\n * @example\n * ```typescript\n * const config = await ship.getLimits();\n * const result = validateFiles(files, config);\n *\n * if (!result.canDeploy) {\n * // Has errors - deployment blocked\n * console.error('Deployment blocked:', result.errors);\n * } else if (result.warnings.length > 0) {\n * // Has warnings - deployment proceeds, some files excluded\n * console.warn('Files excluded:', result.warnings);\n * await ship.deploy(result.validFiles);\n * } else {\n * // All files valid\n * await ship.deploy(result.validFiles);\n * }\n * ```\n */\nexport function validateFiles<T extends ValidatableFile>(\n files: T[],\n config: PlatformLimits\n): FileValidationResult<T> {\n const errors: ValidationIssue[] = [];\n const warnings: ValidationIssue[] = [];\n let fileStatuses: T[] = []; // Use 'let' for atomic enforcement later\n\n // Check at least 1 file required\n if (files.length === 0) {\n const issue: ValidationIssue = {\n file: '(no files)',\n message: 'At least one file must be provided'\n };\n errors.push(issue);\n\n return {\n files: [],\n validFiles: [],\n errors,\n warnings: [],\n canDeploy: false,\n };\n }\n\n // Check for unbuilt project markers (node_modules/, etc.)\n for (const file of files) {\n if (hasUnbuiltMarker(file.name)) {\n errors.push({\n file: file.name,\n message: `Unbuilt project detected — deploy your build output (dist/, build/, out/), not the project folder`\n });\n return {\n files: files.map(f => ({\n ...f,\n status: FILE_VALIDATION_STATUS.VALIDATION_FAILED,\n statusMessage: 'Unbuilt project detected'\n })),\n validFiles: [],\n errors,\n warnings: [],\n canDeploy: false\n };\n }\n }\n\n // Check file count limit\n if (files.length > config.maxFilesCount) {\n const issue: ValidationIssue = {\n file: `(${files.length} files)`,\n message: `File count (${files.length}) exceeds limit of ${config.maxFilesCount}`\n };\n errors.push(issue);\n\n return {\n files: files.map(f => ({\n ...f,\n status: FILE_VALIDATION_STATUS.VALIDATION_FAILED,\n statusMessage: issue.message,\n })),\n validFiles: [],\n errors,\n warnings: [],\n canDeploy: false,\n };\n }\n\n // Validate each file\n let totalSize = 0;\n\n for (const file of files) {\n let fileStatus: FileValidationStatusType = FILE_VALIDATION_STATUS.READY;\n let statusMessage = 'Ready for upload';\n\n // Pre-compute filename validation\n const nameValidation = file.name ? validateFileName(file.name) : { valid: false, reason: 'File name cannot be empty' };\n\n // Check for processing errors\n if (file.status === FILE_VALIDATION_STATUS.PROCESSING_ERROR) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = file.statusMessage || 'File failed during processing';\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n\n // EMPTY FILE - Warning (not error)\n else if (file.size === 0) {\n fileStatus = FILE_VALIDATION_STATUS.EXCLUDED;\n statusMessage = 'File is empty (0 bytes) and cannot be deployed due to storage limitations';\n warnings.push({\n file: file.name,\n message: statusMessage\n });\n // Skip other validations for excluded files\n fileStatuses.push({\n ...file,\n status: fileStatus,\n statusMessage,\n });\n continue;\n }\n\n // Negative file size - Error\n else if (file.size < 0) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = 'File size must be positive';\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n\n // File name validation\n else if (!file.name || file.name.trim().length === 0) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = 'File name cannot be empty';\n errors.push({\n file: file.name || '(empty)',\n message: statusMessage\n });\n }\n else if (file.name.includes('\\0')) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = 'File name contains invalid characters (null byte)';\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n else if (!nameValidation.valid) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = nameValidation.reason || 'Invalid file name';\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n\n // Blocked extension check\n else if (isBlockedExtension(file.name)) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = `File extension not allowed: \"${file.name}\"`;\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n\n // File size validation\n else if (file.size > config.maxFileSize) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = `File size (${formatFileSize(file.size)}) exceeds limit of ${formatFileSize(config.maxFileSize)}`;\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n\n // Total size validation\n else {\n totalSize += file.size;\n if (totalSize > config.maxTotalSize) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = `Total size would exceed limit of ${formatFileSize(config.maxTotalSize)}`;\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n }\n\n fileStatuses.push({\n ...file,\n status: fileStatus,\n statusMessage,\n });\n }\n\n // ATOMIC ENFORCEMENT: Two-phase validation for optimal UX + atomic semantics\n // Phase 1 (above): Validate files individually to collect ALL errors\n // Phase 2 (below): Mark all files as failed if any errors exist\n //\n // Why two phases? We validate individually for better UX (users see all problems\n // at once and can fix everything in one pass), then enforce atomicity to maintain\n // deployment transaction semantics (all-or-nothing).\n if (errors.length > 0) {\n fileStatuses = fileStatuses.map(file => {\n // Keep EXCLUDED files as-is (they're warnings, not errors)\n if (file.status === FILE_VALIDATION_STATUS.EXCLUDED) {\n return file;\n }\n\n // Mark ALL other files as VALIDATION_FAILED (atomic deployment)\n return {\n ...file,\n status: FILE_VALIDATION_STATUS.VALIDATION_FAILED,\n statusMessage: file.status === FILE_VALIDATION_STATUS.VALIDATION_FAILED\n ? file.statusMessage // Keep original error message for the file that actually failed\n : 'Deployment failed due to validation errors in bundle'\n };\n });\n }\n\n // Build atomic result\n // validFiles is empty if ANY errors exist (all-or-nothing)\n const validFiles = errors.length === 0\n ? fileStatuses.filter(f => f.status === FILE_VALIDATION_STATUS.READY)\n : [];\n const canDeploy = errors.length === 0;\n\n return {\n files: fileStatuses,\n validFiles,\n errors,\n warnings,\n canDeploy,\n };\n}\n\n/**\n * Get only the valid files from validation results\n */\nexport function getValidFiles<T extends ValidatableFile>(files: T[]): T[] {\n return files.filter(f => f.status === FILE_VALIDATION_STATUS.READY);\n}\n\n/**\n * Check if all valid files have required properties for upload\n * (Can be extended to check for MD5, etc.)\n */\nexport function allValidFilesReady<T extends ValidatableFile>(files: T[]): boolean {\n const validFiles = getValidFiles(files);\n return validFiles.length > 0;\n}\n","/**\n * @file Shared security validation for the deploy pipeline.\n * Used by both Node.js and browser file processing pipelines.\n */\nimport { ShipError, isBlockedExtension } from '@shipstatic/types';\nimport { validateFileName } from './file-validation.js';\n\n/**\n * Validate a deploy path for security concerns.\n * Rejects paths containing path traversal patterns or null bytes.\n *\n * Checks for:\n * - Null bytes (\\0) — path injection\n * - /../ — directory traversal within path\n * - ../ at start — upward traversal\n * - /.. at end — trailing traversal\n *\n * Does NOT reject double dots in filenames (e.g., \"foo..bar.txt\" is safe).\n *\n * @param deployPath - The deployment path to validate\n * @param sourceIdentifier - Human-readable identifier for error messages\n * @throws {ShipError} If the path contains unsafe patterns\n */\nexport function validateDeployPath(deployPath: string, sourceIdentifier: string): void {\n if (\n deployPath.includes('\\0') ||\n deployPath.includes('/../') ||\n deployPath.startsWith('../') ||\n deployPath.endsWith('/..')\n ) {\n throw ShipError.business(`Security error: Unsafe file path \"${deployPath}\" for file: ${sourceIdentifier}`);\n }\n}\n\n/**\n * Validate a deploy file's name and extension.\n * Rejects unsafe filenames (shell/URL-dangerous chars, reserved names)\n * and blocked file extensions (.exe, .msi, .dll, etc.).\n *\n * @param deployPath - The deployment path to validate\n * @param sourceIdentifier - Human-readable identifier for error messages\n * @throws {ShipError} If the filename is unsafe or extension is blocked\n */\nexport function validateDeployFile(deployPath: string, sourceIdentifier: string): void {\n const nameCheck = validateFileName(deployPath);\n if (!nameCheck.valid) {\n throw ShipError.business(nameCheck.reason || 'Invalid file name');\n }\n\n if (isBlockedExtension(deployPath)) {\n throw ShipError.business(`File extension not allowed: \"${sourceIdentifier}\"`);\n }\n}\n","/**\n * @file Node.js-specific file utilities for the Ship SDK.\n * Provides helpers for recursively discovering, filtering, and preparing files for deploy in Node.js.\n */\nimport { getENV } from '../../shared/lib/env.js';\nimport type { PlatformLimits } from '@shipstatic/types';\nimport type { StaticFile, DeploymentOptions } from '../../shared/types.js';\nimport { calculateMD5 } from '../../shared/lib/md5.js';\nimport { filterJunk } from '../../shared/lib/junk.js';\nimport { validateDeployPath, validateDeployFile } from '../../shared/lib/security.js';\nimport { ShipError, isShipError, UNBUILT_PROJECT_MARKERS } from '@shipstatic/types';\nimport { optimizeDeployPaths } from '../../shared/lib/deploy-paths.js';\nimport { findCommonParent } from '../../shared/lib/path.js';\n\nimport * as fs from 'fs';\nimport * as path from 'path';\n\n\n/**\n * Recursive function to walk directory and return all file paths.\n * Includes symlink loop protection to prevent infinite recursion.\n * @param dirPath - Directory path to traverse\n * @param visited - Set of already visited real paths (for cycle detection)\n * @returns Array of absolute file paths in the directory\n */\nfunction findAllFilePaths(dirPath: string, visited: Set<string> = new Set()): string[] {\n const results: string[] = [];\n\n // Resolve the real path to detect symlink cycles\n const realPath = fs.realpathSync(dirPath);\n if (visited.has(realPath)) {\n // Already visited this directory (symlink cycle) - skip to prevent infinite loop\n return results;\n }\n visited.add(realPath);\n\n const entries = fs.readdirSync(dirPath);\n\n for (const entry of entries) {\n const fullPath = path.join(dirPath, entry);\n const stats = fs.statSync(fullPath);\n\n if (stats.isDirectory()) {\n const subFiles = findAllFilePaths(fullPath, visited);\n results.push(...subFiles);\n } else if (stats.isFile()) {\n results.push(fullPath);\n }\n }\n\n return results;\n}\n\n/**\n * Processes Node.js file and directory paths into an array of StaticFile objects ready for deploy.\n * Computes content paths relative to the upload root before filtering, so only the deployed\n * directory structure is evaluated — not the user's filesystem above it.\n * \n * @param paths - File or directory paths to scan and process.\n * @param options - Processing options (pathDetect, etc.).\n * @param platformLimits - Per-instance platform limits (file-size / count /\n * total-size caps) from the originating Ship's `GET /config` fetch. Passed\n * in rather than read from a module global so concurrent Ships against\n * different API URLs cannot clobber each other's caps.\n * @returns Promise resolving to an array of StaticFile objects.\n * @throws {ShipClientError} If called outside Node.js or if fs/path modules fail.\n */\nexport async function processFilesForNode(\n paths: string[],\n options: DeploymentOptions = {},\n platformLimits?: PlatformLimits\n): Promise<StaticFile[]> {\n if (getENV() !== 'node') {\n throw ShipError.business('processFilesForNode can only be called in Node.js environment.');\n }\n\n // Check input directories for unbuilt project markers before recursive walk\n for (const p of paths) {\n const absPath = path.resolve(p);\n try {\n if (fs.statSync(absPath).isDirectory()) {\n const marker = fs.readdirSync(absPath).find(e => UNBUILT_PROJECT_MARKERS.has(e));\n if (marker) {\n throw ShipError.business(`\"${marker}\" detected — deploy your build output (dist/, build/, out/), not the project folder`);\n }\n }\n } catch (e) {\n if (isShipError(e)) throw e;\n // Path errors handled in the existing flatMap below\n }\n }\n\n // 1. Discover all unique, absolute file paths from the input list\n const absolutePaths = paths.flatMap(p => {\n const absPath = path.resolve(p);\n try {\n const stats = fs.statSync(absPath);\n return stats.isDirectory() ? findAllFilePaths(absPath) : [absPath];\n } catch (error) {\n throw ShipError.file(`Path does not exist: ${p}`, { filePath: p });\n }\n });\n const uniquePaths = [...new Set(absolutePaths)];\n\n // 2. Determine base path for content paths (from INPUT paths, not discovered files)\n const inputAbsolutePaths = paths.map(p => path.resolve(p));\n const inputBasePath = findCommonParent(inputAbsolutePaths.map(p => {\n try {\n const stats = fs.statSync(p);\n return stats.isDirectory() ? p : path.dirname(p);\n } catch {\n return path.dirname(p);\n }\n }));\n\n // 3. Compute content paths (relative to upload root)\n const contentPaths = uniquePaths.map(absPath => {\n if (inputBasePath && inputBasePath.length > 0) {\n const rel = path.relative(inputBasePath, absPath);\n if (rel && typeof rel === 'string' && !rel.startsWith('..')) {\n return rel.replace(/\\\\/g, '/');\n }\n }\n return path.basename(absPath);\n });\n\n // 4. Optimize paths for deployment (strip common root, flatten)\n const deployFiles = optimizeDeployPaths(contentPaths, {\n flatten: options.pathDetect !== false\n });\n const deployPaths = deployFiles.map(f => f.path);\n\n // 5. Filter junk from deploy paths\n const filteredSet = new Set(filterJunk(deployPaths));\n if (filteredSet.size === 0) {\n return [];\n }\n\n // 6. Collect valid file pairs (absolute path for reading, deploy path for output)\n const validAbsPaths: string[] = [];\n const validDeployPaths: string[] = [];\n for (let i = 0; i < uniquePaths.length; i++) {\n if (filteredSet.has(deployPaths[i])) {\n validAbsPaths.push(uniquePaths[i]);\n validDeployPaths.push(deployPaths[i]);\n }\n }\n\n // 7. Process files into StaticFile objects\n const results: StaticFile[] = [];\n let totalSize = 0;\n if (!platformLimits) {\n throw ShipError.config(\n 'Platform limits not provided. processFilesForNode requires the limits ' +\n 'argument — pass `ship.getLimits()` result.'\n );\n }\n\n for (let i = 0; i < validAbsPaths.length; i++) {\n const filePath = validAbsPaths[i];\n const deployPath = validDeployPaths[i];\n \n try {\n // Security validation (shared with browser) — fail fast before any I/O\n validateDeployPath(deployPath, filePath);\n\n const stats = fs.statSync(filePath);\n\n // Skip empty files — R2 cannot store zero-byte objects\n if (stats.size === 0) {\n continue;\n }\n\n // Filename and extension validation (shared with browser)\n validateDeployFile(deployPath, filePath);\n\n // Validate file sizes\n if (stats.size > platformLimits.maxFileSize) {\n throw ShipError.business(`File ${filePath} is too large. Maximum allowed size is ${platformLimits.maxFileSize / (1024 * 1024)}MB.`);\n }\n totalSize += stats.size;\n if (totalSize > platformLimits.maxTotalSize) {\n throw ShipError.business(`Total deploy size is too large. Maximum allowed is ${platformLimits.maxTotalSize / (1024 * 1024)}MB.`);\n }\n\n const content = fs.readFileSync(filePath);\n const { md5 } = await calculateMD5(content);\n\n results.push({\n path: deployPath,\n content,\n size: content.length,\n md5,\n });\n } catch (error) {\n // Re-throw ShipError instances directly\n if (isShipError(error)) {\n throw error;\n }\n // Convert file system errors to ShipError with clear message\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw ShipError.file(`Failed to read file \"${filePath}\": ${errorMessage}`, { filePath });\n }\n }\n\n // Final validation\n if (results.length > platformLimits.maxFilesCount) {\n throw ShipError.business(`Too many files to deploy. Maximum allowed is ${platformLimits.maxFilesCount} files.`);\n }\n \n return results;\n}","/**\n * @file Main entry point for the Ship SDK.\n * \n * This is the primary entry point for Node.js environments, providing\n * full file system support and configuration loading capabilities.\n * \n * For browser environments, import from '@shipstatic/ship/browser' instead.\n */\n\n// Re-export everything from the Node.js index, including both named and default exports\nexport * from './node/index.js';\nexport { default } from './node/index.js';\n","/**\n * @file Base Ship SDK class — shared functionality across environments.\n *\n * The constructor is fully synchronous: an `ApiHttp` instance is built immediately\n * with whatever credentials the caller supplied (and, in Node, env vars merged in\n * by the subclass before `super()`). The only deferred work is the one-shot\n * `GET /config` fetch that hydrates platform limits — that's lazy and runs on\n * first API call via `ensureInitialized()`.\n *\n * Subclasses only override what genuinely differs per environment:\n * - `processInput()` — Node reads paths from disk; Browser handles `File[]`\n * - `getDeployBodyCreator()` — Node streams Buffers; Browser builds Blobs\n *\n * Everything else (auth state, resources, events, lazy platform-limits) lives here.\n */\n\nimport { ShipError } from '@shipstatic/types';\nimport type {\n Deployment,\n PlatformLimits,\n DeploymentResource,\n DomainResource,\n AccountResource,\n TokenResource,\n StaticFile,\n} from '@shipstatic/types';\n\nimport { ApiHttp } from './api/http.js';\nimport { resolveConfig } from './core/config.js';\nimport {\n createDeploymentResource,\n createDomainResource,\n createAccountResource,\n createTokenResource,\n type DeployInput,\n} from './resources.js';\nimport type {\n ShipClientOptions,\n ShipEvents,\n DeploymentOptions,\n DeployBodyCreator,\n} from './types.js';\n\n/**\n * Authentication state for the Ship instance.\n * Discriminated union ensures only one auth method is active at a time.\n */\ntype AuthState =\n | { type: 'token'; value: string }\n | { type: 'apiKey'; value: string }\n | null;\n\n/**\n * Abstract base class for Ship SDK implementations.\n */\nexport abstract class Ship {\n // Resource handles, created once at construction. Each is a thin facade\n // bound to `this.http` plus the lazy-init callback.\n public readonly deployments: DeploymentResource;\n public readonly domains: DomainResource;\n public readonly account: AccountResource;\n public readonly tokens: TokenResource;\n\n // The HTTP client and merged options are private — subclasses interact\n // with the base class through the abstract methods below, never by\n // reaching into these fields. Tests bypass via `(ship as any).http = ...`.\n private readonly http: ApiHttp;\n private readonly clientOptions: ShipClientOptions;\n\n // Lazy-init plumbing for the one-shot `GET /config` fetch.\n // `platformLimits` is INSTANCE state (not a module-level singleton): two\n // Ships against different `apiUrl`s — staging + prod, multi-tenant\n // orchestrators, n8n with multiple credentials — must not clobber each\n // other's limits. Each instance owns its hydrated copy.\n // `protected` so subclasses' `processInput` can pass it down to the\n // platform-specific file-validation utilities.\n private initPromise: Promise<void> | null = null;\n protected platformLimits: PlatformLimits | null = null;\n\n // Auth state — consulted dynamically on every request through `getAuthHeaders`.\n private auth: AuthState = null;\n\n constructor(options: ShipClientOptions = {}) {\n // SDK-boundary normalization: empty-string credentials are never valid,\n // and storing them would pollute `mergeDeployOptions` (which checks\n // `=== undefined`, not falsy) and silently suppress per-call defaults\n // — turning what should have been an authenticated deploy into an\n // anonymous PUBLIC_ACCOUNT deploy via the agent-token fallback.\n //\n // Empty strings reach here from shell-expansion of unset CI variables,\n // empty form fields in browser apps, and any other path that produces\n // `''` instead of `undefined`. Normalizing once at the SDK boundary\n // covers every entry point: CLI, Browser SDK, Node SDK, embedded\n // consumers, and direct base-class use in tests.\n options = {\n ...options,\n apiUrl: options.apiUrl || undefined,\n apiKey: options.apiKey || undefined,\n deployToken: options.deployToken || undefined,\n };\n this.clientOptions = options;\n\n // Initialize auth state from constructor options.\n // Deploy token outranks API key when both are provided.\n if (options.deployToken) {\n this.auth = { type: 'token', value: options.deployToken };\n } else if (options.apiKey) {\n this.auth = { type: 'apiKey', value: options.apiKey };\n }\n\n // Build the HTTP client once. The `getAuthHeaders` callback reads `this.auth`\n // dynamically on every request, so `setApiKey()` / `setDeployToken()` take\n // effect immediately without needing to rebuild the client.\n this.http = new ApiHttp({\n ...options,\n ...resolveConfig(options),\n getAuthHeaders: () => this.getAuthHeaders(),\n createDeployBody: this.getDeployBodyCreator(),\n });\n\n const ctx = {\n getApi: () => this.http,\n ensureInit: () => this.ensureInitialized(),\n };\n\n this.deployments = createDeploymentResource({\n ...ctx,\n processInput: (input, opts) => this.processInput(input, opts),\n clientDefaults: this.clientOptions,\n hasAuth: () => this.hasAuth(),\n });\n this.domains = createDomainResource(ctx);\n this.account = createAccountResource(ctx);\n this.tokens = createTokenResource(ctx);\n }\n\n // Environment-specific behavior.\n protected abstract processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;\n protected abstract getDeployBodyCreator(): DeployBodyCreator;\n\n /**\n * Lazy initialization — fetches platform limits (file size / count caps) once,\n * on the first API call. Subsequent calls reuse the resolved promise.\n */\n protected async ensureInitialized(): Promise<void> {\n if (!this.initPromise) {\n this.initPromise = this.fetchPlatformLimits();\n }\n return this.initPromise;\n }\n\n private async fetchPlatformLimits(): Promise<void> {\n try {\n this.platformLimits = await this.http.getLimits();\n } catch (error) {\n // Reset so the next API call can retry initialization.\n this.initPromise = null;\n throw error;\n }\n }\n\n /**\n * Ping the API server to check connectivity.\n */\n async ping(): Promise<boolean> {\n await this.ensureInitialized();\n return this.http.ping();\n }\n\n /**\n * Deploy project (convenience shortcut to `ship.deployments.upload()`).\n */\n async deploy(input: DeployInput, options?: DeploymentOptions): Promise<Deployment> {\n return this.deployments.upload(input, options);\n }\n\n /**\n * Get current account information (convenience shortcut to `ship.account.get()`).\n */\n async whoami() {\n return this.account.get();\n }\n\n /**\n * Get platform limits (max file size, file count, total size).\n * Reuses the response fetched during initialization. Per-instance state —\n * does not leak between concurrent Ships against different API URLs.\n */\n async getLimits(): Promise<PlatformLimits> {\n if (this.platformLimits) return this.platformLimits;\n await this.ensureInitialized();\n return this.platformLimits!;\n }\n\n on<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n this.http.on(event, handler);\n }\n\n off<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n this.http.off(event, handler);\n }\n\n /**\n * Set global headers included in every request.\n * Useful for injecting custom headers (e.g. for admin impersonation).\n */\n setHeaders(headers: Record<string, string>): void {\n this.http.setGlobalHeaders(headers);\n }\n\n /**\n * Clear all custom global headers.\n */\n clearHeaders(): void {\n this.http.setGlobalHeaders({});\n }\n\n /**\n * Sets the deploy token for authentication.\n * Overrides any previously set API key or deploy token.\n * @param token Deploy token (format: `token-<64-char-hex>`)\n */\n public setDeployToken(token: string): void {\n if (!token || typeof token !== 'string') {\n throw ShipError.business('Invalid deploy token provided. Deploy token must be a non-empty string.');\n }\n this.auth = { type: 'token', value: token };\n }\n\n /**\n * Sets the API key for authentication.\n * Overrides any previously set API key or deploy token.\n * @param key API key (format: `ship-<64-char-hex>`)\n */\n public setApiKey(key: string): void {\n if (!key || typeof key !== 'string') {\n throw ShipError.business('Invalid API key provided. API key must be a non-empty string.');\n }\n this.auth = { type: 'apiKey', value: key };\n }\n\n private getAuthHeaders(): Record<string, string> {\n if (!this.auth) return {};\n return { Authorization: `Bearer ${this.auth.value}` };\n }\n\n /**\n * Check whether authentication credentials are configured.\n * Used by resources to fail fast (or trigger the agent-token fallback) when\n * auth is required.\n */\n private hasAuth(): boolean {\n // useCredentials means cookies are used for auth — no explicit token needed.\n if (this.clientOptions.useCredentials) return true;\n return this.auth !== null;\n }\n}\n","/**\n * @file HTTP client for Ship API.\n */\nimport type {\n Deployment,\n DeploymentCreateResponse,\n DeploymentListResponse,\n PingResponse,\n PlatformLimits,\n Domain,\n DomainListResponse,\n DomainDnsResponse,\n DomainRecordsResponse,\n DomainValidateResponse,\n Account,\n SPACheckRequest,\n SPACheckResponse,\n StaticFile,\n TokenCreateResponse,\n TokenListResponse\n} from '@shipstatic/types';\nimport type { ApiDeployOptions, DeployBodyCreator, DomainSetResult, ShipClientOptions } from '../types.js';\nimport { ShipError, DEFAULT_API } from '@shipstatic/types';\nimport { SimpleEvents } from '../events.js';\nimport { validateLabels, validatePassword } from '../lib/validation.js';\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\nconst ENDPOINTS = {\n DEPLOYMENTS: '/deployments',\n DOMAINS: '/domains',\n TOKENS: '/tokens',\n ACCOUNT: '/account',\n LIMITS: '/limits',\n PING: '/ping',\n SPA_CHECK: '/spa-check'\n} as const;\n\nconst DEFAULT_REQUEST_TIMEOUT = 30000;\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\nexport interface ApiHttpOptions extends ShipClientOptions {\n getAuthHeaders: () => Record<string, string>;\n createDeployBody: DeployBodyCreator;\n}\n\ninterface RequestResult<T> {\n data: T;\n status: number;\n}\n\n// =============================================================================\n// HTTP CLIENT\n// =============================================================================\n\nexport class ApiHttp extends SimpleEvents {\n private readonly apiUrl: string;\n private readonly getAuthHeadersCallback: () => Record<string, string>;\n private readonly useCredentials: boolean;\n private readonly timeout: number;\n private readonly createDeployBody: DeployBodyCreator;\n private readonly deployEndpoint: string;\n private globalHeaders: Record<string, string> = {};\n\n constructor(options: ApiHttpOptions) {\n super();\n this.apiUrl = options.apiUrl || DEFAULT_API;\n this.getAuthHeadersCallback = options.getAuthHeaders;\n this.useCredentials = options.useCredentials ?? false;\n this.timeout = options.timeout ?? DEFAULT_REQUEST_TIMEOUT;\n this.createDeployBody = options.createDeployBody;\n this.deployEndpoint = options.deployEndpoint || ENDPOINTS.DEPLOYMENTS;\n }\n\n /**\n * Set global headers included in every request.\n * Priority: globalHeaders (lowest) < instance auth < per-request headers (highest)\n */\n setGlobalHeaders(headers: Record<string, string>): void {\n this.globalHeaders = headers;\n }\n\n // ===========================================================================\n // CORE REQUEST INFRASTRUCTURE\n // ===========================================================================\n\n /**\n * Execute HTTP request with timeout, events, and error handling\n */\n private async executeRequest<T>(\n url: string,\n options: RequestInit,\n operationName: string\n ): Promise<RequestResult<T>> {\n const headers = this.mergeHeaders(options.headers as Record<string, string>);\n const { signal, cleanup } = this.createTimeoutSignal(options.signal);\n\n const fetchOptions: RequestInit = {\n ...options,\n headers,\n credentials: this.useCredentials && !headers.Authorization ? 'include' : undefined,\n signal,\n };\n\n this.emit('request', url, fetchOptions);\n\n try {\n const response = await fetch(url, fetchOptions);\n cleanup();\n\n if (!response.ok) {\n throw await ShipError.fromHttpResponse(response, operationName);\n }\n\n this.emit('response', this.safeClone(response), url);\n const data = await this.parseResponse<T>(this.safeClone(response));\n return { data, status: response.status };\n } catch (error) {\n cleanup();\n // Normalize anything thrown above (fetch failure, abort, response error) into a ShipError.\n // fromFetchError passes existing ShipErrors through unchanged.\n const shipError = ShipError.fromFetchError(error, operationName);\n this.emit('error', shipError, url);\n throw shipError;\n }\n }\n\n /**\n * Simple request - returns data only\n */\n private async request<T>(url: string, options: RequestInit, operationName: string): Promise<T> {\n const { data } = await this.executeRequest<T>(url, options, operationName);\n return data;\n }\n\n /**\n * Request with status - returns data and HTTP status code\n */\n private async requestWithStatus<T>(url: string, options: RequestInit, operationName: string): Promise<RequestResult<T>> {\n return this.executeRequest<T>(url, options, operationName);\n }\n\n // ===========================================================================\n // REQUEST HELPERS\n // ===========================================================================\n\n private mergeHeaders(customHeaders: Record<string, string> = {}): Record<string, string> {\n return { ...this.globalHeaders, ...this.getAuthHeadersCallback(), ...customHeaders };\n }\n\n private createTimeoutSignal(existingSignal?: AbortSignal | null): { signal: AbortSignal; cleanup: () => void } {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n if (existingSignal) {\n const abort = () => controller.abort();\n existingSignal.addEventListener('abort', abort);\n if (existingSignal.aborted) controller.abort();\n }\n\n return {\n signal: controller.signal,\n cleanup: () => clearTimeout(timeoutId)\n };\n }\n\n private safeClone(response: Response): Response {\n try {\n return response.clone();\n } catch {\n return response;\n }\n }\n\n private async parseResponse<T>(response: Response): Promise<T> {\n if (response.headers.get('Content-Length') === '0' || response.status === 204) {\n return undefined as T;\n }\n return response.json() as Promise<T>;\n }\n\n // ===========================================================================\n // PUBLIC API - DEPLOYMENTS\n // ===========================================================================\n\n async deploy(files: StaticFile[], options: ApiDeployOptions = {}): Promise<DeploymentCreateResponse> {\n if (!files.length) {\n throw ShipError.business('No files to deploy');\n }\n for (const file of files) {\n if (!file.md5) {\n throw ShipError.file(`MD5 checksum missing for file: ${file.path}`, { filePath: file.path });\n }\n }\n\n // Fast-fail on definitely-invalid input before constructing a multipart body.\n validatePassword(options.password);\n const labels = validateLabels(options.labels);\n\n const flags = (options.build || options.prerender || options.spa)\n ? { build: options.build, prerender: options.prerender, spa: options.spa }\n : undefined;\n const { body, headers: bodyHeaders } = await this.createDeployBody(files, {\n labels,\n via: options.via,\n password: options.password,\n flags,\n });\n\n const authHeaders: Record<string, string> = {};\n if (options.deployToken) {\n authHeaders['Authorization'] = `Bearer ${options.deployToken}`;\n } else if (options.apiKey) {\n authHeaders['Authorization'] = `Bearer ${options.apiKey}`;\n }\n if (options.caller) {\n authHeaders['X-Caller'] = options.caller;\n }\n\n return this.request<DeploymentCreateResponse>(\n `${options.apiUrl || this.apiUrl}${this.deployEndpoint}`,\n { method: 'POST', body, headers: { ...bodyHeaders, ...authHeaders }, signal: options.signal || null },\n 'Deploy'\n );\n }\n\n async listDeployments(): Promise<DeploymentListResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}`, { method: 'GET' }, 'List deployments');\n }\n\n async getDeployment(id: string): Promise<Deployment> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}/${encodeURIComponent(id)}`, { method: 'GET' }, 'Get deployment');\n }\n\n async updateDeploymentLabels(id: string, labels: string[]): Promise<Deployment> {\n const normalized = validateLabels(labels);\n return this.request(\n `${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}/${encodeURIComponent(id)}`,\n { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ labels: normalized }) },\n 'Update deployment labels'\n );\n }\n\n async removeDeployment(id: string): Promise<void> {\n await this.request<void>(\n `${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}/${encodeURIComponent(id)}`,\n { method: 'DELETE' },\n 'Remove deployment'\n );\n }\n\n // ===========================================================================\n // PUBLIC API - DOMAINS\n // ===========================================================================\n // All domain methods accept FQDN (Fully Qualified Domain Name) as the `name` parameter.\n // The SDK does not validate or normalize - the API handles all domain semantics.\n\n async setDomain(name: string, deployment?: string, labels?: string[]): Promise<DomainSetResult> {\n const normalized = validateLabels(labels);\n const body: { deployment?: string; labels?: string[] } = {};\n if (deployment) body.deployment = deployment;\n if (normalized !== undefined) body.labels = normalized;\n\n const { data, status } = await this.requestWithStatus<Domain>(\n `${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}`,\n { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) },\n 'Set domain'\n );\n\n return { ...data, isCreate: status === 201 };\n }\n\n async listDomains(): Promise<DomainListResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}`, { method: 'GET' }, 'List domains');\n }\n\n async getDomain(name: string): Promise<Domain> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}`, { method: 'GET' }, 'Get domain');\n }\n\n async removeDomain(name: string): Promise<void> {\n await this.request<void>(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}`, { method: 'DELETE' }, 'Remove domain');\n }\n\n async verifyDomain(name: string): Promise<{ message: string }> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/verify`, { method: 'POST' }, 'Verify domain');\n }\n\n async getDomainDns(name: string): Promise<DomainDnsResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/dns`, { method: 'GET' }, 'Get domain DNS');\n }\n\n async getDomainRecords(name: string): Promise<DomainRecordsResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/records`, { method: 'GET' }, 'Get domain records');\n }\n\n async getDomainShare(name: string): Promise<{ domain: string; hash: string }> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/share`, { method: 'GET' }, 'Get domain share');\n }\n\n async validateDomain(name: string): Promise<DomainValidateResponse> {\n return this.request(\n `${this.apiUrl}${ENDPOINTS.DOMAINS}/validate`,\n { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ domain: name }) },\n 'Validate domain'\n );\n }\n\n // ===========================================================================\n // PUBLIC API - TOKENS\n // ===========================================================================\n\n async createToken(ttl?: number, labels?: string[]): Promise<TokenCreateResponse> {\n const normalized = validateLabels(labels);\n const body: { ttl?: number; labels?: string[] } = {};\n if (ttl !== undefined) body.ttl = ttl;\n if (normalized !== undefined) body.labels = normalized;\n\n return this.request(\n `${this.apiUrl}${ENDPOINTS.TOKENS}`,\n { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) },\n 'Create token'\n );\n }\n\n async listTokens(): Promise<TokenListResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.TOKENS}`, { method: 'GET' }, 'List tokens');\n }\n\n async removeToken(token: string): Promise<void> {\n await this.request<void>(`${this.apiUrl}${ENDPOINTS.TOKENS}/${encodeURIComponent(token)}`, { method: 'DELETE' }, 'Remove token');\n }\n\n async fetchAgentToken(): Promise<TokenCreateResponse> {\n return this.request<TokenCreateResponse>(\n `${this.apiUrl}${ENDPOINTS.TOKENS}/agent`,\n { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}) },\n 'Fetch agent token'\n );\n }\n\n // ===========================================================================\n // PUBLIC API - ACCOUNT & CONFIG\n // ===========================================================================\n\n async getAccount(): Promise<Account> {\n return this.request(`${this.apiUrl}${ENDPOINTS.ACCOUNT}`, { method: 'GET' }, 'Get account');\n }\n\n async getLimits(): Promise<PlatformLimits> {\n return this.request(`${this.apiUrl}${ENDPOINTS.LIMITS}`, { method: 'GET' }, 'Get limits');\n }\n\n async ping(): Promise<boolean> {\n const data = await this.request<PingResponse>(`${this.apiUrl}${ENDPOINTS.PING}`, { method: 'GET' }, 'Ping');\n return data?.success || false;\n }\n\n // ===========================================================================\n // PUBLIC API - SPA CHECK\n // ===========================================================================\n\n async checkSPA(files: StaticFile[], options: ApiDeployOptions = {}): Promise<boolean> {\n const indexFile = files.find(f => f.path === 'index.html' || f.path === '/index.html');\n if (!indexFile || indexFile.size > 100 * 1024) {\n return false;\n }\n\n let indexContent: string;\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(indexFile.content)) {\n indexContent = indexFile.content.toString('utf-8');\n } else if (typeof Blob !== 'undefined' && indexFile.content instanceof Blob) {\n indexContent = await indexFile.content.text();\n } else if (typeof File !== 'undefined' && indexFile.content instanceof File) {\n indexContent = await indexFile.content.text();\n } else {\n return false;\n }\n\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (options.deployToken) {\n headers['Authorization'] = `Bearer ${options.deployToken}`;\n } else if (options.apiKey) {\n headers['Authorization'] = `Bearer ${options.apiKey}`;\n }\n\n const body: SPACheckRequest = { files: files.map(f => f.path), index: indexContent };\n const response = await this.request<SPACheckResponse>(\n `${this.apiUrl}${ENDPOINTS.SPA_CHECK}`,\n { method: 'POST', headers, body: JSON.stringify(body) },\n 'SPA check'\n );\n\n return response.isSPA;\n }\n}\n","/**\n * Event system for Ship SDK\n * Lightweight, reliable event handling with proper error boundaries\n */\n\nimport type { ShipEvents } from './types.js';\n\n/**\n * Lightweight typed event emitter.\n *\n * Public API: `on()` / `off()`. `emit()` is internal — only the SDK\n * publishes events. Throwing handlers are evicted automatically and\n * surfaced as `error` events on the next tick.\n */\nexport class SimpleEvents {\n private handlers = new Map<string, Set<Function>>();\n\n /**\n * Add event handler\n */\n on<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n if (!this.handlers.has(event as string)) {\n this.handlers.set(event as string, new Set());\n }\n this.handlers.get(event as string)!.add(handler);\n }\n\n /**\n * Remove event handler \n */\n off<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n const eventHandlers = this.handlers.get(event as string);\n if (eventHandlers) {\n eventHandlers.delete(handler);\n if (eventHandlers.size === 0) {\n this.handlers.delete(event as string);\n }\n }\n }\n\n /**\n * Emit event (internal use only)\n * @internal\n */\n emit<K extends keyof ShipEvents>(event: K, ...args: ShipEvents[K]): void {\n const eventHandlers = this.handlers.get(event as string);\n if (!eventHandlers) return;\n\n // Snapshot handlers so a handler that mutates the set during iteration\n // (e.g. by removing itself) doesn't skip or duplicate calls.\n const handlerArray = Array.from(eventHandlers);\n\n for (const handler of handlerArray) {\n try {\n handler(...args);\n } catch (error) {\n // A throwing handler is treated as broken — drop it so we don't\n // repeatedly invoke it and re-emit the failure as an `error` event\n // for observability. Defer the re-emit so the next tick has a clean\n // call stack and we can't recurse if the error handler also throws.\n eventHandlers.delete(handler);\n\n if (event !== 'error') {\n setTimeout(() => {\n const err = error instanceof Error ? error : new Error(String(error));\n this.emit('error', err, String(event));\n }, 0);\n }\n }\n }\n }\n}","/**\n * @file Client-side input validation for SDK request boundaries.\n *\n * These validators run before request construction. Constants come from\n * `@shipstatic/types` (`PASSWORD_CONSTRAINTS`, `LABEL_CONSTRAINTS`,\n * `LABEL_PATTERN`) so the SDK and API agree on the rules.\n */\n\nimport {\n LABEL_CONSTRAINTS,\n LABEL_PATTERN,\n PASSWORD_CONSTRAINTS,\n ShipError,\n} from '@shipstatic/types';\n\n/**\n * Validate an optional deployment password.\n *\n * Absent → no-op (an unprotected deployment is a valid choice). Present →\n * must be a string within `PASSWORD_CONSTRAINTS` length bounds. Whitespace\n * is preserved verbatim — significant.\n */\nexport function validatePassword(value: unknown): void {\n if (value === undefined || value === null) return;\n if (typeof value !== 'string') {\n throw ShipError.validation('Password must be a string');\n }\n if (\n value.length < PASSWORD_CONSTRAINTS.MIN_LENGTH ||\n value.length > PASSWORD_CONSTRAINTS.MAX_LENGTH\n ) {\n throw ShipError.validation(\n `Password must be between ${PASSWORD_CONSTRAINTS.MIN_LENGTH} and ${PASSWORD_CONSTRAINTS.MAX_LENGTH} characters`,\n );\n }\n}\n\n/**\n * Validate and normalize an array of labels.\n *\n * Lowercases and trims each entry, enforces per-label length and pattern\n * (`LABEL_CONSTRAINTS` / `LABEL_PATTERN`), count cap, and uniqueness after\n * normalization. Returns the normalized array. An empty array is valid and\n * signals \"clear all labels\" on label-update operations.\n */\nexport function validateLabels(labels: string[]): string[];\nexport function validateLabels(labels: string[] | undefined | null): string[] | undefined;\nexport function validateLabels(labels: string[] | undefined | null): string[] | undefined {\n if (labels === undefined || labels === null) return undefined;\n if (labels.length === 0) return labels;\n\n if (labels.length > LABEL_CONSTRAINTS.MAX_COUNT) {\n throw ShipError.validation(\n `Maximum ${LABEL_CONSTRAINTS.MAX_COUNT} labels allowed`,\n );\n }\n\n const normalized = labels.map((label, i) => {\n if (typeof label !== 'string') {\n throw ShipError.validation(`Label at index ${i} must be a string`);\n }\n const cleaned = label.trim().toLowerCase();\n if (cleaned.length < LABEL_CONSTRAINTS.MIN_LENGTH) {\n throw ShipError.validation(\n `Labels must be at least ${LABEL_CONSTRAINTS.MIN_LENGTH} characters long`,\n );\n }\n if (cleaned.length > LABEL_CONSTRAINTS.MAX_LENGTH) {\n throw ShipError.validation(\n `Labels must be no more than ${LABEL_CONSTRAINTS.MAX_LENGTH} characters long`,\n );\n }\n if (!LABEL_PATTERN.test(cleaned)) {\n throw ShipError.validation(\n `Labels must start and end with alphanumeric characters, with optional separators (${LABEL_CONSTRAINTS.SEPARATORS}) between segments`,\n );\n }\n return cleaned;\n });\n\n const unique = [...new Set(normalized)];\n if (unique.length !== normalized.length) {\n throw ShipError.validation('Duplicate labels are not allowed');\n }\n\n return unique;\n}\n","/**\n * @file Cross-platform configuration helpers.\n *\n * Two pure helpers used by both Node and Browser:\n *\n * - `resolveConfig(options)` — applies the API-URL default. The Node Ship\n * calls this after merging env vars under the user's options; the Browser\n * Ship calls it directly (no ambient sources).\n * - `mergeDeployOptions(perCallOptions, clientDefaults)` — overlays\n * instance-level defaults under per-call overrides for a single deploy.\n *\n * Credential precedence is owned by callers, not this file:\n *\n * - SDK (Node): constructor args > `SHIP_*` env vars (see `node/index.ts`)\n * - SDK (Browser): constructor args only\n * - CLI: `--flag` > env > `.shiprc` / `package.json` (see `cli/create-client.ts`)\n */\n\nimport { DEFAULT_API, type ResolvedConfig } from '@shipstatic/types';\nimport type { ShipClientOptions, DeploymentOptions } from '../types.js';\n\nexport type { ResolvedConfig } from '@shipstatic/types';\n\n/**\n * Apply the API-URL default and project the credential triplet into a\n * `ResolvedConfig` shape. Optional fields are omitted (rather than set to\n * `undefined`) so spread merges downstream behave predictably.\n */\nexport function resolveConfig(options: ShipClientOptions = {}): ResolvedConfig {\n const result: ResolvedConfig = {\n apiUrl: options.apiUrl || DEFAULT_API,\n };\n if (options.apiKey !== undefined) result.apiKey = options.apiKey;\n if (options.deployToken !== undefined) result.deployToken = options.deployToken;\n return result;\n}\n\n/**\n * Overlay client-level defaults under per-call deploy options.\n *\n * Per-call options always win — they're the explicit override for a single\n * `deployments.upload()`. Defaults fill in only when the per-call option is\n * `undefined` (an explicit `null` / empty value passes through).\n */\nexport function mergeDeployOptions(\n options: DeploymentOptions,\n clientDefaults: ShipClientOptions,\n): DeploymentOptions {\n const result: DeploymentOptions = { ...options };\n\n if (result.apiUrl === undefined && clientDefaults.apiUrl !== undefined) {\n result.apiUrl = clientDefaults.apiUrl;\n }\n if (result.apiKey === undefined && clientDefaults.apiKey !== undefined) {\n result.apiKey = clientDefaults.apiKey;\n }\n if (result.deployToken === undefined && clientDefaults.deployToken !== undefined) {\n result.deployToken = clientDefaults.deployToken;\n }\n if (result.timeout === undefined && clientDefaults.timeout !== undefined) {\n result.timeout = clientDefaults.timeout;\n }\n if (result.maxConcurrency === undefined && clientDefaults.maxConcurrency !== undefined) {\n result.maxConcurrency = clientDefaults.maxConcurrency;\n }\n if (result.onProgress === undefined && clientDefaults.onProgress !== undefined) {\n result.onProgress = clientDefaults.onProgress;\n }\n if (result.caller === undefined && clientDefaults.caller !== undefined) {\n result.caller = clientDefaults.caller;\n }\n\n return result;\n}\n","/**\n * Ship SDK resource factory functions.\n */\nimport {\n ShipError,\n isShipError,\n ErrorType,\n type StaticFile,\n type DeployInput,\n type DeploymentResource,\n type DomainResource,\n type AccountResource,\n type TokenResource\n} from '@shipstatic/types';\n\nexport type {\n StaticFile,\n DeployInput,\n DeploymentResource,\n DomainResource,\n AccountResource,\n TokenResource\n};\nimport type { ApiHttp } from './api/http.js';\nimport type { ShipClientOptions, DeploymentOptions } from './types.js';\nimport { mergeDeployOptions } from './core/config.js';\nimport { detectAndConfigureSPA } from './lib/spa.js';\n\n/**\n * Shared context for all resource factories.\n */\nexport interface ResourceContext {\n getApi: () => ApiHttp;\n ensureInit: () => Promise<void>;\n}\n\n/**\n * Extended context for deployment resource.\n */\nexport interface DeploymentResourceContext extends ResourceContext {\n processInput: (input: DeployInput, options: DeploymentOptions) => Promise<StaticFile[]>;\n clientDefaults?: ShipClientOptions;\n hasAuth?: () => boolean;\n}\n\n/**\n * Upload deployment resource with all CRUD operations.\n */\nexport function createDeploymentResource(ctx: DeploymentResourceContext): DeploymentResource {\n const { getApi, ensureInit, processInput, clientDefaults, hasAuth } = ctx;\n\n return {\n upload: async (input: DeployInput, options: DeploymentOptions = {}) => {\n await ensureInit();\n\n const mergedOptions = clientDefaults\n ? mergeDeployOptions(options, clientDefaults)\n : options;\n\n // No credentials — deploy publicly via agent token (short-lived, IP-locked, under PUBLIC_ACCOUNT)\n if (hasAuth && !hasAuth() && !mergedOptions.deployToken && !mergedOptions.apiKey) {\n try {\n const api = getApi();\n const { secret } = await api.fetchAgentToken();\n mergedOptions.deployToken = secret;\n } catch (err) {\n if (isShipError(err) && err.type === ErrorType.RateLimit) {\n throw ShipError.rateLimit(\n 'public deploy rate limit exceeded, try again later or run \\'ship config\\' for a free account with higher limits'\n );\n }\n throw err;\n }\n }\n\n if (!processInput) {\n throw ShipError.config('processInput function is not provided.');\n }\n\n const apiClient = getApi();\n let staticFiles = await processInput(input, mergedOptions);\n staticFiles = await detectAndConfigureSPA(staticFiles, apiClient, mergedOptions);\n\n return apiClient.deploy(staticFiles, mergedOptions);\n },\n\n list: async () => {\n await ensureInit();\n return getApi().listDeployments();\n },\n\n get: async (id: string) => {\n await ensureInit();\n return getApi().getDeployment(id);\n },\n\n set: async (id: string, options: { labels: string[] }) => {\n await ensureInit();\n return getApi().updateDeploymentLabels(id, options.labels);\n },\n\n remove: async (id: string) => {\n await ensureInit();\n await getApi().removeDeployment(id);\n }\n };\n}\n\n/**\n * Create domain resource with all CRUD operations.\n *\n * @remarks\n * The `name` parameter in all methods is an FQDN (Fully Qualified Domain Name).\n * The SDK does not validate or normalize domain names - the API handles all domain semantics.\n */\nexport function createDomainResource(ctx: ResourceContext): DomainResource {\n const { getApi, ensureInit } = ctx;\n\n return {\n // INTENTIONAL DESIGN: The API does NOT support unlinking domains (setting deployment to null).\n // Once a domain is linked to a deployment, it must always have a deployment.\n // Supported: reserve (omit deployment), link, switch deployments atomically, delete entirely.\n // Not supported: unlink after linking (creates ambiguous state with no clear use case).\n // See npm/ship/CLAUDE.md \"Domain Write Semantics\" for full rationale.\n set: async (name: string, options: { deployment?: string; labels?: string[] } = {}) => {\n await ensureInit();\n return getApi().setDomain(name, options.deployment, options.labels);\n },\n\n list: async () => {\n await ensureInit();\n return getApi().listDomains();\n },\n\n get: async (name: string) => {\n await ensureInit();\n return getApi().getDomain(name);\n },\n\n remove: async (name: string) => {\n await ensureInit();\n await getApi().removeDomain(name);\n },\n\n verify: async (name: string) => {\n await ensureInit();\n return getApi().verifyDomain(name);\n },\n\n validate: async (name: string) => {\n await ensureInit();\n return getApi().validateDomain(name);\n },\n\n dns: async (name: string) => {\n await ensureInit();\n return getApi().getDomainDns(name);\n },\n\n records: async (name: string) => {\n await ensureInit();\n return getApi().getDomainRecords(name);\n },\n\n share: async (name: string) => {\n await ensureInit();\n return getApi().getDomainShare(name);\n }\n };\n}\n\n/**\n * Create account resource (whoami functionality).\n */\nexport function createAccountResource(ctx: ResourceContext): AccountResource {\n const { getApi, ensureInit } = ctx;\n\n return {\n get: async () => {\n await ensureInit();\n return getApi().getAccount();\n }\n };\n}\n\n/**\n * Create token resource for managing deploy tokens.\n */\nexport function createTokenResource(ctx: ResourceContext): TokenResource {\n const { getApi, ensureInit } = ctx;\n\n return {\n create: async (options: { ttl?: number; labels?: string[] } = {}) => {\n await ensureInit();\n return getApi().createToken(options.ttl, options.labels);\n },\n\n list: async () => {\n await ensureInit();\n return getApi().listTokens();\n },\n\n remove: async (token: string) => {\n await ensureInit();\n await getApi().removeToken(token);\n }\n };\n}\n","/**\n * @file SPA detection and auto-configuration utilities.\n *\n * Provides SPA detection and ship.json generation functionality\n * that can be used by both Node.js and browser environments.\n */\n\nimport { DEPLOYMENT_CONFIG_FILENAME, SPA_DEFAULT_CONFIG } from '@shipstatic/types';\nimport { calculateMD5 } from './md5.js';\nimport type { StaticFile, DeploymentOptions } from '../types.js';\nimport type { ApiHttp } from '../api/http.js';\n\n/**\n * Creates ship.json configuration for SPA projects.\n * @returns Promise resolving to StaticFile with SPA configuration\n */\nexport async function createSPAConfig(): Promise<StaticFile> {\n const configString = JSON.stringify(SPA_DEFAULT_CONFIG, null, 2);\n\n // Create content that works in both browser and Node.js environments\n let content: Buffer | Blob;\n if (typeof Buffer !== 'undefined') {\n // Node.js environment\n content = Buffer.from(configString, 'utf-8');\n } else {\n // Browser environment\n content = new Blob([configString], { type: 'application/json' });\n }\n\n const { md5 } = await calculateMD5(content);\n\n return {\n path: DEPLOYMENT_CONFIG_FILENAME,\n content,\n size: configString.length,\n md5\n };\n}\n\n/**\n * Detects SPA projects and auto-generates configuration.\n * This function can be used by both Node.js and browser environments.\n *\n * @param files - Array of StaticFiles to analyze\n * @param apiClient - HTTP client for API communication\n * @param options - Deployment options containing SPA detection settings\n * @returns Promise resolving to files array with optional SPA config added\n */\nexport async function detectAndConfigureSPA(\n files: StaticFile[],\n apiClient: ApiHttp,\n options: DeploymentOptions\n): Promise<StaticFile[]> {\n // Skip if disabled, config already exists, or server will handle detection\n if (options.spaDetect === false || options.spa || options.build || options.prerender || files.some(f => f.path === DEPLOYMENT_CONFIG_FILENAME)) {\n return files;\n }\n\n try {\n const isSPA = await apiClient.checkSPA(files, options);\n\n if (isSPA) {\n const spaConfig = await createSPAConfig();\n return [...files, spaConfig];\n }\n } catch (error) {\n // SPA detection failed, continue silently without auto-config\n }\n\n return files;\n}\n","/**\n * @file Ship SDK for Node.js environments.\n *\n * The Node-side `Ship` adds two things on top of the base class:\n * 1. Environment detection — refuses to construct outside Node.\n * 2. `SHIP_*` env-var resolution as the universal \"process boundary\" credential\n * source, mirroring the OpenAI / Anthropic SDK convention. Constructor\n * arguments win over env vars.\n *\n * The SDK does NOT read `~/.shiprc` or `package.json` `\"ship\"` keys — that's\n * the CLI's job (see `cli/shiprc.ts`). Keeping file resolution out of the SDK\n * is what lets embedded consumers (MCP, n8n, GitHub Action) safely write\n * `new Ship({})` for anonymous public deployments without inheriting the host\n * developer's personal credentials.\n */\n\nimport { Ship as BaseShip } from '../shared/base-ship.js';\nimport { ShipError } from '@shipstatic/types';\nimport { getENV } from '../shared/lib/env.js';\nimport { readEnvConfig } from './core/config.js';\nimport type {\n ShipClientOptions,\n Deployment,\n DeployInput,\n DeploymentOptions,\n StaticFile,\n DeployBodyCreator,\n} from '../shared/types.js';\nimport { createDeployBody } from './core/deploy-body.js';\n\n// Export all shared functionality\nexport * from '../shared/index.js';\n\n/**\n * Ship SDK Client for Node.js environments.\n *\n * @example\n * ```typescript\n * // Authenticated — explicit API key\n * const ship = new Ship({ apiKey: 'ship-xxxx' });\n *\n * // Authenticated — picks up SHIP_API_KEY from env\n * const ship = new Ship({});\n *\n * // Anonymous public deploy — works when neither constructor nor env provides creds\n * const ship = new Ship({});\n * await ship.deploy('./dist');\n * ```\n */\nexport class Ship extends BaseShip {\n constructor(options: ShipClientOptions = {}) {\n if (getENV() !== 'node') {\n throw ShipError.business('Node.js Ship class can only be used in Node.js environment.');\n }\n\n // Layer env vars under constructor options. The merged result is what the\n // base class sees, so auth state and the HTTP client are fully formed by\n // the time the constructor returns — no async config phase needed.\n //\n // `||` (not `??`) is deliberate: empty strings on `options` fall through\n // to env, matching the CLI's `mergeCliConfig` behavior and preventing the\n // surprising case where a caller passing `apiKey: ''` (e.g. from an\n // unset variable) silently suppresses a perfectly good `SHIP_API_KEY`.\n const env = readEnvConfig();\n super({\n ...options,\n apiUrl: options.apiUrl || env.apiUrl,\n apiKey: options.apiKey || env.apiKey,\n deployToken: options.deployToken || env.deployToken,\n });\n }\n\n /**\n * Deploy file or directory paths to ShipStatic. Convenience shortcut for\n * `ship.deployments.upload()`.\n *\n * Wrong-platform inputs (e.g. `File[]`) fail at compile time. For\n * platform-neutral code, use `ship.deployments.upload()`, which accepts\n * the wider `DeployInput` and validates at runtime — that asymmetry is\n * intentional: the convenience shortcut narrows; the resource-layer\n * contract stays platform-neutral.\n */\n async deploy(input: string | string[], options?: DeploymentOptions): Promise<Deployment> {\n return super.deploy(input, options);\n }\n\n protected async processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]> {\n // Normalize string to string[] and validate.\n const paths = typeof input === 'string' ? [input] : input;\n\n if (!Array.isArray(paths) || !paths.every(p => typeof p === 'string')) {\n throw ShipError.business('Invalid input type for Node.js environment. Expected string or string[].');\n }\n\n if (paths.length === 0) {\n throw ShipError.business('No files to deploy.');\n }\n\n const { processFilesForNode } = await import('./core/node-files.js');\n return processFilesForNode(paths, options, this.platformLimits ?? undefined);\n }\n\n protected getDeployBodyCreator(): DeployBodyCreator {\n return createDeployBody;\n }\n}\n\n// Default export (for `import Ship from '@shipstatic/ship'`)\nexport default Ship;\n\n// Node-only utilities (path-walking + MD5 over the local filesystem)\nexport { processFilesForNode } from './core/node-files.js';\n","/**\n * @file Environment variable resolution for the Node.js Ship SDK.\n *\n * The SDK has exactly one ambient credential source: process environment variables.\n * `SHIP_API_KEY`, `SHIP_DEPLOY_TOKEN`, and `SHIP_API_URL` are honored as the\n * universal \"process boundary\" — the same idiom used by the OpenAI and Anthropic\n * SDKs. Constructor arguments always win over env vars.\n *\n * File-based config (`~/.shiprc`, `package.json` `\"ship\"` key) is the CLI's\n * responsibility — see `src/node/cli/shiprc.ts`. The SDK does not read files,\n * which is what lets embedded consumers (MCP, n8n, GitHub Action) construct\n * `new Ship({})` for anonymous deployments without leaking the host developer's\n * personal credentials.\n */\n\nimport { z } from 'zod';\nimport type { ShipClientOptions } from '../../shared/types.js';\nimport { ShipError } from '@shipstatic/types';\nimport { getENV } from '../../shared/lib/env.js';\nimport { CREDENTIAL_FIELDS } from '../../shared/core/credential-schema.js';\n\n// `.strict()` matches the file-config schema. The `raw` object below is\n// constructed from a fixed set of keys, so .strict() doesn't catch user\n// typos here (env vars we don't read are simply never put into `raw` in\n// the first place). What it does catch is a *contributor* error — adding\n// a new env-var read without updating `CREDENTIAL_FIELDS` produces a clear\n// validation failure rather than a silently-stripped value. Nearly free\n// (one method call), and keeps both schemas reading the same.\nconst EnvConfigSchema = z.object(CREDENTIAL_FIELDS).strict();\n\n/**\n * Map a `ShipClientOptions` field name (camelCase) back to the env var that\n * supplied it (SCREAMING_SNAKE_CASE), so validation errors point users at\n * the actual variable they need to fix. Kept as an explicit table rather\n * than a regex because the set is small, fixed, and unambiguous.\n */\nconst ENV_VAR_BY_FIELD: Record<string, string> = {\n apiUrl: 'SHIP_API_URL',\n apiKey: 'SHIP_API_KEY',\n deployToken: 'SHIP_DEPLOY_TOKEN',\n};\n\n/**\n * Read `SHIP_*` environment variables and validate the result.\n *\n * Empty strings (CI/Docker often sets env vars to `\"\"` instead of unsetting them)\n * are normalized to `undefined` before validation, so they don't trigger zod's\n * \"min length 1\" check or accidentally override a valid constructor argument.\n *\n * Returns an empty object outside Node.js — browser/edge runtimes have no\n * `process.env` we should reach into.\n */\nexport function readEnvConfig(): Partial<ShipClientOptions> {\n if (getENV() !== 'node') return {};\n\n const raw = {\n apiUrl: process.env.SHIP_API_URL || undefined,\n apiKey: process.env.SHIP_API_KEY || undefined,\n deployToken: process.env.SHIP_DEPLOY_TOKEN || undefined,\n };\n\n try {\n return EnvConfigSchema.parse(raw);\n } catch (error) {\n if (error instanceof z.ZodError) {\n const issue = error.issues[0];\n const field = issue.path[0] as string | undefined;\n const envVar = (field && ENV_VAR_BY_FIELD[field]) ?? 'SHIP environment configuration';\n throw ShipError.config(`Invalid ${envVar}: ${issue.message}`);\n }\n throw ShipError.config('Invalid environment configuration');\n }\n}\n","/**\n * @file Single source of truth for credential field validation.\n *\n * Both the SDK env reader (`node/core/config.ts`) and the CLI file loader\n * (`node/cli/shiprc.ts`) import these — if we tighten or relax a rule\n * (e.g. enforcing the `ship-` prefix), both layers update together.\n *\n * Lives in its own file (not alongside `resolveConfig`) because it's a pure\n * data constant: tests that mock the runtime behavior of `resolveConfig` /\n * `mergeDeployOptions` shouldn't have to forward this through their mocks.\n */\n\nimport { z } from 'zod';\n\nexport const CREDENTIAL_FIELDS = {\n apiUrl: z.string().url().optional(),\n apiKey: z.string().min(1).optional(),\n deployToken: z.string().min(1).optional(),\n};\n","/**\n * Node.js-specific deploy body creation.\n */\nimport { ShipError } from '@shipstatic/types';\nimport type { StaticFile, DeployBody, DeployBodyContext } from '../../shared/types.js';\n\nexport async function createDeployBody(\n files: StaticFile[],\n context: DeployBodyContext = {},\n): Promise<DeployBody> {\n const { FormData, File } = await import('formdata-node');\n const { FormDataEncoder } = await import('form-data-encoder');\n\n const { labels, via, password, flags } = context;\n const formData = new FormData();\n const checksums: string[] = [];\n\n for (const file of files) {\n // 1. Validate content type\n if (!Buffer.isBuffer(file.content) && !(typeof Blob !== 'undefined' && file.content instanceof Blob)) {\n throw ShipError.file(`Unsupported file.content type for Node.js: ${file.path}`, { filePath: file.path });\n }\n\n // 2. Validate md5\n if (!file.md5) {\n throw ShipError.file(`File missing md5 checksum: ${file.path}`, { filePath: file.path });\n }\n\n // 3. Create File and append — API derives Content-Type from extension\n const fileInstance = new File([file.content], file.path, { type: 'application/octet-stream' });\n formData.append('files[]', fileInstance);\n checksums.push(file.md5);\n }\n\n formData.append('checksums', JSON.stringify(checksums));\n\n if (labels && labels.length > 0) formData.append('labels', JSON.stringify(labels));\n if (via) formData.append('via', via);\n if (password) formData.append('password', password);\n if (flags?.build) formData.append('build', 'true');\n if (flags?.prerender) formData.append('prerender', 'true');\n if (flags?.spa) formData.append('spa', 'true');\n\n const encoder = new FormDataEncoder(formData);\n const chunks = [];\n for await (const chunk of encoder.encode()) {\n chunks.push(Buffer.from(chunk));\n }\n const body = Buffer.concat(chunks);\n\n return {\n body: body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength) as ArrayBuffer,\n headers: {\n 'Content-Type': encoder.contentType,\n 'Content-Length': Buffer.byteLength(body).toString()\n }\n };\n}\n","/**\n * @file Shared SDK exports - environment agnostic.\n */\n\n// Core functionality\nexport * from './resources.js';\nexport * from './types.js';\nexport * from './api/http.js';\nexport * from './core/constants.js';\nexport * from './core/config.js';\nexport { Ship } from './base-ship.js';\n\n// Shared utilities\nexport * from './lib/md5.js';\nexport * from './lib/text.js';\nexport * from './lib/junk.js';\nexport * from './lib/deploy-paths.js';\nexport * from './lib/env.js';\nexport * from './lib/file-validation.js';\nexport * from './lib/security.js';\n\n// Re-export types from @shipstatic/types\nexport { ShipError, ErrorType } from '@shipstatic/types';\nexport type { PingResponse, Deployment, Domain, Account } from '@shipstatic/types';","/**\n * Utility functions for string manipulation.\n */\n\n/**\n * Simple utility to pluralize a word based on a count.\n * @param count The number to determine pluralization.\n * @param singular The singular form of the word.\n * @param plural The plural form of the word.\n * @param includeCount Whether to include the count in the returned string. Defaults to true.\n * @returns A string with the count and the correctly pluralized word.\n */\nexport function pluralize(\n count: number,\n singular: string,\n plural: string,\n includeCount: boolean = true\n): string {\n const word = count === 1 ? singular : plural;\n return includeCount ? `${count} ${word}` : word;\n}\n"],"mappings":"4mBAwTO,SAASA,EAAYC,EAAO,CAC/B,OAAQA,IAAU,MACd,OAAOA,GAAU,UACjB,SAAUA,GACVA,EAAM,OAAS,aACf,WAAYA,CACpB,CA4CO,SAASC,EAAmBC,EAAU,CACzC,IAAMC,EAAWD,EAAS,YAAY,GAAG,EACzC,GAAIC,IAAa,IAAMA,IAAaD,EAAS,OAAS,EAClD,MAAO,GACX,IAAME,EAAMF,EAAS,MAAMC,EAAW,CAAC,EAAE,YAAY,EACrD,OAAOE,GAAmB,IAAID,CAAG,CACrC,CAyBO,SAASE,GAAeJ,EAAU,CACrC,OAAOK,GAAsB,KAAKL,CAAQ,CAC9C,CAoBO,SAASM,EAAiBC,EAAU,CAEvC,OADiBA,EAAS,QAAQ,MAAO,GAAG,EAAE,MAAM,GAAG,EAAE,OAAO,OAAO,EACvD,KAAKC,GAAKC,EAAwB,IAAID,CAAC,CAAC,CAC5D,CA6CO,SAASE,GAAeC,EAAQ,CACnC,GAAI,CAACA,EAAO,WAAWC,EAAQ,MAAM,EACjC,MAAMC,EAAU,WAAW,4BAA4BD,EAAQ,MAAM,GAAG,EAE5E,GAAID,EAAO,SAAWC,EAAQ,aAC1B,MAAMC,EAAU,WAAW,mBAAmBD,EAAQ,YAAY,sBAAsBA,EAAQ,MAAM,MAAMA,EAAQ,UAAU,aAAa,EAE/I,IAAME,EAAUH,EAAO,MAAMC,EAAQ,OAAO,MAAM,EAClD,GAAI,CAAC,kB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E,oBAAAM,CAAoB,EAAI,KAAM,uCACtC,OAAOA,EAAoBF,EAAON,EAAS,KAAK,gBAAkB,MAAS,CAC7E,CAEU,sBAA0C,CAClD,OAAOS,EACT,CACF,EAGOC,GAAQX","names":["isShipError","error","isBlockedExtension","filename","dotIndex","ext","BLOCKED_EXTENSIONS","hasUnsafeChars","UNSAFE_FILENAME_CHARS","hasUnbuiltMarker","filePath","s","UNBUILT_PROJECT_MARKERS","validateApiKey","apiKey","API_KEY","ShipError","hexPart","validateDeployToken","deployToken","DEPLOY_TOKEN","validateApiUrl","apiUrl","url","isDeployment","input","isPlatformDomain","domain","platformDomain","isCustomDomain","extractSubdomain","generateDeploymentUrl","deployment","generateDomainUrl","serializeLabels","labels","deserializeLabels","labelsJson","parsed","DeploymentStatus","DomainStatus","AccountPlan","ErrorType","CLIENT_ONLY_ERROR_TYPES","ERROR_CATEGORIES","SERVER_PRODUCIBLE_ERROR_TYPES","AuthMethod","DEPLOYMENT_CONFIG_FILENAME","SPA_DEFAULT_CONFIG","DEFAULT_API","FileValidationStatus","LABEL_CONSTRAINTS","LABEL_PATTERN","PASSWORD_CONSTRAINTS","init_dist","__esmMin","t","_ShipError","type","message","status","details","authDetails","response","operationName","bodyType","json","obj","text","cause","op","resource","id","errorType","__setTestEnvironment","env","_testEnvironment","detectEnvironment","getENV","init_env","__esmMin","calculateMD5Browser","blob","SparkMD5","resolve","reject","chunks","currentChunk","spark","fileReader","loadNext","start","end","e","result","ShipError","calculateMD5Node","input","crypto","hash","fs","stream","err","chunk","calculateMD5","env","getENV","init_md5","__esmMin","init_env","init_dist","filterJunk","filePaths","options","p","hasUnbuiltMarker","ShipError","filePath","parts","basename","part","directorySegments","segment","JUNK_DIRECTORIES","junkDir","import_junk","init_junk","__esmMin","init_dist","findCommonParent","dirPaths","normalizedPaths","p","pathSegments","commonSegments","minLength","i","segment","segments","normalizeWebPath","path","init_path","__esmMin","optimizeDeployPaths","filePaths","options","path","normalizeWebPath","extractFileName","commonPrefix","findCommonDirectory","filePath","deployPath","prefixToRemove","pathSegments","commonSegments","minLength","segments","i","segment","init_deploy_paths","__esmMin","init_path","formatFileSize","bytes","decimals","k","sizes","i","validateFileName","filename","hasUnsafeChars","reservedNames","nameWithoutPath","validateFiles","files","config","errors","warnings","fileStatuses","issue","file","hasUnbuiltMarker","f","FileValidationStatus","totalSize","fileStatus","statusMessage","nameValidation","isBlockedExtension","validFiles","canDeploy","getValidFiles","allValidFilesReady","init_file_validation","__esmMin","init_dist","validateDeployPath","deployPath","sourceIdentifier","ShipError","validateDeployFile","nameCheck","validateFileName","isBlockedExtension","init_security","__esmMin","init_dist","init_file_validation","node_files_exports","__export","processFilesForNode","findAllFilePaths","dirPath","visited","results","realPath","entries","entry","fullPath","stats","subFiles","paths","options","platformLimits","getENV","ShipError","p","absPath","marker","e","UNBUILT_PROJECT_MARKERS","isShipError","absolutePaths","uniquePaths","inputAbsolutePaths","inputBasePath","findCommonParent","contentPaths","rel","deployPaths","optimizeDeployPaths","f","filteredSet","filterJunk","validAbsPaths","validDeployPaths","i","totalSize","filePath","deployPath","validateDeployPath","validateDeployFile","content","md5","calculateMD5","error","errorMessage","fs","path","init_node_files","__esmMin","init_env","init_md5","init_junk","init_security","init_dist","init_deploy_paths","init_path","src_exports","__export","API_KEY","AccountPlan","ApiHttp","AuthMethod","BLOCKED_EXTENSIONS","DEFAULT_API","DEPLOYMENT_CONFIG_FILENAME","DEPLOY_TOKEN","DeploymentStatus","DomainStatus","ErrorType","FileValidationStatus","JUNK_DIRECTORIES","LABEL_CONSTRAINTS","LABEL_PATTERN","PASSWORD_CONSTRAINTS","SPA_DEFAULT_CONFIG","Ship","ShipError","UNBUILT_PROJECT_MARKERS","UNSAFE_FILENAME_CHARS","__setTestEnvironment","allValidFilesReady","calculateMD5","createAccountResource","createDeploymentResource","createDomainResource","createTokenResource","node_default","deserializeLabels","extractSubdomain","filterJunk","formatFileSize","generateDeploymentUrl","generateDomainUrl","getENV","getValidFiles","hasUnbuiltMarker","hasUnsafeChars","isBlockedExtension","isCustomDomain","isDeployment","isPlatformDomain","isShipError","mergeDeployOptions","optimizeDeployPaths","pluralize","processFilesForNode","resolveConfig","serializeLabels","validateApiKey","validateApiUrl","validateDeployFile","validateDeployPath","validateDeployToken","validateFileName","validateFiles","__toCommonJS","init_dist","init_dist","SimpleEvents","event","handler","eventHandlers","args","handlerArray","error","err","init_dist","validatePassword","value","ShipError","PASSWORD_CONSTRAINTS","validateLabels","labels","LABEL_CONSTRAINTS","normalized","label","i","cleaned","LABEL_PATTERN","unique","ENDPOINTS","DEFAULT_REQUEST_TIMEOUT","ApiHttp","SimpleEvents","options","DEFAULT_API","headers","url","operationName","signal","cleanup","fetchOptions","response","ShipError","error","shipError","data","customHeaders","existingSignal","controller","timeoutId","abort","files","file","validatePassword","labels","validateLabels","flags","body","bodyHeaders","authHeaders","id","normalized","name","deployment","status","ttl","token","indexFile","f","indexContent","init_dist","resolveConfig","options","result","DEFAULT_API","mergeDeployOptions","clientDefaults","init_dist","init_dist","init_md5","createSPAConfig","configString","SPA_DEFAULT_CONFIG","content","md5","calculateMD5","DEPLOYMENT_CONFIG_FILENAME","detectAndConfigureSPA","files","apiClient","options","f","spaConfig","createDeploymentResource","ctx","getApi","ensureInit","processInput","clientDefaults","hasAuth","input","options","mergedOptions","mergeDeployOptions","api","secret","err","isShipError","ErrorType","ShipError","apiClient","staticFiles","detectAndConfigureSPA","id","createDomainResource","name","createAccountResource","createTokenResource","token","Ship","options","ApiHttp","resolveConfig","ctx","createDeploymentResource","input","opts","createDomainResource","createAccountResource","createTokenResource","error","event","handler","headers","token","ShipError","key","init_dist","init_env","import_zod","init_dist","init_env","import_zod","CREDENTIAL_FIELDS","EnvConfigSchema","CREDENTIAL_FIELDS","ENV_VAR_BY_FIELD","readEnvConfig","getENV","raw","error","issue","field","envVar","ShipError","init_dist","createDeployBody","files","context","FormData","File","FormDataEncoder","labels","via","password","flags","formData","checksums","file","ShipError","fileInstance","encoder","chunks","chunk","body","init_md5","pluralize","count","singular","plural","includeCount","word","init_junk","init_deploy_paths","init_env","init_file_validation","init_security","init_dist","init_node_files","Ship","options","getENV","ShipError","env","readEnvConfig","input","paths","p","processFilesForNode","createDeployBody","node_default"]}
|